2019-08-01 14:47:12 +05:30
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace api\components\Tokens;
|
|
|
|
|
2019-08-02 05:59:20 +05:30
|
|
|
use Carbon\Carbon;
|
2019-08-01 14:47:12 +05:30
|
|
|
use common\models\Account;
|
|
|
|
use common\models\AccountSession;
|
|
|
|
use Lcobucci\JWT\Token;
|
2019-09-22 02:47:21 +05:30
|
|
|
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
|
|
|
|
use League\OAuth2\Server\Entities\ScopeEntityInterface;
|
2019-08-01 14:47:12 +05:30
|
|
|
use Yii;
|
|
|
|
|
|
|
|
class TokensFactory {
|
|
|
|
|
|
|
|
public const SUB_ACCOUNT_PREFIX = 'ely|';
|
2019-09-22 02:47:21 +05:30
|
|
|
public const AUD_CLIENT_PREFIX = 'client|';
|
2019-08-01 14:47:12 +05:30
|
|
|
|
|
|
|
public static function createForAccount(Account $account, AccountSession $session = null): Token {
|
|
|
|
$payloads = [
|
|
|
|
'ely-scopes' => 'accounts_web_user',
|
2019-09-22 02:47:21 +05:30
|
|
|
'sub' => self::buildSub($account->id),
|
2019-08-01 14:47:12 +05:30
|
|
|
];
|
|
|
|
if ($session === null) {
|
|
|
|
// If we don't remember a session, the token should live longer
|
|
|
|
// so that the session doesn't end while working with the account
|
2019-08-02 05:59:20 +05:30
|
|
|
$payloads['exp'] = Carbon::now()->addDays(7)->getTimestamp();
|
2019-08-01 14:47:12 +05:30
|
|
|
} else {
|
|
|
|
$payloads['jti'] = $session->id;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Yii::$app->tokens->create($payloads);
|
|
|
|
}
|
|
|
|
|
2019-09-22 02:47:21 +05:30
|
|
|
public static function createForOAuthClient(AccessTokenEntityInterface $accessToken): Token {
|
|
|
|
$payloads = [
|
|
|
|
'aud' => self::buildAud($accessToken->getClient()->getIdentifier()),
|
2019-09-23 03:33:36 +05:30
|
|
|
'ely-scopes' => implode(',', array_map(static function(ScopeEntityInterface $scope): string {
|
2019-09-22 02:47:21 +05:30
|
|
|
return $scope->getIdentifier();
|
2019-09-23 03:33:36 +05:30
|
|
|
}, $accessToken->getScopes())),
|
2019-09-22 02:47:21 +05:30
|
|
|
'exp' => $accessToken->getExpiryDateTime()->getTimestamp(),
|
|
|
|
];
|
|
|
|
if ($accessToken->getUserIdentifier() !== null) {
|
|
|
|
$payloads['sub'] = self::buildSub($accessToken->getUserIdentifier());
|
|
|
|
}
|
|
|
|
|
|
|
|
return Yii::$app->tokens->create($payloads);
|
|
|
|
}
|
|
|
|
|
|
|
|
private static function buildSub(int $accountId): string {
|
|
|
|
return self::SUB_ACCOUNT_PREFIX . $accountId;
|
|
|
|
}
|
|
|
|
|
|
|
|
private static function buildAud(string $clientId): string {
|
|
|
|
return self::AUD_CLIENT_PREFIX . $clientId;
|
|
|
|
}
|
|
|
|
|
2019-08-01 14:47:12 +05:30
|
|
|
}
|