mirror of
https://github.com/elyby/accounts.git
synced 2024-11-26 16:52:02 +05:30
Реализована форма восстановления пароля от аккаунта
Логика проверки пароля вынесена в отдельный валидатор В composer.json докинута зависимость от php7
This commit is contained in:
parent
ebf4947c37
commit
2a4da87fd5
@ -3,6 +3,7 @@ namespace api\controllers;
|
||||
|
||||
use api\models\ForgotPasswordForm;
|
||||
use api\models\LoginForm;
|
||||
use api\models\RecoverPasswordForm;
|
||||
use common\helpers\StringHelper;
|
||||
use Yii;
|
||||
use yii\filters\AccessControl;
|
||||
@ -13,13 +14,13 @@ class AuthenticationController extends Controller {
|
||||
public function behaviors() {
|
||||
return ArrayHelper::merge(parent::behaviors(), [
|
||||
'authenticator' => [
|
||||
'except' => ['login', 'forgot-password'],
|
||||
'except' => ['login', 'forgot-password', 'recover-password'],
|
||||
],
|
||||
'access' => [
|
||||
'class' => AccessControl::class,
|
||||
'rules' => [
|
||||
[
|
||||
'actions' => ['login', 'forgot-password'],
|
||||
'actions' => ['login', 'forgot-password', 'recover-password'],
|
||||
'allow' => true,
|
||||
'roles' => ['?'],
|
||||
],
|
||||
@ -32,6 +33,7 @@ class AuthenticationController extends Controller {
|
||||
return [
|
||||
'login' => ['POST'],
|
||||
'forgot-password' => ['POST'],
|
||||
'recover-password' => ['POST'],
|
||||
];
|
||||
}
|
||||
|
||||
@ -93,4 +95,20 @@ class AuthenticationController extends Controller {
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function actionRecoverPassword() {
|
||||
$model = new RecoverPasswordForm();
|
||||
$model->load(Yii::$app->request->post());
|
||||
if (($jwt = $model->recoverPassword()) === false) {
|
||||
return [
|
||||
'success' => false,
|
||||
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'jwt' => $jwt,
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
<?php
|
||||
namespace api\models;
|
||||
|
||||
use api\models\base\ApiForm;
|
||||
use api\models\base\PasswordProtectedForm;
|
||||
use common\models\Account;
|
||||
use common\validators\PasswordValidate;
|
||||
use Yii;
|
||||
use yii\helpers\ArrayHelper;
|
||||
|
||||
@ -25,9 +25,8 @@ class ChangePasswordForm extends PasswordProtectedForm {
|
||||
*/
|
||||
public function rules() {
|
||||
return ArrayHelper::merge(parent::rules(), [
|
||||
['newPassword', 'required', 'message' => 'error.newPassword_required'],
|
||||
['newRePassword', 'required', 'message' => 'error.newRePassword_required'],
|
||||
['newPassword', 'string', 'min' => 8, 'tooShort' => 'error.password_too_short'],
|
||||
[['newPassword', 'newRePassword'], 'required', 'message' => 'error.{attribute}_required'],
|
||||
['newPassword', PasswordValidate::class],
|
||||
['newRePassword', 'validatePasswordAndRePasswordMatch'],
|
||||
['logoutAll', 'boolean'],
|
||||
]);
|
||||
|
71
api/models/RecoverPasswordForm.php
Normal file
71
api/models/RecoverPasswordForm.php
Normal file
@ -0,0 +1,71 @@
|
||||
<?php
|
||||
namespace api\models;
|
||||
|
||||
use api\models\base\KeyConfirmationForm;
|
||||
use common\models\EmailActivation;
|
||||
use common\validators\PasswordValidate;
|
||||
use Yii;
|
||||
use yii\base\ErrorException;
|
||||
|
||||
class RecoverPasswordForm extends KeyConfirmationForm {
|
||||
|
||||
public $newPassword;
|
||||
|
||||
public $newRePassword;
|
||||
|
||||
public function rules() {
|
||||
return array_merge(parent::rules(), [
|
||||
[['newPassword', 'newRePassword'], 'required', 'message' => 'error.{attribute}_required'],
|
||||
['newPassword', PasswordValidate::class],
|
||||
['newRePassword', 'validatePasswordAndRePasswordMatch'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function validatePasswordAndRePasswordMatch($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
if ($this->newPassword !== $this->newRePassword) {
|
||||
$this->addError($attribute, 'error.rePassword_does_not_match');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function recoverPassword() {
|
||||
if (!$this->validate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$confirmModel = $this->getActivationCodeModel();
|
||||
if ($confirmModel->type !== EmailActivation::TYPE_FORGOT_PASSWORD_KEY) {
|
||||
$confirmModel->delete();
|
||||
// TODO: вот где-то здесь нужно ещё попутно сгенерировать соответствующую ошибку
|
||||
return false;
|
||||
}
|
||||
|
||||
$transaction = Yii::$app->db->beginTransaction();
|
||||
try {
|
||||
$account = $confirmModel->account;
|
||||
$account->password = $this->newPassword;
|
||||
if (!$confirmModel->delete()) {
|
||||
throw new ErrorException('Unable remove activation key.');
|
||||
}
|
||||
|
||||
if (!$account->save()) {
|
||||
throw new ErrorException('Unable activate user account.');
|
||||
}
|
||||
|
||||
$transaction->commit();
|
||||
} catch (ErrorException $e) {
|
||||
$transaction->rollBack();
|
||||
if (YII_DEBUG) {
|
||||
throw $e;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: ещё было бы неплохо уведомить пользователя о том, что его E-mail изменился
|
||||
|
||||
return $account->getJWT();
|
||||
}
|
||||
|
||||
}
|
@ -7,6 +7,7 @@ use common\components\UserFriendlyRandomKey;
|
||||
use common\models\Account;
|
||||
use common\models\confirmations\RegistrationConfirmation;
|
||||
use common\models\EmailActivation;
|
||||
use common\validators\PasswordValidate;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Yii;
|
||||
use yii\base\ErrorException;
|
||||
@ -30,7 +31,7 @@ class RegistrationForm extends ApiForm {
|
||||
|
||||
['password', 'required', 'message' => 'error.password_required'],
|
||||
['rePassword', 'required', 'message' => 'error.rePassword_required'],
|
||||
['password', 'string', 'min' => 8, 'tooShort' => 'error.password_too_short'],
|
||||
['password', PasswordValidate::class],
|
||||
['rePassword', 'validatePasswordAndRePasswordMatch'],
|
||||
];
|
||||
}
|
||||
|
15
common/validators/PasswordValidate.php
Normal file
15
common/validators/PasswordValidate.php
Normal file
@ -0,0 +1,15 @@
|
||||
<?php
|
||||
namespace common\validators;
|
||||
|
||||
use yii\validators\StringValidator;
|
||||
|
||||
/**
|
||||
* Класс должен реализовывать в себе все критерии валидации пароля пользователя
|
||||
*/
|
||||
class PasswordValidate extends StringValidator {
|
||||
|
||||
public $min = 8;
|
||||
|
||||
public $tooShort = 'error.password_too_short';
|
||||
|
||||
}
|
@ -14,7 +14,7 @@
|
||||
},
|
||||
"minimum-stability": "stable",
|
||||
"require": {
|
||||
"php": ">=5.6.0",
|
||||
"php": "~7.0.6",
|
||||
"yiisoft/yii2": "~2.0.6",
|
||||
"yiisoft/yii2-bootstrap": "*",
|
||||
"yiisoft/yii2-swiftmailer": "*",
|
||||
|
@ -23,4 +23,13 @@ class AuthenticationRoute extends BasePage {
|
||||
]);
|
||||
}
|
||||
|
||||
public function recoverPassword($key = null, $newPassword = null, $newRePassword = null) {
|
||||
$this->route = ['authentication/recover-password'];
|
||||
$this->actor->sendPOST($this->getUrl(), [
|
||||
'key' => $key,
|
||||
'newPassword' => $newPassword,
|
||||
'newRePassword' => $newRePassword,
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
36
tests/codeception/api/functional/RecoverPasswordCest.php
Normal file
36
tests/codeception/api/functional/RecoverPasswordCest.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php
|
||||
namespace codeception\api\functional;
|
||||
|
||||
use tests\codeception\api\_pages\AccountsRoute;
|
||||
use tests\codeception\api\_pages\AuthenticationRoute;
|
||||
use tests\codeception\api\FunctionalTester;
|
||||
|
||||
class RecoverPasswordCest {
|
||||
|
||||
public function testDataForFrequencyError(FunctionalTester $I) {
|
||||
$authRoute = new AuthenticationRoute($I);
|
||||
|
||||
$I->wantTo('change my account password, using key from email');
|
||||
$authRoute->recoverPassword('H24HBDCHHAG2HGHGHS', '12345678', '12345678');
|
||||
$I->canSeeResponseContainsJson([
|
||||
'success' => true,
|
||||
]);
|
||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
||||
|
||||
$I->wantTo('ensure, that jwt token is valid');
|
||||
$jwt = $I->grabDataFromResponseByJsonPath('$.jwt')[0];
|
||||
$I->amBearerAuthenticated($jwt);
|
||||
$accountRoute = new AccountsRoute($I);
|
||||
$accountRoute->current();
|
||||
$I->canSeeResponseCodeIs(200);
|
||||
$I->canSeeResponseIsJson();
|
||||
$I->notLoggedIn();
|
||||
|
||||
$I->wantTo('check, that password is really changed');
|
||||
$authRoute->login('Notch', '12345678');
|
||||
$I->canSeeResponseContainsJson([
|
||||
'success' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
<?php
|
||||
namespace tests\codeception\api\models;
|
||||
|
||||
use api\models\RecoverPasswordForm;
|
||||
use Codeception\Specify;
|
||||
use common\models\Account;
|
||||
use common\models\EmailActivation;
|
||||
use tests\codeception\api\unit\DbTestCase;
|
||||
use tests\codeception\common\fixtures\EmailActivationFixture;
|
||||
use Yii;
|
||||
|
||||
/**
|
||||
* @property array $emailActivations
|
||||
*/
|
||||
class RecoverPasswordFormTest extends DbTestCase {
|
||||
use Specify;
|
||||
|
||||
public function fixtures() {
|
||||
return [
|
||||
'emailActivations' => [
|
||||
'class' => EmailActivationFixture::class,
|
||||
'dataFile' => '@tests/codeception/common/fixtures/data/email-activations.php',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function testRecoverPassword() {
|
||||
$fixture = $this->emailActivations['freshPasswordRecovery'];
|
||||
$this->specify('change user account password by email confirmation key', function() use ($fixture) {
|
||||
$model = new RecoverPasswordForm([
|
||||
'key' => $fixture['key'],
|
||||
'newPassword' => '12345678',
|
||||
'newRePassword' => '12345678',
|
||||
]);
|
||||
expect($model->recoverPassword())->notEquals(false);
|
||||
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
|
||||
expect($activationExists)->false();
|
||||
/** @var Account $account */
|
||||
$account = Account::findOne($fixture['account_id']);
|
||||
expect($account->validatePassword('12345678'))->true();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user