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-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\Encryption\Factory;
|
|
|
|
|
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-09-06 22:40:42 +05:30
|
|
|
|
* @method AccountIdentity|null getIdentity($autoRenew = true)
|
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;
|
|
|
|
|
|
|
|
|
|
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;
|
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
|
|
|
|
// Если мы не сохраняем сессию, то токен должен жить подольше, чтобы
|
|
|
|
|
// не прогорала сессия во время работы с аккаунтом
|
|
|
|
|
$token->addClaim(new Claim\Expiration(time() + 60 * 60 * 24 * 7));
|
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-05-31 03:33:30 +05:30
|
|
|
|
public function renew(AccountSession $session) {
|
|
|
|
|
$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);
|
|
|
|
|
$context = new VerificationContext(Factory::create($this->getAlgorithm()));
|
|
|
|
|
$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. Возможные кейсы:
|
|
|
|
|
* - Юзер не авторизован
|
|
|
|
|
* - Почему-то нет заголовка с токеном
|
|
|
|
|
* - Во время проверки токена возникла ошибка, что привело к исключению
|
|
|
|
|
* - В токене не найдено ключа сессии. Такое возможно, если юзер выбрал "не запоминать меня" или просто старые
|
|
|
|
|
* токены, без поддержки сохранения используемой сессии
|
|
|
|
|
*
|
|
|
|
|
* @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;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$authHeader = Yii::$app->request->getHeaders()->get('Authorization');
|
|
|
|
|
if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$token = $matches[1];
|
|
|
|
|
try {
|
|
|
|
|
$token = $this->parseToken($token);
|
|
|
|
|
} 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) {
|
|
|
|
|
$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()),
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|