Cakephp 2.x Auth Component : Change password

Changing password of any user is easy if you are using Auth Component. I have been Using Auth Component for many of my projects developed in Cakephp.  Below are the steps for password change functionality of Auth component in CakePHP 2.x.
Create a new function called pass() in the controller .( users controller in my case )
( you can  name the function anything. )
    public function pass() {
        if ($this->Auth->user('id')) {   // Just to  make sure User is logged 
            $this->User->id = $this->Auth->user('id');  // Set User Id
            if (!$this->User->exists()) {
                throw new NotFoundException(__('Invalid user'));
            }
            if ($this->request->is('post')) {
                if ($this->User->save($this->request->data)) {
                    $this->Session->setFlash('Password has been changed.');
                } else {
                    $this->Session->setFlash('Password could not be changed.');
                }
            } else {
//                $this->data = $this->User->findById($this->Auth->user('id'));
            }
        }
    }

 

Setting user Id is important here or a new record is created every time you try to change password. You can either pass id through query params or you can get it from Auth. In the above example User Id is taken from Auth.
 Now create a view file with function name in the views/{controller_name}/ directory. In this case it would be views/Users/pass.ctp
Create a form to change password in that view file
<div>
    <?php echo $this->Session->flash(); ?>
<?php echo $this->Form->create('User'); ?>
     <fieldset>
          <legend><?php echo __('Change Password'); ?></legend>
     <?php
                echo $this->Form->input('current_password',array('label'=>'Old password','value'=>'','type'=>'password'));
                echo $this->Form->input('password1',array('label'=>'New password','type'=>'password'));
                echo $this->Form->input('password2',array('label'=>'Confirm password','type'=>'password'));
     ?>
     </fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

 

As we are not redirecting to other method or controller . it is suggested to show message so user can know password is changed. 

Now comes the magic in the model. We are asking for current password. And if that is correct we are going to check if both new passwords match. If they match change password and display message.
to the $validate array in your model add this 

var $validate = array(
    'current_password' => array(
        'rule' => 'checkCurrentPassword',
        'message' => '...'
    ),
    'password1' => array(
        'rule' => '',
        'message' => '...',
    ),
    'password2' => array(
        'rule' => 'passwordsMatch',
        'message' => '...',
    )
);

 

 So we need to create two functions one for checking current password and other to check if both passwords matches or not.