Best Way To Implement User Change Password ?

Hii…

I would like to know how to implement a change password functionality. I have searched through forum n google and have not found a good one yet.

Fields :




Current Password

New Password

Confirm New Password



Encryption :




md5



Any help would be great…

You have to start with a new form.

Example,


<?php


class ChangePasswordForm extends CFormModel

{

  public $currentPassword;

  public $newPassword;

  public $newPassword_repeat;

  private $_user;

  

  public function rules()

  {

    return array(

      array(

        'currentPassword', 'compareCurrentPassword'

      ),

      array(

        'currentPassword, newPassword, newPassword_repeat', 'required',

        'message'=>'Introduzca su {attribute}.',

      ),

      array(

        'newPassword_repeat', 'compare',

        'compareAttribute'=>'newPassword',

        'message'=>'La contraseña nueva no coincide.',

      ),

      

    );

  }

  

  public function compareCurrentPassword($attribute,$params)

  {

    if( md5($this->currentPassword) !== $this->_user->password )

    {

      $this->addError($attribute,'La contraseña actual es incorrecta');

    }

  }

  

  public function init()

  {

    $this->_user = User::model()->findByAttributes( array( 'username'=>Yii::app()->User->username ) );

  }

  

  public function attributeLabels()

  {

    return array(

      'currentPassword'=>'Contraseña actual',

      'newPassword'=>'Nueva contraseña',

      'newPassword_repeat'=>'Nueva contraseña (Repetir)',

    );

  }

  

  public function changePassword()

  {

    $this->_user->password = $this->newPassword;

    if( $this->_user->save() )

      return true;

    return false;

  }

}

Controller:




class UserController extends Controller

{

  public function filters()

  {

    return array(

        'accessControl',

    );

  }

  

  public function accessRules()

  {

    return array(

      array(

        'deny',

        'actions'=>array('ChangePassword'),

        // Denegar a usuarios anónimos.

        'users'=>array('?'),

        // Solo disponible para autenticacion con MySQL

        'expression'=>"Yii::app()->params['authSystem']['type'] === 'MySqlUserIdentity'",

      ),

    );

  }

 

 public function actionChangePassword()

  {

    $model = new ChangePasswordForm;

    if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

    {

      echo CActiveForm::validate($model);

      Yii::app()->end();

    }


    // collect user input data

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

    {

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

      // Validar input del usuario y cambiar contraseña.

      if($model->validate() && $model->changePassword())

      {

       Yii::app()->user->setFlash('success', '<strong>Éxito!</strong> Su contraseña fue cambiada.');

       $this->redirect( $this->action->id );

      }

    }

    // Mostrar formulario de cambio de contraseña.

    $this->render('changePassword',array('model'=>$model));

  }

}

View:




<?php

/* @var $this SiteController */

/* @var $model LoginForm */

/* @var $form CActiveForm  */


$this->pageTitle=Yii::app()->name . ' - Cambiar contraseña.';

?>

<div id='box-logo'>

  <div id='logo-sw-270x60'></div>

</div>

<h2>Cambiar contraseña</h2>

<?php /** @var BootActiveForm $form */

$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(

    'id'=>'changePassword-form',

    'inlineErrors'=>true,

    'enableClientValidation'=>true,

    'clientOptions'=>array(

      'validateOnSubmit'=>true,

    ),

    'htmlOptions'=>array('class'=>'well'),

)); ?>




<?php echo $form->passwordFieldRow($model, 'currentPassword', array('class'=>'span3','placeholder'=>'Contraseña actual...')); ?>

<?php echo $form->passwordFieldRow($model, 'newPassword', array('class'=>'span3','placeholder'=>'Contraseña nueva...')); ?>

<?php echo $form->passwordFieldRow($model, 'newPassword_repeat', array('class'=>'span3','placeholder'=>'Contraseña nueva (repetir)...')); ?>

</br>

<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'label'=>'Enviar', 'type'=>'primary')); ?>

<?php $this->endWidget(); ?>

<?php 

  $this->widget('bootstrap.widgets.TbAlert', array(

      'block'=>true, // display a larger alert block?

      'fade'=>true, // use transitions?

      'closeText'=>'&times;', // close link text - if set to false, no close link is displayed

      'alerts'=>array( // configurations per alert type

        'success'=>array(

          'block'=>true,

          'fade'=>true,

          'closeText'=>'&times;',

        ), // success, info, warning, error or danger

      ),

    )

  );

?>

In User Model, called at changePassword method in ChangePasswordForm model, you need to do this:




public function beforeSave()

  {

    $this->password = md5($this->password);

    return true;

  }

Thanks, this solution of such kind issue is working good!

Check out my usr module. Get the source code and see how it performs password change. I call it password recovery.

You can copy the code or write your own based on this. Or just use the whole module if it suits your needs.




protected function beforeSave()

{

	if(parent::beforeSave())

	{

		if($this->isNewRecord)

		{

			$this->password=md5($this->password);

		}else{

			$this->user=User::model()->findByPk($this->id);

			if($this->password!=$this->user->password){

				$this->password=md5($this->password);

			}

		}

		return true;

	}

	else

		return false;

}



i m implementing change password functionality. and add init() function code in this way…

public function init()

{


    &#036;this-&gt;_user=user::model()-&gt;findByAttributes(array('web_login'=&gt;Yii::app()-&gt;user-&gt;web_login));


}

when i put this function code in conroller it raises an erroe like below:-

include(user.php): failed to open stream: No such file or directory

what should i do in this case??

thanks.

Hey Follow this tutorial for best help -

http://www.yiiframework.com/wiki/718/change-password-with-tbactiveform