Is there a better way to change user password in cakephp using Auth?

后端 未结 4 1166
傲寒
傲寒 2020-12-13 01:25

I am learning cakephp by myself. I tried to create a user controller with a changepassword function. It works, but I am not sure if this is the best way, and I could not goo

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 01:54

    The solution provided by Mike is great, but he left out the "checkCurrentPassword" function. Here is an example of that function you can place in your Model:

    # app/models/user.php
    public function checkCurrentPassword($data) {
        $this->id = AuthComponent::user('id');
        $password = $this->field('password');
        return(AuthComponent::password($data['current_password']) == $password);
    }
    

    This solution gets the current user ID from the Auth component and changes the model to point to that particular user. Then it compares the hash of the current_password entered on the form with the hashed password stored for that user.

    Also, here is the beforeSave function you can use to hash the new password:

    # app/models/user.php
    public function beforeSave($options = array()) {
        if (isset($this->data[$this->alias]['password1'])) {
            $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password1']);
        }       
        return true;
    }
    

提交回复
热议问题