Cakephp 3:控制器中的当前密码匹配

Cakephp 3 : Current password match in controller

如果更改,我正在尝试匹配当前密码。为此,我使用了 Auth 密码,然后将其与当前密码匹配。但它 returning 总是错误的。

这是我试过的控制器代码

 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 !'));

  }

此处 $postpassword 哈希工作正常,但 $this->Auth->user('password') return 值为 1。我如何获得身份验证密码并与 $postpassword 匹配?

编辑

我得到了一些知识,然后我就这样解决了这个问题

$password     = 'y$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");
       }

现在我只需要 $this->Auth->user('password'); 在控制器中。 在 cakephp auth 组件中可以吗?

无需散列密码,Auth 将执行所有操作。

if ($this->request->is(['patch', 'post', 'put'])) {
      $obj = new DefaultPasswordHasher;

      if($this->Auth->user('password') == $this->request->data['current_password'])
      {
         // code to save change password.                          
      }
      else
      $this->Flash->error(__('The password you have entered does not match !'));

  }

身份验证适配器在返回已识别用户的数据之前删除密码,但是您应该收到 null,而不是 1

无论如何,如果您需要该信息,则必须手动阅读,例如

$Table->get($this->Auth->user('id'))->password

但是,正如已经 一样,最好使用验证或应用程序规则来完成这些工作。

参见示例

这样很简单:

将此插入您的 (Users)Table :

use Cake\Auth\DefaultPasswordHasher;
use Cake\Validation\Validator;

像下面这样扩展你的 function validationDefault(Validator $validator )

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;
}

就是这样! :)