<?php
namespace common\modules\user\controllers;
use common\modules\user\models\PasswordForm;
use yii\filters\AccessControl;
use yii\web\Controller;
use Yii;
/**
* Class PasswordController
* @package common\modules\user\controllers
*/
class PasswordController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@'],
]
],
],
];
}
/**
* @return string|\yii\web\Response
*/
public function actionIndex()
{
$model = new PasswordForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->updatePassword()) {
Yii::$app->getSession()->setFlash('success', 'Пароль успешно изменен!');
} else {
Yii::$app->getSession()->setFlash('error', 'Не удалось изменить пароль!');
}
return $this->refresh();
}
return $this->render('index', [
'model' => $model
]);
}
}
<?php
namespace common\modules\user\models;
use core\entities\user\User;
use yii\base\Model;
use yii\web\HttpException;
use Yii;
/**
* Class PasswordForm
* @package common\modules\user\models
*/
class PasswordForm extends Model
{
public $old_password;
public $password;
public $confirm;
public function rules()
{
return [
[['confirm'], 'compare', 'compareAttribute' => 'password', 'message' => 'Введенные пароли не совпадают'],
[['confirm', 'password', 'old_password'], 'required'],
[['old_password'], 'checkCurrentPassword']
];
}
public function load($data, $formName = null)
{
if (!parent::load($data, $formName)) {
return false;
}
$this->confirm = trim($this->confirm);
$this->password = trim($this->password);
$this->old_password = trim($this->old_password);
return true;
}
public function attributeLabels()
{
return [
'old_password' => 'Действующий пароль',
'password' => 'Пароль',
'confirm' => 'Повторите пароль'
];
}
/**
* @throws HttpException
*/
public function checkCurrentPassword($attribute): bool
{
$model = $this->findModel(Yii::$app->user->id);
if (!$model->validatePassword($this->$attribute)) {
$this->addError($attribute, 'Неправильный пароль');
}
return true;
}
/**
* @throws \yii\base\Exception
* @throws HttpException
*/
public function updatePassword(): bool
{
$model = $this->findModel(Yii::$app->user->id);
$model->setPassword($this->password);
if (!$model->save()) {
$this->addError('password', 'Ошибка при сохранении пароля. Обратитесь к администратору сайта');
return false;
}
return true;
}
/**
* @param int $id
* @return User
* @throws HttpException
*/
protected function findModel(int $id): User
{
if ($model = User::findOne(['id' => $id])) {
return $model;
} else {
throw new HttpException(404, 'Пользователь не найден');
}
}
}
public function validatePassword(string $password): bool
{
return \Yii::$app->security->validatePassword($password, $this->password_hash);
}
public function setPassword($password)
{
$this->password_hash = \Yii::$app->security->generatePasswordHash($password);
}
<div class="form-user">
<?php if (Yii::$app->session->getFlash('success')): ?>
<div class="alert alert-success" style="color: green;" role="alert">
Пароль успешно изменен
</div>
<?php endif; ?>
<?php $form = ActiveForm::begin() ?>
<?= $form->field($model, 'old_password')->passwordInput()->label('Текущий пароль') ?>
<?= $form->field($model, 'password')->passwordInput()->label('Новый пароль') ?>
<?= $form->field($model, 'confirm')->passwordInput()->label('Новый пароль еще раз') ?>
<?= Html::submitButton('Изменить пароль', ['class' => 'button']) ?>
<?php ActiveForm::end() ?>
</div>