Реорганизована выдача JWT токенов

Добавлен механизм сохранения сессий и refresh_token
This commit is contained in:
ErickSkrauch
2016-05-30 02:44:17 +03:00
parent 98c01625d1
commit bdc96d82c1
34 changed files with 676 additions and 73 deletions

View File

@@ -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');
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}