Yii2 user change own password
Yii2 framework generate password hashed format.
The following will hash the password. Do what you need with it:
- Yii::$app->security->generatePasswordHash($password);
This was taken from the setPassword() function in the advanced app. Source: yii2-app-advanced/User.php at master · yiisoft/yii2-app-advanced · GitHub
Steps
/backend/models/ChangePasswordForm.php
<?php
namespace backend\models;
use Yii;
use yii\base\InvalidParamException;
use yii\base\Model;
use common\models\User;
/**
* Change password form for current user only
*/
class ChangePasswordForm extends Model
{
public $id;
public $password;
public $confirm_password;
/**
* @var \common\models\User
*/
private $_user;
/**
* Creates a form model given a token.
*
* @param string $token
* @param array $config name-value pairs that will be used to initialize the object properties
* @throws \yii\base\InvalidParamException if token is empty or not valid
*/
public function __construct($id, $config = [])
{
$this->_user = User::findIdentity($id);
if (!$this->_user) {
throw new InvalidParamException('Unable to find user!');
}
$this->id = $this->_user->id;
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['password','confirm_password'], 'required'],
[['password','confirm_password'], 'string', 'min' => 6],
['confirm_password', 'compare', 'compareAttribute' => 'password'],
];
}
/**
* Changes password.
*
* @return boolean if password was changed.
*/
public function changePassword()
{
$user = $this->_user;
$user->setPassword($this->password);
$user->password_encrypt= base64_encode($this->password);
return $user->save(false);
}
}
/backend/controllers/SiteController.php
add this code
public function actionChangepassword()
{
$id = \Yii::$app->user->id;
//user details..
$user = $this->findModeluser($id);
try {
$model = new \backend\models\ChangePasswordForm($id);
} catch (InvalidParamException $e) {
throw new \yii\web\BadRequestHttpException($e->getMessage());
}
if ($model->load(\Yii::$app->request->post()) && $model->validate() && $model->changePassword()) {
\Yii::$app->session->setFlash('success', 'Password Changed!');
}
return $this->render('changePassword', [
'model' => $model,
'user' => $user,
]);
}
/backend/views/site/changePassword.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\DetailView;
use backend\modules\tools\models\Center;
$user->subcenter=Center::getCenter($user->ccid);
$this->title = 'View or Change User Password';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-changePassword box box-body table-responsive">
<?= DetailView::widget([
'model' => $user,
'attributes' => [
'id',
'first_name',
'subcenter',
'username',
'email'
],
]) ?>
<div class="lb-box-header lb-with-border">
<h4 class="lb-box-title"><span class="glyphicon glyphicon-user"></span> Change your password</h4>
</div>
<div class="box-body lb-bgcolor" style="padding: 20px 0px 0px 20px;">
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-6 lb-div-width1">
<?= Html::activeLabel($model, 'password') ?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6 lb-div-width1">
<?= $form->field($model, 'password')->passwordInput()->label(FALSE) ?>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-6 lb-div-width1">
<?= Html::activeLabel($model, 'confirm_password') ?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6 lb-div-width1">
<?= $form->field($model, 'confirm_password')->passwordInput()->label(FALSE) ?>
</div>
</div>
<div class="form-group" align="center">
<?= Html::submitButton('Change', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
Another method for use old password
ChangePasswordForm model like this include old password.
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use app\models\Login;
class ChangePasswordForm extends Model{
public $oldpass;
public $newpass;
public $repeatnewpass;
public function rules(){
return [
[['oldpass','newpass','repeatnewpass'],'required'],
['oldpass','findPasswords'],
['repeatnewpass','compare','compareAttribute'=>'newpass'],
];
}
public function findPasswords($attribute, $params){
$user = Login::find()->where([
'username'=>Yii::$app->user->identity->username
])->one();
$password = $user->password;
if($password!=$this->oldpass)
$this->addError($attribute,'Old password is incorrect');
}
public function attributeLabels(){
return [
'oldpass'=>'Old Password',
'newpass'=>'New Password',
'repeatnewpass'=>'Repeat New Password',
];
}
}
in add siteController
public function actionChangepassword(){
$model = new ChangePasswordForm;
$modeluser = Login::find()->where([
'username'=>Yii::$app->user->identity->username
])->one();
if($model->load(Yii::$app->request->post())){
if($model->validate()){
try{
$modeluser->password = $_POST['PasswordForm']['newpass'];
if($modeluser->save()){
Yii::$app->getSession()->setFlash(
'success','Password changed'
);
return $this->redirect(['index']);
}else{
Yii::$app->getSession()->setFlash(
'error','Password not changed'
);
return $this->redirect(['index']);
}
}catch(Exception $e){
Yii::$app->getSession()->setFlash(
'error',"{$e->getMessage()}"
);
return $this->render('changepassword',[
'model'=>$model
]);
}
}else{
return $this->render('changepassword',[
'model'=>$model
]);
}
}else{
return $this->render('changepassword',[
'model'=>$model
]);
}
}