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();
}
}