Search code examples
phpauthenticationyiiuser-management

Yii, best way to implement "user change of password"


I'm using Yii for an application, I'm writing a very simple user management, like registering, deleting and updating users... For updating the existing user I need to check the old password first before change it to the new inserted password. So here is the fields I have in the form:

username:----
old_password:---
new_password:---

and my user table looks like this:

id, username, password

How can I validate the old_password before updating it with the new_password? I know the usual php coding, but I want to know if there are any Yii tricks that does this automatically...

Thanks in advance


Solution

  • Its simple create a action that has logic for update pass.

    Make target for form to new action in this case actionChangePass and validate there the way you want .

    A rough example can be put like this

        public function actionChangePass($id)
        {  
        $user = loadModel($id)
        if(md5($_POST['User']['old_password']) === $user->password)
        {
           $user->setScenario('changePassword');
           $user->attributes = $_POST['User'];                
           $user->password = md5($_POST['User']['new_password']);
           if($user->save())
             Yii::app()->user->setFlash('passChanged', 'Your password has been changed <strong>successfully</strong>.');
        }            
        else
        {
          Yii::app()->user->setFlash('passChangeError', 'Your password was not changed because it did not matched the <strong>old password</strong>.');                    
        }  
     }
    

    Also make sure you have $old_password in your user User Model. Also you can do some validations in rules of model to make new password required

    there can be some different ways too but i do it like this

    Also create your custom validation scenario changePassword