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

后端 未结 4 1171
傲寒
傲寒 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:32

    I see that you validate and manipulate data in the controller. Doing this in a model is generally a better practice. I implemented similar functionality just a few days ago. My change_password() method looks somewhat like this:

    # app/controllers/users_controller.php
    function change_password() {
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->Session->setFlash('Password has been changed.');
                // call $this->redirect() here
            } else {
                $this->Session->setFlash('Password could not be changed.');
            }
        } else {
            $this->data = $this->User->findById($this->Auth->user('id'));
        }
    }
    

    And here's a stripped down version of the view used with that method:

    # app/views/users/change_password.ctp
    echo $this->Form->create('User');
    echo $this->Form->input('id');
    echo $this->Form->input('current_password');
    echo $this->Form->input('password1');
    echo $this->Form->input('password2');
    echo $this->Form->end('Submit');
    

    The code that does something interesting is in the model. I added the fields from the form to the validate property and wrote custom validation methods. This allows me to use password1 and password2 fields in any other place in the application, for example, on the registration form.

    # app/models/user.php
    var $validate = array(
        'current_password' => array(
            'rule' => 'checkCurrentPassword',
            'message' => '...'
        ),
        'password1' => array(
            'rule' => 'checkPasswordStrength',
            'message' => '...',
        ),
        'password2' => array(
            'rule' => 'passwordsMatch',
            'message' => '...',
        )
    );
    

    Finally, in the beforeSave() callback of the model I set password to the hash of password1 to prepare the data to be stored it in the database.

提交回复
热议问题