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

时间:2015-08-28 04:32:30

标签: cakephp cakephp-3.0

如果更改,我会尝试匹配当前密码。为此我已经使用Auth密码,然后我将其与当前密码匹配。但它的回归总是错误的。

这是我试过的控制器代码

 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')返回值1.我如何获得auth密码并与$ postpassword匹配?

修改

我已经掌握了一些知识然后我就这样解决了这个问题

$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");
       }

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

3 个答案:

答案 0 :(得分:3)

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

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

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

但是,正如已经mentioned in the comments一样,使用验证或应用程序规则可以做得更好。

例如,参见 DefaultPasswordHasher generating different hash for the same value

答案 1 :(得分:3)

这很简单:

将其插入(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;
}

就是这样! :)

答案 2 :(得分:0)

无需哈希密码,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 !'));

  }