I am trying to match current password before if change. For that I have taken Auth password and then I matched it with current password. But it's returning always false.
Here is the controller code that I have tried
if ($this->request->is(['patch', 'post', 'put'])) {
$obj = new DefaultPasswordHasher;
$postpassword = $obj->hash($this->request->data['current_password']);
if($this->Auth->user('password') == $postpassword)
{
// code to save change password.
}
else
$this->Flash->error(__('The password you have entered does not match !'));
}
Here $postpassword hash working fine, but $this->Auth->user('password')
return value 1. How can I get auth password and match with $postpassword ?
Edit
I have get some knowledge then I have solve this problem like this way
$password = '$2y$10$pHbHu6xhNAw/v5HuQ1DSjOm5MPkqZukD1.532ACu7YLgD1ef9K7i2';
if ($this->request->is(['patch', 'post', 'put'])) {
$obj = new DefaultPasswordHasher;
$postpassword = $obj->check($this->request->data['current_password'], $password);
if($postpassword==1)
$this -> set('password',"hello");
}
Now I need just $this->Auth->user('password');
in controller.
Is it possible in cakephp auth component ?
Its pretty easy this way:
Insert this in your (Users)Table
:
use Cake\Auth\DefaultPasswordHasher;
use Cake\Validation\Validator;
Extend your function validationDefault(Validator $validator )
like the following:
public function validationDefault(Validator $validator ) {
$validator
->add('current_password','custom',[
'rule'=> function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if ((new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message'=>'The old password does not match the current password!',
])
->notEmpty('current_password');
return $validator;
}
And thats it! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With