我编写了一个用户控制器,如果提交的用户名和密码(用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
阵列中没有任何设置。
我该如何解决这个问题?
如果您使用cakePHP 2.x,则可以在模型的回调函数中将密码加密设置为beforeSave()为
<?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;
}
?>
有关更多信息,请单击链接。如果您仍想在控制器中加密密码,则可以使用类似的代码。
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或更高版本,请遵循此处的文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句