2019-12-04 23:40:15 +05:30
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace api\modules\authserver\validators;
|
|
|
|
|
2020-06-13 04:25:02 +05:30
|
|
|
use api\components\Tokens\TokenReader;
|
2019-12-04 23:40:15 +05:30
|
|
|
use api\modules\authserver\exceptions\ForbiddenOperationException;
|
|
|
|
use Carbon\Carbon;
|
2020-06-13 04:25:02 +05:30
|
|
|
use common\models\Account;
|
2019-12-04 23:40:15 +05:30
|
|
|
use Exception;
|
|
|
|
use Yii;
|
|
|
|
use yii\validators\Validator;
|
|
|
|
|
|
|
|
class AccessTokenValidator extends Validator {
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
private const string INVALID_TOKEN = 'Invalid token.';
|
|
|
|
private const string TOKEN_EXPIRED = 'Token expired.';
|
2020-06-13 04:25:02 +05:30
|
|
|
|
2020-06-12 02:57:02 +05:30
|
|
|
public bool $verifyExpiration = true;
|
2019-12-04 23:40:15 +05:30
|
|
|
|
2020-06-13 04:25:02 +05:30
|
|
|
public bool $verifyAccount = true;
|
|
|
|
|
2019-12-04 23:40:15 +05:30
|
|
|
/**
|
|
|
|
* @return array|null
|
|
|
|
* @throws ForbiddenOperationException
|
|
|
|
*/
|
|
|
|
protected function validateValue($value): ?array {
|
|
|
|
try {
|
|
|
|
$token = Yii::$app->tokens->parse($value);
|
2024-12-02 15:40:55 +05:30
|
|
|
} catch (Exception) {
|
2020-06-13 04:25:02 +05:30
|
|
|
throw new ForbiddenOperationException(self::INVALID_TOKEN);
|
2019-12-04 23:40:15 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
if (!Yii::$app->tokens->verify($token)) {
|
2020-06-13 04:25:02 +05:30
|
|
|
throw new ForbiddenOperationException(self::INVALID_TOKEN);
|
2019-12-04 23:40:15 +05:30
|
|
|
}
|
|
|
|
|
2020-06-13 04:25:02 +05:30
|
|
|
if ($this->verifyExpiration && $token->isExpired(Carbon::now())) {
|
|
|
|
throw new ForbiddenOperationException(self::TOKEN_EXPIRED);
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($this->verifyAccount && !$this->validateAccount((new TokenReader($token))->getAccountId())) {
|
|
|
|
throw new ForbiddenOperationException(self::INVALID_TOKEN);
|
2019-12-04 23:40:15 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2020-06-13 04:25:02 +05:30
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2019-12-04 23:40:15 +05:30
|
|
|
}
|