2019-12-09 22:01:54 +05:30
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace api\components\Tokens;
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
use Lcobucci\JWT\UnencryptedToken;
|
2019-12-09 22:01:54 +05:30
|
|
|
use Yii;
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
final readonly class TokenReader {
|
2019-12-09 22:01:54 +05:30
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function __construct(
|
|
|
|
private UnencryptedToken $token,
|
|
|
|
) {
|
2019-12-09 22:01:54 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function getAccountId(): ?int {
|
2024-12-02 15:40:55 +05:30
|
|
|
$sub = $this->token->claims()->get('sub', false);
|
2019-12-09 22:01:54 +05:30
|
|
|
if ($sub === false) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (mb_strpos((string)$sub, TokensFactory::SUB_ACCOUNT_PREFIX) !== 0) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
return (int)mb_substr((string)$sub, mb_strlen(TokensFactory::SUB_ACCOUNT_PREFIX));
|
2019-12-09 22:01:54 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function getClientId(): ?string {
|
2024-12-02 15:40:55 +05:30
|
|
|
return $this->token->claims()->get('client_id', false) ?: null;
|
2019-12-09 22:01:54 +05:30
|
|
|
}
|
|
|
|
|
2024-12-06 06:04:09 +05:30
|
|
|
/**
|
|
|
|
* @return list<string>|null
|
|
|
|
*/
|
2019-12-09 22:01:54 +05:30
|
|
|
public function getScopes(): ?array {
|
2024-12-02 15:40:55 +05:30
|
|
|
$scopes = $this->token->claims()->get('scope', false);
|
2019-12-13 16:25:09 +05:30
|
|
|
if ($scopes !== false) {
|
2024-12-02 15:40:55 +05:30
|
|
|
return explode(' ', (string)$scopes);
|
2019-12-13 16:25:09 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// Handle legacy tokens, which used "ely-scopes" claim and was delimited with comma
|
2024-12-02 15:40:55 +05:30
|
|
|
$scopes = $this->token->claims()->get('ely-scopes', false);
|
2019-12-09 22:01:54 +05:30
|
|
|
if ($scopes === false) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
return explode(',', (string)$scopes);
|
2019-12-09 22:01:54 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function getMinecraftClientToken(): ?string {
|
2024-12-02 15:40:55 +05:30
|
|
|
$encodedClientToken = $this->token->claims()->get('ely-client-token', false);
|
2019-12-09 22:01:54 +05:30
|
|
|
if ($encodedClientToken === false) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2020-08-23 02:53:36 +05:30
|
|
|
/**
|
2024-12-02 15:40:55 +05:30
|
|
|
* It really might throw an exception, but we have not seen any case of such exception yet
|
2020-08-23 02:53:36 +05:30
|
|
|
* @noinspection PhpUnhandledExceptionInspection
|
|
|
|
*/
|
2019-12-09 22:01:54 +05:30
|
|
|
return Yii::$app->tokens->decryptValue($encodedClientToken);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|