2016-05-30 05:14:17 +05:30
|
|
|
|
<?php
|
|
|
|
|
namespace api\components\User;
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
use api\exceptions\ThisShouldNotHappenException;
|
|
|
|
|
use common\models\Account;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
use common\models\AccountSession;
|
2017-09-19 22:36:16 +05:30
|
|
|
|
use common\rbac\Roles as R;
|
2016-11-04 14:53:04 +05:30
|
|
|
|
use DateInterval;
|
|
|
|
|
use DateTime;
|
2016-06-05 19:31:35 +05:30
|
|
|
|
use Emarref\Jwt\Algorithm\AlgorithmInterface;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
use Emarref\Jwt\Algorithm\Hs256;
|
|
|
|
|
use Emarref\Jwt\Claim;
|
|
|
|
|
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
|
2016-06-05 19:31:35 +05:30
|
|
|
|
use Emarref\Jwt\Exception\VerificationException;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
use Emarref\Jwt\Token;
|
2016-06-05 19:31:35 +05:30
|
|
|
|
use Emarref\Jwt\Verification\Context as VerificationContext;
|
2017-09-19 22:36:16 +05:30
|
|
|
|
use Exception;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
use Yii;
|
|
|
|
|
use yii\base\InvalidConfigException;
|
2017-12-02 23:34:48 +05:30
|
|
|
|
use yii\web\UnauthorizedHttpException;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
use yii\web\User as YiiUserComponent;
|
|
|
|
|
|
2016-06-05 19:31:35 +05:30
|
|
|
|
/**
|
|
|
|
|
* @property AccountSession|null $activeSession
|
2017-09-19 22:36:16 +05:30
|
|
|
|
* @property IdentityInterface|null $identity
|
2016-07-17 23:16:04 +05:30
|
|
|
|
*
|
2017-09-19 22:36:16 +05:30
|
|
|
|
* @method IdentityInterface|null loginByAccessToken($token, $type = null)
|
|
|
|
|
* @method IdentityInterface|null getIdentity($autoRenew = true)
|
2016-06-05 19:31:35 +05:30
|
|
|
|
*/
|
2016-05-30 05:14:17 +05:30
|
|
|
|
class Component extends YiiUserComponent {
|
|
|
|
|
|
2017-12-02 23:34:48 +05:30
|
|
|
|
public const KEEP_MINECRAFT_SESSIONS = 1;
|
|
|
|
|
public const KEEP_SITE_SESSIONS = 2;
|
|
|
|
|
public const KEEP_CURRENT_SESSION = 4;
|
2017-09-19 22:36:16 +05:30
|
|
|
|
|
2017-12-02 23:34:48 +05:30
|
|
|
|
public const JWT_SUBJECT_PREFIX = 'ely|';
|
2017-02-23 04:31:32 +05:30
|
|
|
|
|
2016-08-04 03:37:21 +05:30
|
|
|
|
public $enableSession = false;
|
|
|
|
|
|
|
|
|
|
public $loginUrl = null;
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
public $identityClass = Identity::class;
|
2016-08-04 03:37:21 +05:30
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
public $secret;
|
|
|
|
|
|
2016-11-04 14:53:04 +05:30
|
|
|
|
public $expirationTimeout = 'PT1H';
|
|
|
|
|
|
|
|
|
|
public $sessionTimeout = 'P7D';
|
2016-05-30 05:14:17 +05:30
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
/**
|
|
|
|
|
* @var Token[]
|
|
|
|
|
*/
|
|
|
|
|
private static $parsedTokensCache = [];
|
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
public function init() {
|
|
|
|
|
parent::init();
|
|
|
|
|
if (!$this->secret) {
|
|
|
|
|
throw new InvalidConfigException('secret must be specified');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-30 03:14:05 +05:30
|
|
|
|
public function findIdentityByAccessToken($accessToken): ?IdentityInterface {
|
2017-12-02 23:34:48 +05:30
|
|
|
|
if (empty($accessToken)) {
|
2017-09-30 03:14:05 +05:30
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
/** @var \api\components\User\IdentityInterface|string $identityClass */
|
|
|
|
|
$identityClass = $this->identityClass;
|
|
|
|
|
try {
|
|
|
|
|
return $identityClass::findIdentityByAccessToken($accessToken);
|
2017-12-02 23:34:48 +05:30
|
|
|
|
} catch (UnauthorizedHttpException $e) {
|
|
|
|
|
// Do nothing. It's okay to catch this.
|
2017-09-19 22:36:16 +05:30
|
|
|
|
} catch (Exception $e) {
|
|
|
|
|
Yii::error($e);
|
2016-05-30 05:14:17 +05:30
|
|
|
|
}
|
2017-12-02 23:34:48 +05:30
|
|
|
|
|
|
|
|
|
return null;
|
2017-09-19 22:36:16 +05:30
|
|
|
|
}
|
2016-05-30 05:14:17 +05:30
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
public function createJwtAuthenticationToken(Account $account, bool $rememberMe): AuthenticationResult {
|
2016-05-30 05:14:17 +05:30
|
|
|
|
$ip = Yii::$app->request->userIP;
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$token = $this->createToken($account);
|
2016-05-30 05:14:17 +05:30
|
|
|
|
if ($rememberMe) {
|
|
|
|
|
$session = new AccountSession();
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$session->account_id = $account->id;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
$session->setIp($ip);
|
|
|
|
|
$session->generateRefreshToken();
|
|
|
|
|
if (!$session->save()) {
|
2017-09-19 22:36:16 +05:30
|
|
|
|
throw new ThisShouldNotHappenException('Cannot save account session model');
|
2016-05-30 05:14:17 +05:30
|
|
|
|
}
|
2016-06-05 19:31:35 +05:30
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$token->addClaim(new Claim\JwtId($session->id));
|
2016-05-30 05:14:17 +05:30
|
|
|
|
} else {
|
|
|
|
|
$session = null;
|
2017-09-19 22:36:16 +05:30
|
|
|
|
// Если мы не сохраняем сессию, то токен должен жить подольше,
|
|
|
|
|
// чтобы не прогорала сессия во время работы с аккаунтом
|
2016-11-04 14:53:04 +05:30
|
|
|
|
$token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout))));
|
2016-05-30 05:14:17 +05:30
|
|
|
|
}
|
|
|
|
|
|
2016-06-05 19:31:35 +05:30
|
|
|
|
$jwt = $this->serializeToken($token);
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
return new AuthenticationResult($account, $jwt, $session);
|
2016-05-30 05:14:17 +05:30
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
public function renewJwtAuthenticationToken(AccountSession $session): AuthenticationResult {
|
2016-05-31 03:33:30 +05:30
|
|
|
|
$transaction = Yii::$app->db->beginTransaction();
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$account = $session->account;
|
|
|
|
|
$token = $this->createToken($account);
|
|
|
|
|
$token->addClaim(new Claim\JwtId($session->id));
|
|
|
|
|
$jwt = $this->serializeToken($token);
|
2016-05-31 03:33:30 +05:30
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$result = new AuthenticationResult($account, $jwt, $session);
|
2016-05-31 03:33:30 +05:30
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$session->setIp(Yii::$app->request->userIP);
|
|
|
|
|
$session->last_refreshed_at = time();
|
|
|
|
|
if (!$session->save()) {
|
|
|
|
|
throw new ThisShouldNotHappenException('Cannot update session info');
|
2016-05-31 03:33:30 +05:30
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$transaction->commit();
|
|
|
|
|
|
2016-05-31 03:33:30 +05:30
|
|
|
|
return $result;
|
|
|
|
|
}
|
|
|
|
|
|
2016-06-05 19:31:35 +05:30
|
|
|
|
/**
|
|
|
|
|
* @param string $jwtString
|
|
|
|
|
* @return Token распаршенный токен
|
|
|
|
|
* @throws VerificationException если один из Claims не пройдёт проверку
|
|
|
|
|
*/
|
2017-09-19 22:36:16 +05:30
|
|
|
|
public function parseToken(string $jwtString): Token {
|
|
|
|
|
$token = &self::$parsedTokensCache[$jwtString];
|
|
|
|
|
if ($token === null) {
|
|
|
|
|
$jwt = new Jwt();
|
2018-01-01 19:42:15 +05:30
|
|
|
|
try {
|
|
|
|
|
$notVerifiedToken = $jwt->deserialize($jwtString);
|
|
|
|
|
} catch (Exception $e) {
|
|
|
|
|
throw new VerificationException('Incorrect token encoding', 0, $e);
|
|
|
|
|
}
|
2017-09-19 22:36:16 +05:30
|
|
|
|
|
|
|
|
|
$context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm()));
|
|
|
|
|
$context->setSubject(self::JWT_SUBJECT_PREFIX);
|
|
|
|
|
$jwt->verify($notVerifiedToken, $context);
|
2016-06-05 19:31:35 +05:30
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$token = $notVerifiedToken;
|
|
|
|
|
}
|
2016-05-30 05:14:17 +05:30
|
|
|
|
|
2016-06-05 19:31:35 +05:30
|
|
|
|
return $token;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2016-06-05 19:31:35 +05:30
|
|
|
|
* Метод находит AccountSession модель, относительно которой был выдан текущий JWT токен.
|
|
|
|
|
* В случае, если на пути поиска встретится ошибка, будет возвращено значение null. Возможные кейсы:
|
|
|
|
|
* - Юзер не авторизован
|
|
|
|
|
* - Почему-то нет заголовка с токеном
|
|
|
|
|
* - Во время проверки токена возникла ошибка, что привело к исключению
|
2016-11-04 14:53:04 +05:30
|
|
|
|
* - В токене не найдено ключа сессии. Такое возможно, если юзер выбрал "не запоминать меня"
|
|
|
|
|
* или просто старые токены, без поддержки сохранения используемой сессии
|
2016-06-05 19:31:35 +05:30
|
|
|
|
*
|
|
|
|
|
* @return AccountSession|null
|
2016-05-30 05:14:17 +05:30
|
|
|
|
*/
|
2017-09-19 22:36:16 +05:30
|
|
|
|
public function getActiveSession(): ?AccountSession {
|
2016-06-05 19:31:35 +05:30
|
|
|
|
if ($this->getIsGuest()) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-11 20:28:08 +05:30
|
|
|
|
$bearer = $this->getBearerToken();
|
2017-09-19 22:36:16 +05:30
|
|
|
|
if ($bearer === null) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2016-06-05 19:31:35 +05:30
|
|
|
|
try {
|
2016-12-11 20:28:08 +05:30
|
|
|
|
$token = $this->parseToken($bearer);
|
2016-06-05 19:31:35 +05:30
|
|
|
|
} catch (VerificationException $e) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
$sessionId = $token->getPayload()->findClaimByName(Claim\JwtId::NAME);
|
2016-06-05 19:31:35 +05:30
|
|
|
|
if ($sessionId === null) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return AccountSession::findOne($sessionId->getValue());
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
public function terminateSessions(Account $account, int $mode = 0): void {
|
|
|
|
|
$currentSession = null;
|
|
|
|
|
if ($mode & self::KEEP_CURRENT_SESSION) {
|
|
|
|
|
$currentSession = $this->getActiveSession();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!($mode & self::KEEP_SITE_SESSIONS)) {
|
|
|
|
|
foreach ($account->sessions as $session) {
|
|
|
|
|
if ($currentSession === null || $currentSession->id !== $session->id) {
|
2017-02-23 04:31:32 +05:30
|
|
|
|
$session->delete();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
if (!($mode & self::KEEP_MINECRAFT_SESSIONS)) {
|
|
|
|
|
foreach ($account->minecraftAccessKeys as $minecraftAccessKey) {
|
2017-02-23 04:31:32 +05:30
|
|
|
|
$minecraftAccessKey->delete();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
public function getAlgorithm(): AlgorithmInterface {
|
2016-05-30 05:14:17 +05:30
|
|
|
|
return new Hs256($this->secret);
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
protected function serializeToken(Token $token): string {
|
2016-06-05 19:31:35 +05:30
|
|
|
|
return (new Jwt())->serialize($token, EncryptionFactory::create($this->getAlgorithm()));
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
|
protected function createToken(Account $account): Token {
|
2016-06-05 19:31:35 +05:30
|
|
|
|
$token = new Token();
|
2017-09-19 22:36:16 +05:30
|
|
|
|
foreach($this->getClaims($account) as $claim) {
|
2016-06-05 19:31:35 +05:30
|
|
|
|
$token->addClaim($claim);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $token;
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
/**
|
2017-09-19 22:36:16 +05:30
|
|
|
|
* @param Account $account
|
2016-05-30 05:14:17 +05:30
|
|
|
|
* @return Claim\AbstractClaim[]
|
|
|
|
|
*/
|
2017-09-19 22:36:16 +05:30
|
|
|
|
protected function getClaims(Account $account): array {
|
2016-11-04 14:53:04 +05:30
|
|
|
|
$currentTime = new DateTime();
|
2016-05-30 05:14:17 +05:30
|
|
|
|
|
|
|
|
|
return [
|
2017-09-19 22:36:16 +05:30
|
|
|
|
new ScopesClaim([R::ACCOUNTS_WEB_USER]),
|
2016-05-30 05:14:17 +05:30
|
|
|
|
new Claim\IssuedAt($currentTime),
|
2016-11-04 14:53:04 +05:30
|
|
|
|
new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))),
|
2017-09-19 22:36:16 +05:30
|
|
|
|
new Claim\Subject(self::JWT_SUBJECT_PREFIX . $account->id),
|
2016-05-30 05:14:17 +05:30
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-11 20:28:08 +05:30
|
|
|
|
private function getBearerToken() {
|
|
|
|
|
$authHeader = Yii::$app->request->getHeaders()->get('Authorization');
|
|
|
|
|
if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $matches[1];
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
}
|