I’m trying to allow people to change their password in my app (CakePHP 3.6), however, after I test this functionality I cannot login anymore.
The hash has changed in the database, just fine, but the password I used to create this hash, does not appear to be valid?
I am using the Cake\Auth\DefaultPasswordHasher
for creating the hashes.
The odd part is, that when I replace the new hash with the old hash, it works just fine, until I change my password again.
It can literally be the same password (of course, it’ll be outputting a different hash) and it still doesn’t work (it can’t be a typo either since I just copy-paste it from a notepad.
this is the (relevant) code that I use when changing the password:
$user_data = $this->Users
->find()
->where(['id'=> $this->Auth->user('id')])
->first();
$user = $this->Users->patchEntity($user_data,['password' => (new DefaultPasswordHasher())->hash($this->request->getData('new_password'))]);
if($this->Users->save($user)){
// yay
}else{
// nay
}
$this->request->getData('new_password')
does hold the right value of the new password, so that can’t be it.
And this is the (relevant) code for logging in:
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
UPDATE: I’ve commented out the saving of the hash (for simplicity’s sake) and added the following code after patching the entity:
var_dump((new DefaultPasswordHasher())->check($this->request->getData('new_password'),$user->password));
This returns bool(false)
, indicating that something seems to be going horribly wrong while hashing the password.
UPDATE 2:
using the following code, I can see that something goes horribly wrong while patching the user entity:
$hash = (new DefaultPasswordHasher())->hash($this->request->getData('new_password'));
$user = $this->Users->patchEntity($user_data,['password' => $hash]);
var_dump($user->password); // $2y$10$HhpJJUqZNjFdm6uMzF19J.ftjWSjp9SIzK8VSCTS.n/vjTNHQWp4G
var_dump($hash); // $2y$10$GjBy9M0yjBjUbZR3e9Unu.QrVayS5zPpmcbapx5Qk1JYif4a6YSQ2
UPDATE 3:
I changed no it doesn’t$user = $this->Users->patchEntity($user_data,['password' => $hash]);
with $user->password = $hash;
and now it seems to work just fine.
FINAL UPDATE:
we apparently have a _setPassword()
function in the user entity, so the reason why the hashes weren’t the same, is due to it being hashed twice.