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:
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',
|
||||
'components' => [
|
||||
'user' => [
|
||||
'class' => \api\components\User\Component::class,
|
||||
'identityClass' => \api\models\AccountIdentity::class,
|
||||
'enableSession' => false,
|
||||
'loginUrl' => null,
|
||||
'secret' => $params['userSecret'],
|
||||
],
|
||||
'log' => [
|
||||
'traceLevel' => YII_DEBUG ? 3 : 0,
|
||||
|
@@ -40,7 +40,7 @@ class AuthenticationController extends Controller {
|
||||
public function actionLogin() {
|
||||
$model = new LoginForm();
|
||||
$model->load(Yii::$app->request->post());
|
||||
if (($jwt = $model->login()) === false) {
|
||||
if (($result = $model->login()) === false) {
|
||||
$data = [
|
||||
'success' => false,
|
||||
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
||||
@@ -53,10 +53,9 @@ class AuthenticationController extends Controller {
|
||||
return $data;
|
||||
}
|
||||
|
||||
return [
|
||||
return array_merge([
|
||||
'success' => true,
|
||||
'jwt' => $jwt,
|
||||
];
|
||||
], $result->getAsResponse());
|
||||
}
|
||||
|
||||
public function actionForgotPassword() {
|
||||
@@ -98,17 +97,16 @@ class AuthenticationController extends Controller {
|
||||
public function actionRecoverPassword() {
|
||||
$model = new RecoverPasswordForm();
|
||||
$model->load(Yii::$app->request->post());
|
||||
if (($jwt = $model->recoverPassword()) === false) {
|
||||
if (($result = $model->recoverPassword()) === false) {
|
||||
return [
|
||||
'success' => false,
|
||||
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
return array_merge([
|
||||
'success' => true,
|
||||
'jwt' => $jwt,
|
||||
];
|
||||
], $result->getAsResponse());
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -15,7 +15,7 @@ class Controller extends \yii\rest\Controller {
|
||||
$parentBehaviors = parent::behaviors();
|
||||
// Добавляем авторизатор для входа по jwt токенам
|
||||
$parentBehaviors['authenticator'] = [
|
||||
'class' => HttpBearerAuth::className(),
|
||||
'class' => HttpBearerAuth::class,
|
||||
];
|
||||
|
||||
// xml нам не понадобится
|
||||
|
@@ -79,17 +79,16 @@ class SignupController extends Controller {
|
||||
public function actionConfirm() {
|
||||
$model = new ConfirmEmailForm();
|
||||
$model->load(Yii::$app->request->post());
|
||||
if (!($jwt = $model->confirm())) {
|
||||
if (!($result = $model->confirm())) {
|
||||
return [
|
||||
'success' => false,
|
||||
'errors' => $this->normalizeModelErrors($model->getErrors()),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
return array_merge([
|
||||
'success' => true,
|
||||
'jwt' => $jwt,
|
||||
];
|
||||
], $result->getAsResponse());
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -2,17 +2,61 @@
|
||||
namespace api\models;
|
||||
|
||||
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\helpers\StringHelper;
|
||||
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 {
|
||||
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
@@ -31,7 +75,7 @@ class AccountIdentity extends Account implements IdentityInterface {
|
||||
* @inheritdoc
|
||||
*/
|
||||
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
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\models\AccountIdentity;
|
||||
use api\models\base\KeyConfirmationForm;
|
||||
use common\models\Account;
|
||||
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
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\models\AccountIdentity;
|
||||
use api\models\base\ApiForm;
|
||||
use api\traits\AccountFinder;
|
||||
use common\models\Account;
|
||||
use Yii;
|
||||
|
||||
/**
|
||||
* @method AccountIdentity|null getAccount()
|
||||
*/
|
||||
class LoginForm extends ApiForm {
|
||||
use AccountFinder;
|
||||
|
||||
public $login;
|
||||
public $password;
|
||||
public $rememberMe = true;
|
||||
public $rememberMe = false;
|
||||
|
||||
public function rules() {
|
||||
return [
|
||||
@@ -31,7 +35,7 @@ class LoginForm extends ApiForm {
|
||||
|
||||
public function validateLogin($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
if (!$this->getAccount()) {
|
||||
if ($this->getAccount() === null) {
|
||||
$this->addError($attribute, 'error.' . $attribute . '_not_exist');
|
||||
}
|
||||
}
|
||||
@@ -40,7 +44,7 @@ class LoginForm extends ApiForm {
|
||||
public function validatePassword($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
$account = $this->getAccount();
|
||||
if (!$account || !$account->validatePassword($this->password)) {
|
||||
if ($account === null || !$account->validatePassword($this->password)) {
|
||||
$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() {
|
||||
if (!$this->validate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->rememberMe) {
|
||||
// TODO: здесь нужно записать какую-то
|
||||
}
|
||||
|
||||
$account = $this->getAccount();
|
||||
if ($account->password_hash_strategy === Account::PASS_HASH_STRATEGY_OLD_ELY) {
|
||||
$account->setPassword($this->password);
|
||||
$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
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\models\AccountIdentity;
|
||||
use api\models\base\KeyConfirmationForm;
|
||||
use common\models\EmailActivation;
|
||||
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() {
|
||||
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;
|
||||
@@ -24,4 +25,11 @@ trait AccountFinder {
|
||||
return strpos($this->getLogin(), '@') ? 'email' : 'username';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Account|string
|
||||
*/
|
||||
protected function getAccountClassName() {
|
||||
return Account::class;
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user