我编写了一个用户控制器,如果提交的用户名和密码(用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
数组中没有任何设置。
我该如何解决这个问题?
答案 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。
进行操作