mirror of
https://github.com/elyby/accounts.git
synced 2026-11-14 03:33:23 +05:30
51 lines
1.6 KiB
PHP
51 lines
1.6 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace api\modules\authserver\validators;
|
|
|
|
use api\components\Tokens\InvalidTokenException;
|
|
use api\components\Tokens\TokenExpiredException;
|
|
use api\components\Tokens\TokenReader;
|
|
use api\modules\authserver\exceptions\ForbiddenOperationException;
|
|
use common\models\Account;
|
|
use Yii;
|
|
use yii\validators\Validator;
|
|
|
|
class AccessTokenValidator extends Validator {
|
|
|
|
private const string INVALID_TOKEN = 'Invalid token.';
|
|
private const string TOKEN_EXPIRED = 'Token expired.';
|
|
|
|
public bool $verifyExpiration = true;
|
|
|
|
public bool $verifyAccount = true;
|
|
|
|
/**
|
|
* @return array|null
|
|
* @throws ForbiddenOperationException
|
|
*/
|
|
protected function validateValue($value): ?array {
|
|
try {
|
|
$token = Yii::$app->tokens->verifyAccessToken($value, verifyExpiration: $this->verifyExpiration);
|
|
} catch (TokenExpiredException $e) {
|
|
throw new ForbiddenOperationException(self::TOKEN_EXPIRED, previous: $e);
|
|
} catch (InvalidTokenException $e) {
|
|
throw new ForbiddenOperationException(self::INVALID_TOKEN, previous: $e);
|
|
}
|
|
|
|
if ($this->verifyAccount && !$this->validateAccount((new TokenReader($token))->getAccountId())) {
|
|
throw new ForbiddenOperationException(self::INVALID_TOKEN);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private function validateAccount(int $accountId): bool {
|
|
/** @var Account|null $account */
|
|
$account = Account::find()->excludeDeleted()->andWhere(['id' => $accountId])->one();
|
|
|
|
return $account !== null && $account->status !== Account::STATUS_BANNED;
|
|
}
|
|
|
|
}
|