我试图在用户忘记旧密码时为其设置新密码。 我有代码,它正在工作(创建一个新的随机密码,更新数据库并通过电子邮件将其发送到输入的电子邮件)然而,当我尝试使用新密码登录时,它显示无效密码(显然是旧密码)也是不正确的)
我的代码是:
function forgot() {
if(!empty($this->data)) {
$user = $this->User->findByEmail($this->data['User']['email']);
$user_email = $this->data['User']['email'];
if($user) {
$user['User']['tmp_password'] = $this->User->createTempPassword(10);
$user['User']['password'] = $this->Auth->password($user['User']['tmp_password']);
if($this->User->save($user, false)) {
$this->User->set('User.password', $user['User']['password'], array('User.email' => $user_email));
$this->User->save();
$this->__sendPasswordEmail($user,$user['User']['tmp_password']);
$this->Session->setFlash('An email has been sent with your new password.');
$this->redirect($this->referer());
}
} else {
$this->Session->setFlash('No user was found with the submitted email address.');
}
}
}
public function beforeSave($options = array()) {
// hash our password
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
// if we get a new password, hash it
if (isset($this->data[$this->alias]['password_update']) && !empty($this->data[$this->alias]['password_update'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password_update']);
}
// fallback to our parent
return parent::beforeSave($options);
}
function createTempPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
我读了几个类似的问题,我发现密码哈希可能是一个问题,但我不知道我的代码在哪里交互,因为我使用相同的哈希方法。 (你可能会问为什么我用$ this-&gt;用户 - &gt;设置/保存 - 好吧,我只是在试着弄清楚问题,不是那个。)
密码如下:BT9DPRsN - bcfbde69a31197d18589e81dd41af6dbc3c21557
谢谢。
答案 0 :(得分:1)
对此行发表评论,它将适用于您$user['User']['password'] = $this->Auth->password($user['User']['tmp_password']);
这背后的原因是因为您已经在cakephp回调函数beforeSave
中对密码进行了哈希处理,每当您尝试在数据库中保存密码字段时,它首先将其哈希,然后保存。希望它有所帮助。
答案 1 :(得分:0)
我认为你有两次哈希密码,
Controller的beforeSave()中的第一个和Model(AppModel或User)的beforeSave()中的第二个
你应该使用它一次,(可以在最近的Controller中清除语句返回beforeSave()或在AppModel中仅定义beforeSave())。
http://rao5s.vn