Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3 : Current password match in controller

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 ?

like image 302
Alimon Karim Avatar asked Mar 15 '23 22:03

Alimon Karim


1 Answers

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! :)

like image 88
Dorian Rec Avatar answered Mar 25 '23 03:03

Dorian Rec