Update Just Password In Model

Hi,

I haven’t used Yii much and wanted to know if this appraoch is ok for updating just my user’s password.

Controller


	public function actionUpdatePass($id){

		

		// Load model

		$model = $this->loadModel($id, 'User');

			

		if (isset($_POST['User'])) {


		// If old pass matches $_POST proceed

		if(hash_hmac('sha256', $_POST['User']['old_pass'], Yii::app()->params['encryptionKey']) === $model->pass)

		{


				// Hash new password

				$model->pass = hash_hmac('sha256', $_POST['User']['new_pass'], Yii::app()->params['encryptionKey']);

				

				if ($model->save()) {

					

										// Passwords did match

					Yii::app()->user->setFlash('success','<strong>Password Changed</strong>');


					$this->redirect(array('candidate/view', 'id' => $model->id, 'first_name'=> strtolower($model->first_name)));


				}

			} else {

			

			// Passwords didn't match

			Yii::app()->user->setFlash('danger','<strong>Incorrect Password</strong> - Please retry');

		}			

	} 




		$this->render('updatePass', array(

				'model' => $model,

				));

	}



I actually made an _update_pass.php form that just gave an old password and new password field.

And that was about right, I just wondered if that was ok? I know you can do whole User model update in one, but I wanted some separation.

Thanks

Jonny :slight_smile:

Looks good - you could also set a scenario and do validation/encryption in the model.





public function actionUpdatePass($id)

{

	$model = $this->loadModel($id, 'User');

	$model->setScenario('changePassword');


	if (isset($_POST['User']))

	{

		$model->attributes = $_POST['User'];


		if ($model->save())

		{

			Yii::app()->user->setFlash('success', 'Password updated successfully.');

			$this->redirect(array('project/index'));

		}

	}

 

	$this->render('updatePass', array(

		'model' => $model,

	));

}


<?php

class User extends CActiveRecord

{

    /**

     * @var string the new password set by the user

     */

    public $newPassword;


    /**

     *

     * @var string the confirmation of the new password

     */

    public $newPasswordRepeat;


    /**

     * Returns the static model of the specified AR class.

     * @return User the static model class

     */

    public static function model($className=__CLASS__)

    {

        return parent::model($className);

    }


    /**

     * @return string the associated database table name

     */

    public function tableName()

    {

        return '{{user}}';

    }


    /**

     * @return array validation rules for model attributes.

     */

    public function rules()

    {

        // NOTE: you should only define rules for those attributes that

        // will receive user inputs.

        return array(

			...

            array('newPassword, newPasswordRepeat', 'required', 'on' => 'changePassword'),

            array('newPassword', 'compare', 'compareAttribute' => 'newPasswordRepeat'),

            array('newPassword, newPasswordRepeat', 'safe', 'on' => 'changePassword'),

            array('newPassword', 'length', 'min' => 10),

            array('newPassword', 'match',

                'allowEmpty' => false,

                'pattern' => '^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$^',

                'message' => 'Passsword must contain at least: 1 uppercase letter (A-Z), 1 lowercase letter (a-z), and a digit (0-9)',

                'on' => 'changePassword'),

            array('password', 'uniquePassword',

                'on' => 'changePassword'),

        );

    }


    /**

     * Verifies the user's new password is not the same as their old one.

     * This is the uniquePassword validator call when validating a User

     */

    public function uniquePassword()

    {

        $user = Yii::app()->user->getModel();


        $newPassword = hashingAlgorithm($this->newPassword);


        if ($this->newPassword === $this->newPasswordRepeat)

        {

            if ($user->password === $newPassword)

            {

                $this->addError('password', 'Your new password cannot be the same as your old one.');

            }

        }

    }


    /**

     * @return array customized attribute labels (name=>label)

     */

    public function attributeLabels()

    {

        return array(

			...

            // Non DB fields

            'newPassword' => 'New Password',

            'newPasswordRepeat' => 'Confirm Password',

        );

    }




    public function beforeSave()

    {

        if ($this->getScenario() == 'changePassword')

            $this->password = hashingAlgorithm($this->newPassword);

        

        return parent::beforeSave();

    }




}



Matt

Thanks Matt