I'm trying to set a new password to users when they forget the old one. I have the code, it's working ( Creates a new random password, updates the database and sends it by email to the entered email ) however when I try to login with the new password it says invalid password ( Obviously the old one is incorrect as well )
My code is :
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
}
I read a few similar questions and I've seen that password hashing might be a problem but I don't see where does that interacts in my code because I use the same hashing method. (You might ask why I used $this->User->set / Save - Well, I was just playing around try to figure out the issue, wasn't that. )
Password be like : BT9DPRsN - bcfbde69a31197d18589e81dd41af6dbc3c21557
Thank you.
createTempPassword()
for better understanding, but i guess it solved your problem$user['User']['password'] = $this->Auth->password($user['User']['tmp_password']);