2016-05-12 14:20:30 +05:30
|
|
|
<?php
|
|
|
|
namespace api\models;
|
|
|
|
|
|
|
|
use common\models\Account;
|
2016-06-05 19:31:35 +05:30
|
|
|
use Emarref\Jwt\Claim\JwtId;
|
2016-05-30 05:14:17 +05:30
|
|
|
use Emarref\Jwt\Exception\VerificationException;
|
2016-06-05 19:31:35 +05:30
|
|
|
use Emarref\Jwt\Token;
|
2016-05-30 05:14:17 +05:30
|
|
|
use Yii;
|
2016-05-12 14:20:30 +05:30
|
|
|
use yii\base\NotSupportedException;
|
2016-05-30 05:14:17 +05:30
|
|
|
use yii\helpers\StringHelper;
|
2016-05-12 14:20:30 +05:30
|
|
|
use yii\web\IdentityInterface;
|
2016-05-30 05:14:17 +05:30
|
|
|
use yii\web\UnauthorizedHttpException;
|
2016-05-12 14:20:30 +05:30
|
|
|
|
|
|
|
class AccountIdentity extends Account implements IdentityInterface {
|
2016-05-30 05:14:17 +05:30
|
|
|
/**
|
|
|
|
* @inheritdoc
|
|
|
|
*/
|
|
|
|
public static function findIdentityByAccessToken($token, $type = null) {
|
|
|
|
/** @var \api\components\User\Component $component */
|
|
|
|
$component = Yii::$app->user;
|
|
|
|
try {
|
2016-06-05 19:31:35 +05:30
|
|
|
$token = $component->parseToken($token);
|
2016-05-30 05:14:17 +05:30
|
|
|
} catch (VerificationException $e) {
|
|
|
|
if (StringHelper::startsWith($e->getMessage(), 'Token expired at')) {
|
|
|
|
$message = 'Token expired';
|
|
|
|
} else {
|
|
|
|
$message = 'Incorrect token';
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new UnauthorizedHttpException($message);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Если исключение выше не случилось, то значит всё оке
|
2016-06-05 19:31:35 +05:30
|
|
|
/** @var JwtId $jti */
|
|
|
|
$jti = $token->getPayload()->findClaimByName(JwtId::NAME);
|
2016-05-30 05:14:17 +05:30
|
|
|
$account = static::findOne($jti->getValue());
|
|
|
|
if ($account === null) {
|
|
|
|
throw new UnauthorizedHttpException('Invalid token');
|
|
|
|
}
|
|
|
|
|
|
|
|
return $account;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @inheritdoc
|
|
|
|
*/
|
|
|
|
public function getId() {
|
|
|
|
return $this->id;
|
|
|
|
}
|
|
|
|
|
2016-05-12 14:20:30 +05:30
|
|
|
/**
|
|
|
|
* @inheritdoc
|
|
|
|
*/
|
|
|
|
public static function findIdentity($id) {
|
|
|
|
return static::findOne($id);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @inheritdoc
|
|
|
|
*/
|
|
|
|
public function getAuthKey() {
|
|
|
|
throw new NotSupportedException('This method used for cookie auth, except we using JWT tokens');
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @inheritdoc
|
|
|
|
*/
|
|
|
|
public function validateAuthKey($authKey) {
|
2016-05-30 05:14:17 +05:30
|
|
|
throw new NotSupportedException('This method used for cookie auth, except we using JWT tokens');
|
2016-05-12 14:20:30 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
}
|