2016-05-30 05:14:17 +05:30
|
|
|
|
<?php
|
|
|
|
|
namespace api\components\User;
|
|
|
|
|
|
2016-05-31 03:33:30 +05:30
|
|
|
|
use api\models\AccountIdentity;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
use common\models\AccountSession;
|
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\Jwt;
|
|
|
|
|
use Emarref\Jwt\Token;
|
2016-06-05 19:31:35 +05:30
|
|
|
|
use Emarref\Jwt\Verification\Context as VerificationContext;
|
2016-05-30 05:14:17 +05:30
|
|
|
|
use Yii;
|
|
|
|
|
use yii\base\ErrorException;
|
|
|
|
|
use yii\base\InvalidConfigException;
|
|
|
|
|
use yii\web\IdentityInterface;
|
|
|
|
|
use yii\web\User as YiiUserComponent;
|
|
|
|
|
|
2016-06-05 19:31:35 +05:30
|
|
|
|
/**
|
|
|
|
|
* @property AccountSession|null $activeSession
|
2016-07-17 23:16:04 +05:30
|
|
|
|
* @property AccountIdentity|null $identity
|
|
|
|
|
*
|
2016-12-11 20:28:08 +05:30
|
|
|
|
* @method AccountIdentity|null loginByAccessToken($token, $type = null)
|
2016-06-05 19:31:35 +05:30
|
|
|
|
*/
|
2016-05-30 05:14:17 +05:30
|
|
|
|
class Component extends YiiUserComponent {
|
|
|
|
|
|
2016-08-04 03:37:21 +05:30
|
|
|
|
public $enableSession = false;
|
|
|
|
|
|
|
|
|
|
public $loginUrl = null;
|
|
|
|
|
|
|
|
|
|
public $identityClass = AccountIdentity::class;
|
|
|
|
|
|
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
|
|
|
|
|
2016-12-11 20:28:08 +05:30
|
|
|
|
private $_identity;
|
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
public function init() {
|
|
|
|
|
parent::init();
|
|
|
|
|
if (!$this->secret) {
|
|
|
|
|
throw new InvalidConfigException('secret must be specified');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-11 20:28:08 +05:30
|
|
|
|
/**
|
|
|
|
|
* @param bool $autoRenew
|
|
|
|
|
* @return null|AccountIdentity
|
|
|
|
|
*/
|
|
|
|
|
public function getIdentity($autoRenew = true) {
|
|
|
|
|
$result = parent::getIdentity($autoRenew);
|
|
|
|
|
if ($result === null && $this->_identity !== false) {
|
|
|
|
|
$bearer = $this->getBearerToken();
|
|
|
|
|
if ($bearer !== null) {
|
|
|
|
|
$result = $this->loginByAccessToken($bearer);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$this->_identity = $result ?: false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
/**
|
|
|
|
|
* @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;
|
2016-06-05 19:31:35 +05:30
|
|
|
|
$token = $this->createToken($identity);
|
2016-05-30 05:14:17 +05:30
|
|
|
|
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');
|
|
|
|
|
}
|
2016-06-05 19:31:35 +05:30
|
|
|
|
|
|
|
|
|
$token->addClaim(new SessionIdClaim($session->id));
|
2016-05-30 05:14:17 +05:30
|
|
|
|
} else {
|
|
|
|
|
$session = null;
|
2016-07-17 22:24:33 +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);
|
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
Yii::info("User '{$id}' logged in from {$ip}.", __METHOD__);
|
|
|
|
|
|
|
|
|
|
$result = new LoginResult($identity, $jwt, $session);
|
|
|
|
|
$this->afterLogin($identity, false, $rememberMe);
|
|
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-13 03:40:05 +05:30
|
|
|
|
public function renew(AccountSession $session): RenewResult {
|
2016-05-31 03:33:30 +05:30
|
|
|
|
$account = $session->account;
|
|
|
|
|
$transaction = Yii::$app->db->beginTransaction();
|
|
|
|
|
try {
|
|
|
|
|
$identity = new AccountIdentity($account->attributes);
|
2016-06-05 19:31:35 +05:30
|
|
|
|
$token = $this->createToken($identity);
|
|
|
|
|
$jwt = $this->serializeToken($token);
|
2016-05-31 03:33:30 +05:30
|
|
|
|
|
|
|
|
|
$result = new RenewResult($identity, $jwt);
|
|
|
|
|
|
|
|
|
|
$session->setIp(Yii::$app->request->userIP);
|
|
|
|
|
$session->last_refreshed_at = time();
|
|
|
|
|
if (!$session->save()) {
|
|
|
|
|
throw new ErrorException('Cannot update session info');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$transaction->commit();
|
|
|
|
|
} catch (ErrorException $e) {
|
|
|
|
|
$transaction->rollBack();
|
|
|
|
|
throw $e;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
|
}
|
|
|
|
|
|
2016-06-05 19:31:35 +05:30
|
|
|
|
/**
|
|
|
|
|
* @param string $jwtString
|
|
|
|
|
* @return Token распаршенный токен
|
|
|
|
|
* @throws VerificationException если один из Claims не пройдёт проверку
|
|
|
|
|
*/
|
|
|
|
|
public function parseToken(string $jwtString) : Token {
|
|
|
|
|
$hostInfo = Yii::$app->request->hostInfo;
|
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
$jwt = new Jwt();
|
2016-06-05 19:31:35 +05:30
|
|
|
|
$token = $jwt->deserialize($jwtString);
|
2016-09-19 13:48:52 +05:30
|
|
|
|
$context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm()));
|
2016-06-05 19:31:35 +05:30
|
|
|
|
$context->setAudience($hostInfo);
|
|
|
|
|
$context->setIssuer($hostInfo);
|
|
|
|
|
$jwt->verify($token, $context);
|
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
|
|
|
|
*/
|
2016-06-05 19:31:35 +05:30
|
|
|
|
public function getActiveSession() {
|
|
|
|
|
if ($this->getIsGuest()) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-11 20:28:08 +05:30
|
|
|
|
$bearer = $this->getBearerToken();
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$sessionId = $token->getPayload()->findClaimByName(SessionIdClaim::NAME);
|
|
|
|
|
if ($sessionId === null) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return AccountSession::findOne($sessionId->getValue());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function getAlgorithm() : AlgorithmInterface {
|
2016-05-30 05:14:17 +05:30
|
|
|
|
return new Hs256($this->secret);
|
|
|
|
|
}
|
|
|
|
|
|
2016-06-05 19:31:35 +05:30
|
|
|
|
protected function serializeToken(Token $token) : string {
|
|
|
|
|
return (new Jwt())->serialize($token, EncryptionFactory::create($this->getAlgorithm()));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function createToken(IdentityInterface $identity) : Token {
|
|
|
|
|
$token = new Token();
|
|
|
|
|
foreach($this->getClaims($identity) as $claim) {
|
|
|
|
|
$token->addClaim($claim);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $token;
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-30 05:14:17 +05:30
|
|
|
|
/**
|
|
|
|
|
* @param IdentityInterface $identity
|
|
|
|
|
* @return Claim\AbstractClaim[]
|
|
|
|
|
*/
|
|
|
|
|
protected function getClaims(IdentityInterface $identity) {
|
2016-11-04 14:53:04 +05:30
|
|
|
|
$currentTime = new DateTime();
|
2016-05-30 05:14:17 +05:30
|
|
|
|
$hostInfo = Yii::$app->request->hostInfo;
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
new Claim\Audience($hostInfo),
|
|
|
|
|
new Claim\Issuer($hostInfo),
|
|
|
|
|
new Claim\IssuedAt($currentTime),
|
2016-11-04 14:53:04 +05:30
|
|
|
|
new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))),
|
2016-05-30 05:14:17 +05:30
|
|
|
|
new Claim\JwtId($identity->getId()),
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-11 20:28:08 +05:30
|
|
|
|
/**
|
|
|
|
|
* @return ?string
|
|
|
|
|
*/
|
|
|
|
|
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
|
|
|
|
}
|