Auth登录在cakephp中不起作用

时间:2013-10-18 18:36:05

标签: php cakephp authentication

我编写了一个用户控制器,如果提交的用户名和密码(用cakephp的Security :: hash()=>加密,例如6b0deec0d563224524da45691584643bc78c96ea加密,没有其他散列设置),则应该登录用户。数据库。但它不起作用,我不知道为什么。

这是 UsersController.php

的摘录
public function add() {
    $this->set("title_for_layout", "Register");

    if($this->request->is("post")) {
        $this->User->set($this->request->data);

    if($this->User->save(array("password" => Security::hash($this->request->data["User"]["password"])))) {
            $this->Session->setFlash(__("Successfully registred."), "flash_success");
            $this->redirect("/login");
    } else {
        $this->Session->setFlash(__("Validation failed."), "flash_danger");
    }
    }
}

注册工作正常,并且在数据库中创建了一行,其中我的列“username”包含普通用户名,例如“myuser”和“password”,其中包含散列字符串。我不认为这个问题可以解决。

这是我的 UsersController.php

的另一个片段
public function login() {
    $this->set("title_for_layout", "Login");

    if($this->request->is("post")) {
        if($this->Auth->login()) {
            $this->Session->setFlash("Login successfull.", "flash_success");
        } else {
            $this->Session->setFlash("Login failed.", "flash_danger");
        }
    }
}

以下是 login.ctp

视图
<?php echo $this->Form->create('User'); ?>
<?= $this->Form->input("username"); ?>
<?= $this->Form->password("password"); ?>
<?= $this->Form->end("submit"); ?>

这是我的问题:登录总是失败。另外,我在$component数组中没有任何设置。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果您正在使用cakePHP 2.x,那么您可以在模型的回调函数中设置密码加密,然后将其保存为

<?php
// app/Model/User.php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {

// ...

public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

?>

有关详细信息,请参阅link。如果您仍想在控制器中加密密码,那么您可以使用类似的代码。

public function add() {
    $this->set("title_for_layout", "Register");

    if($this->request->is("post")) {
        $this->User->set($this->request->data);

    if($this->User->save(array("password" => $this->Auth->password($this->request->data["User"]["password"])))) {
            $this->Session->setFlash(__("Successfully registred."), "flash_success");
            $this->redirect("/login");
    } else {
        $this->Session->setFlash(__("Validation failed."), "flash_danger");
    }
    }
}

?>

如果您正在使用cakePHP 2.4或更高版本,请按照文档here

进行操作
相关问题