mirror of
https://github.com/elyby/accounts.git
synced 2025-05-31 14:11:46 +05:30
Реорганизована выдача JWT токенов
Добавлен механизм сохранения сессий и refresh_token
This commit is contained in:
parent
98c01625d1
commit
bdc96d82c1
102
api/components/User/Component.php
Normal file
102
api/components/User/Component.php
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
<?php
|
||||||
|
namespace api\components\User;
|
||||||
|
|
||||||
|
use common\models\AccountSession;
|
||||||
|
use Emarref\Jwt\Algorithm\Hs256;
|
||||||
|
use Emarref\Jwt\Claim;
|
||||||
|
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
|
||||||
|
use Emarref\Jwt\Jwt;
|
||||||
|
use Emarref\Jwt\Token;
|
||||||
|
use Yii;
|
||||||
|
use yii\base\ErrorException;
|
||||||
|
use yii\base\InvalidConfigException;
|
||||||
|
use yii\web\IdentityInterface;
|
||||||
|
use yii\web\User as YiiUserComponent;
|
||||||
|
|
||||||
|
class Component extends YiiUserComponent {
|
||||||
|
|
||||||
|
public $secret;
|
||||||
|
|
||||||
|
public $expirationTimeout = 3600; // 1h
|
||||||
|
|
||||||
|
public function init() {
|
||||||
|
parent::init();
|
||||||
|
if (!$this->secret) {
|
||||||
|
throw new InvalidConfigException('secret must be specified');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param IdentityInterface $identity
|
||||||
|
* @param bool $rememberMe
|
||||||
|
*
|
||||||
|
* @return LoginResult|bool
|
||||||
|
* @throws ErrorException
|
||||||
|
*/
|
||||||
|
public function login(IdentityInterface $identity, $rememberMe = false) {
|
||||||
|
if (!$this->beforeLogin($identity, false, $rememberMe)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->switchIdentity($identity, 0);
|
||||||
|
|
||||||
|
$id = $identity->getId();
|
||||||
|
$ip = Yii::$app->request->userIP;
|
||||||
|
|
||||||
|
$jwt = $this->getJWT($identity);
|
||||||
|
if ($rememberMe) {
|
||||||
|
$session = new AccountSession();
|
||||||
|
$session->account_id = $id;
|
||||||
|
$session->setIp($ip);
|
||||||
|
$session->generateRefreshToken();
|
||||||
|
if (!$session->save()) {
|
||||||
|
throw new ErrorException('Cannot save account session model');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$session = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Yii::info("User '{$id}' logged in from {$ip}.", __METHOD__);
|
||||||
|
|
||||||
|
$result = new LoginResult($identity, $jwt, $session);
|
||||||
|
$this->afterLogin($identity, false, $rememberMe);
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getJWT(IdentityInterface $identity) {
|
||||||
|
$jwt = new Jwt();
|
||||||
|
$token = new Token();
|
||||||
|
foreach($this->getClaims($identity) as $claim) {
|
||||||
|
$token->addClaim($claim);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $jwt->serialize($token, EncryptionFactory::create($this->getAlgorithm()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return Hs256
|
||||||
|
*/
|
||||||
|
public function getAlgorithm() {
|
||||||
|
return new Hs256($this->secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param IdentityInterface $identity
|
||||||
|
*
|
||||||
|
* @return Claim\AbstractClaim[]
|
||||||
|
*/
|
||||||
|
protected function getClaims(IdentityInterface $identity) {
|
||||||
|
$currentTime = time();
|
||||||
|
$hostInfo = Yii::$app->request->hostInfo;
|
||||||
|
|
||||||
|
return [
|
||||||
|
new Claim\Audience($hostInfo),
|
||||||
|
new Claim\Issuer($hostInfo),
|
||||||
|
new Claim\IssuedAt($currentTime),
|
||||||
|
new Claim\Expiration($currentTime + $this->expirationTimeout),
|
||||||
|
new Claim\JwtId($identity->getId()),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
61
api/components/User/LoginResult.php
Normal file
61
api/components/User/LoginResult.php
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
<?php
|
||||||
|
namespace api\components\User;
|
||||||
|
|
||||||
|
use common\models\AccountSession;
|
||||||
|
use Yii;
|
||||||
|
use yii\web\IdentityInterface;
|
||||||
|
|
||||||
|
class LoginResult {
|
||||||
|
/**
|
||||||
|
* @var IdentityInterface
|
||||||
|
*/
|
||||||
|
private $identity;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private $jwt;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var AccountSession|null
|
||||||
|
*/
|
||||||
|
private $session;
|
||||||
|
|
||||||
|
public function __construct(IdentityInterface $identity, string $jwt, AccountSession $session = null) {
|
||||||
|
$this->identity = $identity;
|
||||||
|
$this->jwt = $jwt;
|
||||||
|
$this->session = $session;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getIdentity() : IdentityInterface {
|
||||||
|
return $this->identity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getJwt() : string {
|
||||||
|
return $this->jwt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return AccountSession|null
|
||||||
|
*/
|
||||||
|
public function getSession() {
|
||||||
|
return $this->session;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getAsResponse() {
|
||||||
|
/** @var Component $component */
|
||||||
|
$component = Yii::$app->user;
|
||||||
|
$response = [
|
||||||
|
'access_token' => $this->getJwt(),
|
||||||
|
'expires_in' => $component->expirationTimeout,
|
||||||
|
];
|
||||||
|
|
||||||
|
$session = $this->getSession();
|
||||||
|
if ($session !== null) {
|
||||||
|
$response['refresh_token'] = $session->refresh_token;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -13,9 +13,11 @@ return [
|
|||||||
'controllerNamespace' => 'api\controllers',
|
'controllerNamespace' => 'api\controllers',
|
||||||
'components' => [
|
'components' => [
|
||||||
'user' => [
|
'user' => [
|
||||||
|
'class' => \api\components\User\Component::class,
|
||||||
'identityClass' => \api\models\AccountIdentity::class,
|
'identityClass' => \api\models\AccountIdentity::class,
|
||||||
'enableSession' => false,
|
'enableSession' => false,
|
||||||
'loginUrl' => null,
|
'loginUrl' => null,
|
||||||
|
'secret' => $params['userSecret'],
|
||||||
],
|
],
|
||||||
'log' => [
|
'log' => [
|
||||||
'traceLevel' => YII_DEBUG ? 3 : 0,
|
'traceLevel' => YII_DEBUG ? 3 : 0,
|
||||||
|
@ -40,7 +40,7 @@ class AuthenticationController extends Controller {
|
|||||||
public function actionLogin() {
|
public function actionLogin() {
|
||||||
$model = new LoginForm();
|
$model = new LoginForm();
|
||||||
$model->load(Yii::$app->request->post());
|
$model->load(Yii::$app->request->post());
|
||||||
if (($jwt = $model->login()) === false) {
|
if (($result = $model->login()) === false) {
|
||||||
$data = [
|
$data = [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
||||||
@ -53,10 +53,9 @@ class AuthenticationController extends Controller {
|
|||||||
return $data;
|
return $data;
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return array_merge([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
'jwt' => $jwt,
|
], $result->getAsResponse());
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function actionForgotPassword() {
|
public function actionForgotPassword() {
|
||||||
@ -98,17 +97,16 @@ class AuthenticationController extends Controller {
|
|||||||
public function actionRecoverPassword() {
|
public function actionRecoverPassword() {
|
||||||
$model = new RecoverPasswordForm();
|
$model = new RecoverPasswordForm();
|
||||||
$model->load(Yii::$app->request->post());
|
$model->load(Yii::$app->request->post());
|
||||||
if (($jwt = $model->recoverPassword()) === false) {
|
if (($result = $model->recoverPassword()) === false) {
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return array_merge([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
'jwt' => $jwt,
|
], $result->getAsResponse());
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -15,7 +15,7 @@ class Controller extends \yii\rest\Controller {
|
|||||||
$parentBehaviors = parent::behaviors();
|
$parentBehaviors = parent::behaviors();
|
||||||
// Добавляем авторизатор для входа по jwt токенам
|
// Добавляем авторизатор для входа по jwt токенам
|
||||||
$parentBehaviors['authenticator'] = [
|
$parentBehaviors['authenticator'] = [
|
||||||
'class' => HttpBearerAuth::className(),
|
'class' => HttpBearerAuth::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
// xml нам не понадобится
|
// xml нам не понадобится
|
||||||
|
@ -79,17 +79,16 @@ class SignupController extends Controller {
|
|||||||
public function actionConfirm() {
|
public function actionConfirm() {
|
||||||
$model = new ConfirmEmailForm();
|
$model = new ConfirmEmailForm();
|
||||||
$model->load(Yii::$app->request->post());
|
$model->load(Yii::$app->request->post());
|
||||||
if (!($jwt = $model->confirm())) {
|
if (!($result = $model->confirm())) {
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return array_merge([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
'jwt' => $jwt,
|
], $result->getAsResponse());
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,17 +2,61 @@
|
|||||||
namespace api\models;
|
namespace api\models;
|
||||||
|
|
||||||
use common\models\Account;
|
use common\models\Account;
|
||||||
|
use Emarref\Jwt\Encryption\Factory;
|
||||||
|
use Emarref\Jwt\Exception\VerificationException;
|
||||||
|
use Emarref\Jwt\Jwt;
|
||||||
|
use Emarref\Jwt\Verification\Context as VerificationContext;
|
||||||
|
use Yii;
|
||||||
use yii\base\NotSupportedException;
|
use yii\base\NotSupportedException;
|
||||||
|
use yii\helpers\StringHelper;
|
||||||
use yii\web\IdentityInterface;
|
use yii\web\IdentityInterface;
|
||||||
|
use yii\web\UnauthorizedHttpException;
|
||||||
|
|
||||||
/**
|
|
||||||
* @method static findIdentityByAccessToken($token, $type = null) этот метод реализуется в UserTrait, который
|
|
||||||
* подключён в родительском Account и позволяет выполнить условия интерфейса
|
|
||||||
* @method string getId() метод реализован в родительском классе, т.к. UserTrait требует, чтобы этот метод
|
|
||||||
* присутствовал обязательно, но при этом не навязывает его как абстрактный
|
|
||||||
*/
|
|
||||||
class AccountIdentity extends Account implements IdentityInterface {
|
class AccountIdentity extends Account implements IdentityInterface {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @inheritdoc
|
||||||
|
*/
|
||||||
|
public static function findIdentityByAccessToken($token, $type = null) {
|
||||||
|
$jwt = new Jwt();
|
||||||
|
$token = $jwt->deserialize($token);
|
||||||
|
/** @var \api\components\User\Component $component */
|
||||||
|
$component = Yii::$app->user;
|
||||||
|
|
||||||
|
$hostInfo = Yii::$app->request->hostInfo;
|
||||||
|
$context = new VerificationContext(Factory::create($component->getAlgorithm()));
|
||||||
|
$context->setAudience($hostInfo);
|
||||||
|
$context->setIssuer($hostInfo);
|
||||||
|
try {
|
||||||
|
$jwt->verify($token, $context);
|
||||||
|
} catch (VerificationException $e) {
|
||||||
|
if (StringHelper::startsWith($e->getMessage(), 'Token expired at')) {
|
||||||
|
$message = 'Token expired';
|
||||||
|
} else {
|
||||||
|
$message = 'Incorrect token';
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new UnauthorizedHttpException($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если исключение выше не случилось, то значит всё оке
|
||||||
|
/** @var \Emarref\Jwt\Claim\JwtId $jti */
|
||||||
|
$jti = $token->getPayload()->findClaimByName('jti');
|
||||||
|
$account = static::findOne($jti->getValue());
|
||||||
|
if ($account === null) {
|
||||||
|
throw new UnauthorizedHttpException('Invalid token');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $account;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @inheritdoc
|
||||||
|
*/
|
||||||
|
public function getId() {
|
||||||
|
return $this->id;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @inheritdoc
|
* @inheritdoc
|
||||||
*/
|
*/
|
||||||
@ -31,7 +75,7 @@ class AccountIdentity extends Account implements IdentityInterface {
|
|||||||
* @inheritdoc
|
* @inheritdoc
|
||||||
*/
|
*/
|
||||||
public function validateAuthKey($authKey) {
|
public function validateAuthKey($authKey) {
|
||||||
return $this->getAuthKey() === $authKey;
|
throw new NotSupportedException('This method used for cookie auth, except we using JWT tokens');
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace api\models\authentication;
|
namespace api\models\authentication;
|
||||||
|
|
||||||
|
use api\models\AccountIdentity;
|
||||||
use api\models\base\KeyConfirmationForm;
|
use api\models\base\KeyConfirmationForm;
|
||||||
use common\models\Account;
|
use common\models\Account;
|
||||||
use common\models\EmailActivation;
|
use common\models\EmailActivation;
|
||||||
@ -43,7 +44,10 @@ class ConfirmEmailForm extends KeyConfirmationForm {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $account->getJWT();
|
/** @var \api\components\User\Component $component */
|
||||||
|
$component = Yii::$app->user;
|
||||||
|
|
||||||
|
return $component->login(new AccountIdentity($account->attributes), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,17 +1,21 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace api\models\authentication;
|
namespace api\models\authentication;
|
||||||
|
|
||||||
|
use api\models\AccountIdentity;
|
||||||
use api\models\base\ApiForm;
|
use api\models\base\ApiForm;
|
||||||
use api\traits\AccountFinder;
|
use api\traits\AccountFinder;
|
||||||
use common\models\Account;
|
use common\models\Account;
|
||||||
use Yii;
|
use Yii;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @method AccountIdentity|null getAccount()
|
||||||
|
*/
|
||||||
class LoginForm extends ApiForm {
|
class LoginForm extends ApiForm {
|
||||||
use AccountFinder;
|
use AccountFinder;
|
||||||
|
|
||||||
public $login;
|
public $login;
|
||||||
public $password;
|
public $password;
|
||||||
public $rememberMe = true;
|
public $rememberMe = false;
|
||||||
|
|
||||||
public function rules() {
|
public function rules() {
|
||||||
return [
|
return [
|
||||||
@ -31,7 +35,7 @@ class LoginForm extends ApiForm {
|
|||||||
|
|
||||||
public function validateLogin($attribute) {
|
public function validateLogin($attribute) {
|
||||||
if (!$this->hasErrors()) {
|
if (!$this->hasErrors()) {
|
||||||
if (!$this->getAccount()) {
|
if ($this->getAccount() === null) {
|
||||||
$this->addError($attribute, 'error.' . $attribute . '_not_exist');
|
$this->addError($attribute, 'error.' . $attribute . '_not_exist');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -40,7 +44,7 @@ class LoginForm extends ApiForm {
|
|||||||
public function validatePassword($attribute) {
|
public function validatePassword($attribute) {
|
||||||
if (!$this->hasErrors()) {
|
if (!$this->hasErrors()) {
|
||||||
$account = $this->getAccount();
|
$account = $this->getAccount();
|
||||||
if (!$account || !$account->validatePassword($this->password)) {
|
if ($account === null || !$account->validatePassword($this->password)) {
|
||||||
$this->addError($attribute, 'error.' . $attribute . '_incorrect');
|
$this->addError($attribute, 'error.' . $attribute . '_incorrect');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -60,24 +64,27 @@ class LoginForm extends ApiForm {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return bool|string JWT с информацией об аккаунте
|
* @return \api\components\User\LoginResult|bool
|
||||||
*/
|
*/
|
||||||
public function login() {
|
public function login() {
|
||||||
if (!$this->validate()) {
|
if (!$this->validate()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($this->rememberMe) {
|
|
||||||
// TODO: здесь нужно записать какую-то
|
|
||||||
}
|
|
||||||
|
|
||||||
$account = $this->getAccount();
|
$account = $this->getAccount();
|
||||||
if ($account->password_hash_strategy === Account::PASS_HASH_STRATEGY_OLD_ELY) {
|
if ($account->password_hash_strategy === Account::PASS_HASH_STRATEGY_OLD_ELY) {
|
||||||
$account->setPassword($this->password);
|
$account->setPassword($this->password);
|
||||||
$account->save();
|
$account->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
return $account->getJWT();
|
/** @var \api\components\User\Component $component */
|
||||||
|
$component = Yii::$app->user;
|
||||||
|
|
||||||
|
return $component->login($account, $this->rememberMe);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getAccountClassName() {
|
||||||
|
return AccountIdentity::class;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace api\models\authentication;
|
namespace api\models\authentication;
|
||||||
|
|
||||||
|
use api\models\AccountIdentity;
|
||||||
use api\models\base\KeyConfirmationForm;
|
use api\models\base\KeyConfirmationForm;
|
||||||
use common\models\EmailActivation;
|
use common\models\EmailActivation;
|
||||||
use common\validators\PasswordValidate;
|
use common\validators\PasswordValidate;
|
||||||
@ -63,9 +64,12 @@ class RecoverPasswordForm extends KeyConfirmationForm {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: ещё было бы неплохо уведомить пользователя о том, что его E-mail изменился
|
// TODO: ещё было бы неплохо уведомить пользователя о том, что его пароль изменился
|
||||||
|
|
||||||
return $account->getJWT();
|
/** @var \api\components\User\Component $component */
|
||||||
|
$component = Yii::$app->user;
|
||||||
|
|
||||||
|
return $component->login(new AccountIdentity($account->attributes), false);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,8 @@ trait AccountFinder {
|
|||||||
*/
|
*/
|
||||||
public function getAccount() {
|
public function getAccount() {
|
||||||
if ($this->account === null) {
|
if ($this->account === null) {
|
||||||
$this->account = Account::findOne([$this->getLoginAttribute() => $this->getLogin()]);
|
$className = $this->getAccountClassName();
|
||||||
|
$this->account = $className::findOne([$this->getLoginAttribute() => $this->getLogin()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->account;
|
return $this->account;
|
||||||
@ -24,4 +25,11 @@ trait AccountFinder {
|
|||||||
return strpos($this->getLogin(), '@') ? 'email' : 'username';
|
return strpos($this->getLogin(), '@') ? 'email' : 'username';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return Account|string
|
||||||
|
*/
|
||||||
|
protected function getAccountClassName() {
|
||||||
|
return Account::class;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,6 @@ namespace common\models;
|
|||||||
|
|
||||||
use common\components\UserPass;
|
use common\components\UserPass;
|
||||||
use common\validators\LanguageValidator;
|
use common\validators\LanguageValidator;
|
||||||
use damirka\JWT\UserTrait as UserJWTTrait;
|
|
||||||
use Ely\Yii2\TempmailValidator;
|
use Ely\Yii2\TempmailValidator;
|
||||||
use Yii;
|
use Yii;
|
||||||
use yii\base\InvalidConfigException;
|
use yii\base\InvalidConfigException;
|
||||||
@ -29,15 +28,14 @@ use yii\db\ActiveRecord;
|
|||||||
*
|
*
|
||||||
* Отношения:
|
* Отношения:
|
||||||
* @property EmailActivation[] $emailActivations
|
* @property EmailActivation[] $emailActivations
|
||||||
* @property OauthSession[] $sessions
|
* @property OauthSession[] $oauthSessions
|
||||||
* @property UsernameHistory[] $usernameHistory
|
* @property UsernameHistory[] $usernameHistory
|
||||||
|
* @property AccountSession[] $sessions
|
||||||
*
|
*
|
||||||
* Поведения:
|
* Поведения:
|
||||||
* @mixin TimestampBehavior
|
* @mixin TimestampBehavior
|
||||||
*/
|
*/
|
||||||
class Account extends ActiveRecord {
|
class Account extends ActiveRecord {
|
||||||
use UserJWTTrait;
|
|
||||||
|
|
||||||
const STATUS_DELETED = -10;
|
const STATUS_DELETED = -10;
|
||||||
const STATUS_REGISTERED = 0;
|
const STATUS_REGISTERED = 0;
|
||||||
const STATUS_ACTIVE = 10;
|
const STATUS_ACTIVE = 10;
|
||||||
@ -121,7 +119,7 @@ class Account extends ActiveRecord {
|
|||||||
return $this->hasMany(EmailActivation::class, ['account_id' => 'id']);
|
return $this->hasMany(EmailActivation::class, ['account_id' => 'id']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getSessions() {
|
public function getOauthSessions() {
|
||||||
return $this->hasMany(OauthSession::class, ['owner_id' => 'id']);
|
return $this->hasMany(OauthSession::class, ['owner_id' => 'id']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -129,6 +127,10 @@ class Account extends ActiveRecord {
|
|||||||
return $this->hasMany(UsernameHistory::class, ['account_id' => 'id']);
|
return $this->hasMany(UsernameHistory::class, ['account_id' => 'id']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function getSessions() {
|
||||||
|
return $this->hasMany(AccountSession::class, ['account_id' => 'id']);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Метод проверяет, может ли текущий пользователь быть автоматически авторизован
|
* Метод проверяет, может ли текущий пользователь быть автоматически авторизован
|
||||||
* для указанного клиента без запроса доступа к необходимому списку прав
|
* для указанного клиента без запроса доступа к необходимому списку прав
|
||||||
@ -144,7 +146,7 @@ class Account extends ActiveRecord {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @var OauthSession|null $session */
|
/** @var OauthSession|null $session */
|
||||||
$session = $this->getSessions()->andWhere(['client_id' => $client->id])->one();
|
$session = $this->getOauthSessions()->andWhere(['client_id' => $client->id])->one();
|
||||||
if ($session !== null) {
|
if ($session !== null) {
|
||||||
$existScopes = $session->getScopes()->members();
|
$existScopes = $session->getScopes()->members();
|
||||||
if (empty(array_diff(array_keys($scopes), $existScopes))) {
|
if (empty(array_diff(array_keys($scopes), $existScopes))) {
|
||||||
|
54
common/models/AccountSession.php
Normal file
54
common/models/AccountSession.php
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
namespace common\models;
|
||||||
|
|
||||||
|
use Yii;
|
||||||
|
use yii\behaviors\TimestampBehavior;
|
||||||
|
use yii\db\ActiveRecord;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Поля модели:
|
||||||
|
* @property integer $id
|
||||||
|
* @property integer $account_id
|
||||||
|
* @property string $refresh_token
|
||||||
|
* @property integer $last_used_ip
|
||||||
|
* @property integer $created_at
|
||||||
|
* @property integer $last_refreshed
|
||||||
|
*
|
||||||
|
* Отношения:
|
||||||
|
* @property Account $account
|
||||||
|
*
|
||||||
|
* Поведения:
|
||||||
|
* @mixin TimestampBehavior
|
||||||
|
*/
|
||||||
|
class AccountSession extends ActiveRecord {
|
||||||
|
|
||||||
|
public static function tableName() {
|
||||||
|
return '{{%accounts_sessions}}';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function behaviors() {
|
||||||
|
return [
|
||||||
|
[
|
||||||
|
'class' => TimestampBehavior::class,
|
||||||
|
'updatedAtAttribute' => 'last_refreshed_at',
|
||||||
|
]
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getAccount() {
|
||||||
|
return $this->hasOne(Account::class, ['id' => 'account_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function generateRefreshToken() {
|
||||||
|
$this->refresh_token = Yii::$app->security->generateRandomString(96);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setIp($ip) {
|
||||||
|
$this->last_used_ip = ip2long($ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getReadableIp() {
|
||||||
|
return long2ip($this->last_used_ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -16,15 +16,14 @@
|
|||||||
"require": {
|
"require": {
|
||||||
"php": "~7.0.6",
|
"php": "~7.0.6",
|
||||||
"yiisoft/yii2": "~2.0.8",
|
"yiisoft/yii2": "~2.0.8",
|
||||||
"yiisoft/yii2-bootstrap": "*",
|
|
||||||
"yiisoft/yii2-swiftmailer": "*",
|
"yiisoft/yii2-swiftmailer": "*",
|
||||||
"ramsey/uuid": "~3.1",
|
"ramsey/uuid": "~3.1",
|
||||||
"league/oauth2-server": "~4.1.5",
|
"league/oauth2-server": "~4.1.5",
|
||||||
"yiisoft/yii2-redis": "~2.0.0",
|
"yiisoft/yii2-redis": "~2.0.0",
|
||||||
"damirka/yii2-jwt": "~0.1.0",
|
|
||||||
"guzzlehttp/guzzle": "~5.3.0",
|
"guzzlehttp/guzzle": "~5.3.0",
|
||||||
"php-amqplib/php-amqplib": "~2.6.2",
|
"php-amqplib/php-amqplib": "~2.6.2",
|
||||||
"ely/yii2-tempmail-validator": "~1.0.0"
|
"ely/yii2-tempmail-validator": "~1.0.0",
|
||||||
|
"emarref/jwt": "~1.0.0"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"yiisoft/yii2-codeception": "*",
|
"yiisoft/yii2-codeception": "*",
|
||||||
|
24
console/migrations/m160517_151805_account_sessions.php
Normal file
24
console/migrations/m160517_151805_account_sessions.php
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use console\db\Migration;
|
||||||
|
|
||||||
|
class m160517_151805_account_sessions extends Migration {
|
||||||
|
|
||||||
|
public function safeUp() {
|
||||||
|
$this->createTable('{{%accounts_sessions}}', [
|
||||||
|
'id' => $this->primaryKey(),
|
||||||
|
'account_id' => $this->db->getTableSchema('{{%accounts}}')->getColumn('id')->dbType . ' NOT NULL',
|
||||||
|
'refresh_token' => $this->string()->notNull()->unique(),
|
||||||
|
'last_used_ip' => $this->integer()->unsigned()->notNull(),
|
||||||
|
'created_at' => $this->integer()->notNull(),
|
||||||
|
'last_refreshed_at' => $this->integer()->notNull(),
|
||||||
|
], $this->tableOptions);
|
||||||
|
|
||||||
|
$this->addForeignKey('FK_account_session_to_account', '{{%accounts_sessions}}', 'account_id', '{{%accounts}}', 'id', 'CASCADE', 'CASCADE');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function safeDown() {
|
||||||
|
$this->dropTable('{{%accounts_sessions}}');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php
|
||||||
return [
|
return [
|
||||||
'jwtSecret' => 'some-long-secret-key',
|
'userSecret' => 'some-long-secret-key',
|
||||||
];
|
];
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php
|
||||||
return [
|
return [
|
||||||
'jwtSecret' => 'some-long-secret-key',
|
'userSecret' => 'some-long-secret-key',
|
||||||
];
|
];
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php
|
||||||
return [
|
return [
|
||||||
'jwtSecret' => 'some-long-secret-key',
|
'userSecret' => 'some-long-secret-key',
|
||||||
];
|
];
|
||||||
|
@ -8,12 +8,18 @@ use yii\codeception\BasePage;
|
|||||||
*/
|
*/
|
||||||
class AuthenticationRoute extends BasePage {
|
class AuthenticationRoute extends BasePage {
|
||||||
|
|
||||||
public function login($login = '', $password = '') {
|
public function login($login = '', $password = '', $rememberMe = false) {
|
||||||
$this->route = ['authentication/login'];
|
$this->route = ['authentication/login'];
|
||||||
$this->actor->sendPOST($this->getUrl(), [
|
$params = [
|
||||||
'login' => $login,
|
'login' => $login,
|
||||||
'password' => $password,
|
'password' => $password,
|
||||||
]);
|
];
|
||||||
|
|
||||||
|
if ($rememberMe) {
|
||||||
|
$params['rememberMe'] = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->actor->sendPOST($this->getUrl(), $params);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function forgotPassword($login = '') {
|
public function forgotPassword($login = '') {
|
||||||
|
@ -34,8 +34,8 @@ class FunctionalTester extends Actor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->canSeeResponseIsJson();
|
$this->canSeeResponseIsJson();
|
||||||
$this->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
$this->canSeeAuthCredentials(false);
|
||||||
$jwt = $this->grabDataFromResponseByJsonPath('$.jwt')[0];
|
$jwt = $this->grabDataFromResponseByJsonPath('$.access_token')[0];
|
||||||
$this->amBearerAuthenticated($jwt);
|
$this->amBearerAuthenticated($jwt);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,4 +43,14 @@ class FunctionalTester extends Actor {
|
|||||||
$this->haveHttpHeader('Authorization', null);
|
$this->haveHttpHeader('Authorization', null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function canSeeAuthCredentials($expectRefresh = false) {
|
||||||
|
$this->canSeeResponseJsonMatchesJsonPath('$.access_token');
|
||||||
|
$this->canSeeResponseJsonMatchesJsonPath('$.expires_in');
|
||||||
|
if ($expectRefresh) {
|
||||||
|
$this->canSeeResponseJsonMatchesJsonPath('$.refresh_token');
|
||||||
|
} else {
|
||||||
|
$this->cantSeeResponseJsonMatchesJsonPath('$.refresh_token');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -36,7 +36,7 @@ class EmailConfirmationCest {
|
|||||||
'success' => true,
|
'success' => true,
|
||||||
]);
|
]);
|
||||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
$I->canSeeAuthCredentials(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -111,8 +111,8 @@ class LoginCest {
|
|||||||
$I->canSeeResponseContainsJson([
|
$I->canSeeResponseContainsJson([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
]);
|
]);
|
||||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
|
||||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||||
|
$I->canSeeAuthCredentials(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLoginByEmailCorrect(FunctionalTester $I) {
|
public function testLoginByEmailCorrect(FunctionalTester $I) {
|
||||||
@ -124,6 +124,7 @@ class LoginCest {
|
|||||||
'success' => true,
|
'success' => true,
|
||||||
]);
|
]);
|
||||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||||
|
$I->canSeeAuthCredentials(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLoginInAccWithPasswordMethod(FunctionalTester $I) {
|
public function testLoginInAccWithPasswordMethod(FunctionalTester $I) {
|
||||||
@ -134,8 +135,20 @@ class LoginCest {
|
|||||||
$I->canSeeResponseContainsJson([
|
$I->canSeeResponseContainsJson([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
]);
|
]);
|
||||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
|
||||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||||
|
$I->canSeeAuthCredentials(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testLoginByEmailWithRemember(FunctionalTester $I) {
|
||||||
|
$route = new AuthenticationRoute($I);
|
||||||
|
|
||||||
|
$I->wantTo('login into account using correct data and get refresh_token');
|
||||||
|
$route->login('admin@ely.by', 'password_0', true);
|
||||||
|
$I->canSeeResponseContainsJson([
|
||||||
|
'success' => true,
|
||||||
|
]);
|
||||||
|
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||||
|
$I->canSeeAuthCredentials(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -15,10 +15,10 @@ class RecoverPasswordCest {
|
|||||||
$I->canSeeResponseContainsJson([
|
$I->canSeeResponseContainsJson([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
]);
|
]);
|
||||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
$I->canSeeAuthCredentials(false);
|
||||||
|
|
||||||
$I->wantTo('ensure, that jwt token is valid');
|
$I->wantTo('ensure, that jwt token is valid');
|
||||||
$jwt = $I->grabDataFromResponseByJsonPath('$.jwt')[0];
|
$jwt = $I->grabDataFromResponseByJsonPath('$.access_token')[0];
|
||||||
$I->amBearerAuthenticated($jwt);
|
$I->amBearerAuthenticated($jwt);
|
||||||
$accountRoute = new AccountsRoute($I);
|
$accountRoute = new AccountsRoute($I);
|
||||||
$accountRoute->current();
|
$accountRoute->current();
|
||||||
|
101
tests/codeception/api/unit/components/User/ComponentTest.php
Normal file
101
tests/codeception/api/unit/components/User/ComponentTest.php
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
<?php
|
||||||
|
namespace codeception\api\unit\components\User;
|
||||||
|
|
||||||
|
use api\components\User\Component;
|
||||||
|
use api\components\User\LoginResult;
|
||||||
|
use api\models\AccountIdentity;
|
||||||
|
use Codeception\Specify;
|
||||||
|
use common\models\AccountSession;
|
||||||
|
use Emarref\Jwt\Algorithm\AlgorithmInterface;
|
||||||
|
use Emarref\Jwt\Claim\ClaimInterface;
|
||||||
|
use tests\codeception\api\unit\DbTestCase;
|
||||||
|
use tests\codeception\common\_support\ProtectedCaller;
|
||||||
|
use tests\codeception\common\fixtures\AccountFixture;
|
||||||
|
use tests\codeception\common\fixtures\AccountSessionFixture;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @property AccountFixture $accounts
|
||||||
|
* @property AccountSessionFixture $sessions
|
||||||
|
*/
|
||||||
|
class ComponentTest extends DbTestCase {
|
||||||
|
use Specify;
|
||||||
|
use ProtectedCaller;
|
||||||
|
|
||||||
|
private $originalRemoteHost;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var Component
|
||||||
|
*/
|
||||||
|
private $component;
|
||||||
|
|
||||||
|
public function _before() {
|
||||||
|
$this->originalRemoteHost = $_SERVER['REMOTE_ADDR'] ?? null;
|
||||||
|
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
|
||||||
|
parent::_before();
|
||||||
|
|
||||||
|
$this->component = new Component([
|
||||||
|
'identityClass' => AccountIdentity::class,
|
||||||
|
'enableSession' => false,
|
||||||
|
'loginUrl' => null,
|
||||||
|
'secret' => 'secret',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function _after() {
|
||||||
|
parent::_after();
|
||||||
|
$_SERVER['REMOTE_ADDR'] = $this->originalRemoteHost;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fixtures() {
|
||||||
|
return [
|
||||||
|
'accounts' => AccountFixture::class,
|
||||||
|
'sessions' => AccountSessionFixture::class,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testLogin() {
|
||||||
|
$this->specify('success get LoginResult object without session value', function() {
|
||||||
|
$account = new AccountIdentity(['id' => 1]);
|
||||||
|
$result = $this->component->login($account, false);
|
||||||
|
expect($result)->isInstanceOf(LoginResult::class);
|
||||||
|
expect($result->getSession())->null();
|
||||||
|
expect(is_string($result->getJwt()))->true();
|
||||||
|
expect($result->getIdentity())->equals($account);
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->specify('success get LoginResult object with session value if rememberMe is true', function() {
|
||||||
|
/** @var AccountIdentity $account */
|
||||||
|
$account = AccountIdentity::findOne($this->accounts['admin']['id']);
|
||||||
|
$result = $this->component->login($account, true);
|
||||||
|
expect($result)->isInstanceOf(LoginResult::class);
|
||||||
|
expect($result->getSession())->isInstanceOf(AccountSession::class);
|
||||||
|
expect(is_string($result->getJwt()))->true();
|
||||||
|
expect($result->getIdentity())->equals($account);
|
||||||
|
expect($result->getSession()->refresh())->true();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testGetJWT() {
|
||||||
|
$this->specify('get string, contained jwt token', function() {
|
||||||
|
expect($this->component->getJWT(new AccountIdentity(['id' => 1])))
|
||||||
|
->regExp('/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+\/=]*$/');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testGetAlgorithm() {
|
||||||
|
$this->specify('get expected hash algorithm object', function() {
|
||||||
|
expect($this->component->getAlgorithm())->isInstanceOf(AlgorithmInterface::class);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testGetClaims() {
|
||||||
|
$this->specify('get expected array of claims', function() {
|
||||||
|
$claims = $this->callProtected($this->component, 'getClaims', new AccountIdentity(['id' => 1]));
|
||||||
|
expect(is_array($claims))->true();
|
||||||
|
expect('all array items should have valid type', array_filter($claims, function($claim) {
|
||||||
|
return !$claim instanceof ClaimInterface;
|
||||||
|
}))->isEmpty();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
64
tests/codeception/api/unit/models/AccountIdentityTest.php
Normal file
64
tests/codeception/api/unit/models/AccountIdentityTest.php
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
<?php
|
||||||
|
namespace codeception\api\unit\models;
|
||||||
|
|
||||||
|
use api\models\AccountIdentity;
|
||||||
|
use Codeception\Specify;
|
||||||
|
use Exception;
|
||||||
|
use tests\codeception\api\unit\DbTestCase;
|
||||||
|
use tests\codeception\common\fixtures\AccountFixture;
|
||||||
|
use Yii;
|
||||||
|
use yii\web\IdentityInterface;
|
||||||
|
use yii\web\UnauthorizedHttpException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @property AccountIdentity $accounts
|
||||||
|
*/
|
||||||
|
class AccountIdentityTest extends DbTestCase {
|
||||||
|
use Specify;
|
||||||
|
|
||||||
|
public function fixtures() {
|
||||||
|
return [
|
||||||
|
'accounts' => [
|
||||||
|
'class' => AccountFixture::class,
|
||||||
|
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFindIdentityByAccessToken() {
|
||||||
|
$this->specify('success validate passed jwt token', function() {
|
||||||
|
$identity = AccountIdentity::findIdentityByAccessToken($this->generateToken());
|
||||||
|
expect($identity)->isInstanceOf(IdentityInterface::class);
|
||||||
|
expect($identity->getId())->equals($this->accounts['admin']['id']);
|
||||||
|
});
|
||||||
|
|
||||||
|
// TODO: нормально оттестить исключение, если токен истёк
|
||||||
|
return;
|
||||||
|
|
||||||
|
$this->specify('get unauthorized with "Token expired message if token valid, but expire"', function() {
|
||||||
|
$originalTimezone = date_default_timezone_get();
|
||||||
|
date_default_timezone_set('America/Los_Angeles');
|
||||||
|
try {
|
||||||
|
$token = $this->generateToken();
|
||||||
|
date_default_timezone_set($originalTimezone);
|
||||||
|
AccountIdentity::findIdentityByAccessToken($token);
|
||||||
|
} catch (Exception $e) {
|
||||||
|
expect($e)->isInstanceOf(UnauthorizedHttpException::class);
|
||||||
|
expect($e->getMessage())->equals('Token expired');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect('if test valid, this should not happened', false)->true();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function generateToken() {
|
||||||
|
/** @var \api\components\User\Component $component */
|
||||||
|
$component = Yii::$app->user;
|
||||||
|
/** @var AccountIdentity $account */
|
||||||
|
$account = AccountIdentity::findOne($this->accounts['admin']['id']);
|
||||||
|
|
||||||
|
return $component->getJWT($account);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,9 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace tests\codeception\api\models\authentication;
|
namespace tests\codeception\api\models\authentication;
|
||||||
|
|
||||||
|
use api\components\User\LoginResult;
|
||||||
use api\models\authentication\ConfirmEmailForm;
|
use api\models\authentication\ConfirmEmailForm;
|
||||||
use Codeception\Specify;
|
use Codeception\Specify;
|
||||||
use common\models\Account;
|
use common\models\Account;
|
||||||
|
use common\models\AccountSession;
|
||||||
use common\models\EmailActivation;
|
use common\models\EmailActivation;
|
||||||
use tests\codeception\api\unit\DbTestCase;
|
use tests\codeception\api\unit\DbTestCase;
|
||||||
use tests\codeception\common\fixtures\EmailActivationFixture;
|
use tests\codeception\common\fixtures\EmailActivationFixture;
|
||||||
@ -31,7 +33,9 @@ class ConfirmEmailFormTest extends DbTestCase {
|
|||||||
$fixture = $this->emailActivations['freshRegistrationConfirmation'];
|
$fixture = $this->emailActivations['freshRegistrationConfirmation'];
|
||||||
$model = $this->createModel($fixture['key']);
|
$model = $this->createModel($fixture['key']);
|
||||||
$this->specify('expect true result', function() use ($model, $fixture) {
|
$this->specify('expect true result', function() use ($model, $fixture) {
|
||||||
expect('model return successful result', $model->confirm())->notEquals(false);
|
$result = $model->confirm();
|
||||||
|
expect($result)->isInstanceOf(LoginResult::class);
|
||||||
|
expect('session was generated', $result->getSession())->isInstanceOf(AccountSession::class);
|
||||||
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
|
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
|
||||||
expect('email activation key is not exist', $activationExists)->false();
|
expect('email activation key is not exist', $activationExists)->false();
|
||||||
/** @var Account $user */
|
/** @var Account $user */
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace tests\codeception\api\models\authentication;
|
namespace tests\codeception\api\models\authentication;
|
||||||
|
|
||||||
|
use api\components\User\LoginResult;
|
||||||
|
use api\models\AccountIdentity;
|
||||||
use api\models\authentication\LoginForm;
|
use api\models\authentication\LoginForm;
|
||||||
use Codeception\Specify;
|
use Codeception\Specify;
|
||||||
use common\models\Account;
|
use common\models\Account;
|
||||||
@ -14,12 +16,22 @@ use Yii;
|
|||||||
class LoginFormTest extends DbTestCase {
|
class LoginFormTest extends DbTestCase {
|
||||||
use Specify;
|
use Specify;
|
||||||
|
|
||||||
|
private $originalRemoteAddr;
|
||||||
|
|
||||||
|
public function setUp() {
|
||||||
|
$this->originalRemoteAddr = $_SERVER['REMOTE_ADDR'] ?? null;
|
||||||
|
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
|
||||||
|
parent::setUp();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function tearDown() {
|
||||||
|
parent::tearDown();
|
||||||
|
$_SERVER['REMOTE_ADDR'] = $this->originalRemoteAddr;
|
||||||
|
}
|
||||||
|
|
||||||
public function fixtures() {
|
public function fixtures() {
|
||||||
return [
|
return [
|
||||||
'accounts' => [
|
'accounts' => AccountFixture::class,
|
||||||
'class' => AccountFixture::class,
|
|
||||||
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
|
|
||||||
],
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,7 +48,7 @@ class LoginFormTest extends DbTestCase {
|
|||||||
$this->specify('no errors if login exists', function () {
|
$this->specify('no errors if login exists', function () {
|
||||||
$model = $this->createModel([
|
$model = $this->createModel([
|
||||||
'login' => 'mr-test',
|
'login' => 'mr-test',
|
||||||
'account' => new Account(),
|
'account' => new AccountIdentity(),
|
||||||
]);
|
]);
|
||||||
$model->validateLogin('login');
|
$model->validateLogin('login');
|
||||||
expect($model->getErrors('login'))->isEmpty();
|
expect($model->getErrors('login'))->isEmpty();
|
||||||
@ -47,7 +59,7 @@ class LoginFormTest extends DbTestCase {
|
|||||||
$this->specify('error.password_incorrect if password invalid', function () {
|
$this->specify('error.password_incorrect if password invalid', function () {
|
||||||
$model = $this->createModel([
|
$model = $this->createModel([
|
||||||
'password' => '87654321',
|
'password' => '87654321',
|
||||||
'account' => new Account(['password' => '12345678']),
|
'account' => new AccountIdentity(['password' => '12345678']),
|
||||||
]);
|
]);
|
||||||
$model->validatePassword('password');
|
$model->validatePassword('password');
|
||||||
expect($model->getErrors('password'))->equals(['error.password_incorrect']);
|
expect($model->getErrors('password'))->equals(['error.password_incorrect']);
|
||||||
@ -56,7 +68,7 @@ class LoginFormTest extends DbTestCase {
|
|||||||
$this->specify('no errors if password valid', function () {
|
$this->specify('no errors if password valid', function () {
|
||||||
$model = $this->createModel([
|
$model = $this->createModel([
|
||||||
'password' => '12345678',
|
'password' => '12345678',
|
||||||
'account' => new Account(['password' => '12345678']),
|
'account' => new AccountIdentity(['password' => '12345678']),
|
||||||
]);
|
]);
|
||||||
$model->validatePassword('password');
|
$model->validatePassword('password');
|
||||||
expect($model->getErrors('password'))->isEmpty();
|
expect($model->getErrors('password'))->isEmpty();
|
||||||
@ -66,7 +78,7 @@ class LoginFormTest extends DbTestCase {
|
|||||||
public function testValidateActivity() {
|
public function testValidateActivity() {
|
||||||
$this->specify('error.account_not_activated if account in not activated state', function () {
|
$this->specify('error.account_not_activated if account in not activated state', function () {
|
||||||
$model = $this->createModel([
|
$model = $this->createModel([
|
||||||
'account' => new Account(['status' => Account::STATUS_REGISTERED]),
|
'account' => new AccountIdentity(['status' => Account::STATUS_REGISTERED]),
|
||||||
]);
|
]);
|
||||||
$model->validateActivity('login');
|
$model->validateActivity('login');
|
||||||
expect($model->getErrors('login'))->equals(['error.account_not_activated']);
|
expect($model->getErrors('login'))->equals(['error.account_not_activated']);
|
||||||
@ -74,7 +86,7 @@ class LoginFormTest extends DbTestCase {
|
|||||||
|
|
||||||
$this->specify('no errors if account active', function () {
|
$this->specify('no errors if account active', function () {
|
||||||
$model = $this->createModel([
|
$model = $this->createModel([
|
||||||
'account' => new Account(['status' => Account::STATUS_ACTIVE]),
|
'account' => new AccountIdentity(['status' => Account::STATUS_ACTIVE]),
|
||||||
]);
|
]);
|
||||||
$model->validateActivity('login');
|
$model->validateActivity('login');
|
||||||
expect($model->getErrors('login'))->isEmpty();
|
expect($model->getErrors('login'))->isEmpty();
|
||||||
@ -86,13 +98,13 @@ class LoginFormTest extends DbTestCase {
|
|||||||
$model = $this->createModel([
|
$model = $this->createModel([
|
||||||
'login' => 'erickskrauch',
|
'login' => 'erickskrauch',
|
||||||
'password' => '12345678',
|
'password' => '12345678',
|
||||||
'account' => new Account([
|
'account' => new AccountIdentity([
|
||||||
'username' => 'erickskrauch',
|
'username' => 'erickskrauch',
|
||||||
'password' => '12345678',
|
'password' => '12345678',
|
||||||
'status' => Account::STATUS_ACTIVE,
|
'status' => Account::STATUS_ACTIVE,
|
||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
expect('model should login user', $model->login())->notEquals(false);
|
expect('model should login user', $model->login())->isInstanceOf(LoginResult::class);
|
||||||
expect('error message should not be set', $model->errors)->isEmpty();
|
expect('error message should not be set', $model->errors)->isEmpty();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -103,7 +115,7 @@ class LoginFormTest extends DbTestCase {
|
|||||||
'login' => $this->accounts['user-with-old-password-type']['username'],
|
'login' => $this->accounts['user-with-old-password-type']['username'],
|
||||||
'password' => '12345678',
|
'password' => '12345678',
|
||||||
]);
|
]);
|
||||||
expect($model->login())->notEquals(false);
|
expect($model->login())->isInstanceOf(LoginResult::class);
|
||||||
expect($model->errors)->isEmpty();
|
expect($model->errors)->isEmpty();
|
||||||
expect($model->getAccount()->password_hash_strategy)->equals(Account::PASS_HASH_STRATEGY_YII2);
|
expect($model->getAccount()->password_hash_strategy)->equals(Account::PASS_HASH_STRATEGY_YII2);
|
||||||
});
|
});
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace tests\codeception\api\models\authentication;
|
namespace tests\codeception\api\models\authentication;
|
||||||
|
|
||||||
|
use api\components\User\LoginResult;
|
||||||
use api\models\authentication\RecoverPasswordForm;
|
use api\models\authentication\RecoverPasswordForm;
|
||||||
use Codeception\Specify;
|
use Codeception\Specify;
|
||||||
use common\models\Account;
|
use common\models\Account;
|
||||||
@ -29,7 +30,9 @@ class RecoverPasswordFormTest extends DbTestCase {
|
|||||||
'newPassword' => '12345678',
|
'newPassword' => '12345678',
|
||||||
'newRePassword' => '12345678',
|
'newRePassword' => '12345678',
|
||||||
]);
|
]);
|
||||||
expect($model->recoverPassword())->notEquals(false);
|
$result = $model->recoverPassword();
|
||||||
|
expect($result)->isInstanceOf(LoginResult::class);
|
||||||
|
expect('session was not generated', $result->getSession())->null();
|
||||||
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
|
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
|
||||||
expect($activationExists)->false();
|
expect($activationExists)->false();
|
||||||
/** @var Account $account */
|
/** @var Account $account */
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace tests\codeception\api\traits;
|
namespace tests\codeception\api\traits;
|
||||||
|
|
||||||
|
use api\models\AccountIdentity;
|
||||||
use api\traits\AccountFinder;
|
use api\traits\AccountFinder;
|
||||||
use Codeception\Specify;
|
use Codeception\Specify;
|
||||||
use common\models\Account;
|
use common\models\Account;
|
||||||
@ -32,6 +33,19 @@ class AccountFinderTest extends DbTestCase {
|
|||||||
expect($account->id)->equals($this->accounts['admin']['id']);
|
expect($account->id)->equals($this->accounts['admin']['id']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$this->specify('founded account for passed login data with changed account model class name', function() {
|
||||||
|
/** @var AccountFinderTestTestClass $model */
|
||||||
|
$model = new class extends AccountFinderTestTestClass {
|
||||||
|
protected function getAccountClassName() {
|
||||||
|
return AccountIdentity::class;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
$model->login = $this->accounts['admin']['email'];
|
||||||
|
$account = $model->getAccount();
|
||||||
|
expect($account)->isInstanceOf(AccountIdentity::class);
|
||||||
|
expect($account->id)->equals($this->accounts['admin']['id']);
|
||||||
|
});
|
||||||
|
|
||||||
$this->specify('null, if account not founded', function() {
|
$this->specify('null, if account not founded', function() {
|
||||||
$model = new AccountFinderTestTestClass();
|
$model = new AccountFinderTestTestClass();
|
||||||
$model->login = 'unexpected';
|
$model->login = 'unexpected';
|
||||||
|
@ -8,4 +8,6 @@ class AccountFixture extends ActiveFixture {
|
|||||||
|
|
||||||
public $modelClass = Account::class;
|
public $modelClass = Account::class;
|
||||||
|
|
||||||
|
public $dataFile = '@tests/codeception/common/fixtures/data/accounts.php';
|
||||||
|
|
||||||
}
|
}
|
||||||
|
17
tests/codeception/common/fixtures/AccountSessionFixture.php
Normal file
17
tests/codeception/common/fixtures/AccountSessionFixture.php
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
namespace tests\codeception\common\fixtures;
|
||||||
|
|
||||||
|
use common\models\AccountSession;
|
||||||
|
use yii\test\ActiveFixture;
|
||||||
|
|
||||||
|
class AccountSessionFixture extends ActiveFixture {
|
||||||
|
|
||||||
|
public $modelClass = AccountSession::class;
|
||||||
|
|
||||||
|
public $dataFile = '@tests/codeception/common/fixtures/data/account-sessions.php';
|
||||||
|
|
||||||
|
public $depends = [
|
||||||
|
AccountFixture::class,
|
||||||
|
];
|
||||||
|
|
||||||
|
}
|
11
tests/codeception/common/fixtures/data/account-sessions.php
Normal file
11
tests/codeception/common/fixtures/data/account-sessions.php
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
return [
|
||||||
|
'admin' => [
|
||||||
|
'id' => 1,
|
||||||
|
'account_id' => 1,
|
||||||
|
'refresh_token' => 'SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz',
|
||||||
|
'last_used_ip' => ip2long('127.0.0.1'),
|
||||||
|
'created_at' => time(),
|
||||||
|
'last_refreshed_at' => time(),
|
||||||
|
],
|
||||||
|
];
|
35
tests/codeception/common/unit/models/AccountSessionTest.php
Normal file
35
tests/codeception/common/unit/models/AccountSessionTest.php
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
namespace codeception\common\unit\models;
|
||||||
|
|
||||||
|
use Codeception\Specify;
|
||||||
|
use common\models\AccountSession;
|
||||||
|
use tests\codeception\common\unit\TestCase;
|
||||||
|
|
||||||
|
class AccountSessionTest extends TestCase {
|
||||||
|
use Specify;
|
||||||
|
|
||||||
|
public function testGenerateRefreshToken() {
|
||||||
|
$this->specify('method call will set refresh_token value', function() {
|
||||||
|
$model = new AccountSession();
|
||||||
|
$model->generateRefreshToken();
|
||||||
|
expect($model->refresh_token)->notNull();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSetIp() {
|
||||||
|
$this->specify('method should convert passed ip string to long', function() {
|
||||||
|
$model = new AccountSession();
|
||||||
|
$model->setIp('127.0.0.1');
|
||||||
|
expect($model->last_used_ip)->equals(2130706433);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testGetReadableIp() {
|
||||||
|
$this->specify('method should convert stored ip long into readable ip string', function() {
|
||||||
|
$model = new AccountSession();
|
||||||
|
$model->last_used_ip = 2130706433;
|
||||||
|
expect($model->getReadableIp())->equals('127.0.0.1');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,5 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
/**
|
return [
|
||||||
* Application configuration for all api test types
|
'components' => [
|
||||||
*/
|
'user' => [
|
||||||
return [];
|
'secret' => 'tests-secret-key',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
Loading…
x
Reference in New Issue
Block a user