mirror of
https://github.com/elyby/accounts.git
synced 2025-05-31 14:11:46 +05:30
Объединены сущности для авторизации посредством JWT токенов и токенов, выданных через oAuth2.
Все действия, связанные с аккаунтами, теперь вызываются через url `/api/v1/accounts/<id>/<action>`. Добавлена вменяемая система разграничения прав на основе RBAC. Теперь oAuth2 токены генерируются как случайная строка в 40 символов длинной, а не UUID. Исправлен баг с неправильным временем жизни токена в ответе успешного запроса аутентификации. Теперь все unit тесты можно успешно прогнать без наличия интернета.
This commit is contained in:
@@ -1,18 +0,0 @@
|
||||
<?php
|
||||
namespace common\components\Annotations;
|
||||
|
||||
class Reader extends \Minime\Annotations\Reader {
|
||||
|
||||
/**
|
||||
* Поначаду я думал кэшировать эту штуку, но потом забил, т.к. всё всё равно завернул
|
||||
* в Yii::$app->cache и как-то надобность в отдельном кэше отпала, так что пока забьём
|
||||
* и оставим как заготовку на будущее
|
||||
*
|
||||
* @return \Minime\Annotations\Interfaces\ReaderInterface
|
||||
*/
|
||||
public static function createFromDefaults() {
|
||||
return parent::createFromDefaults();
|
||||
//return new self(new \Minime\Annotations\Parser(), new RedisCache());
|
||||
}
|
||||
|
||||
}
|
@@ -1,65 +0,0 @@
|
||||
<?php
|
||||
namespace common\components\Annotations;
|
||||
|
||||
use common\components\Redis\Key;
|
||||
use common\components\Redis\Set;
|
||||
use Minime\Annotations\Interfaces\CacheInterface;
|
||||
use yii\helpers\Json;
|
||||
|
||||
class RedisCache implements CacheInterface {
|
||||
|
||||
/**
|
||||
* Generates uuid for a given docblock string
|
||||
* @param string $docblock docblock string
|
||||
* @return string uuid that maps to the given docblock
|
||||
*/
|
||||
public function getKey($docblock) {
|
||||
return md5($docblock);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an annotation AST to cache
|
||||
*
|
||||
* @param string $key cache entry uuid
|
||||
* @param array $annotations annotation AST
|
||||
*/
|
||||
public function set($key, array $annotations) {
|
||||
$this->getRedisKey($key)->setValue(Json::encode($annotations))->expire(3600);
|
||||
$this->getRedisKeysSet()->add($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves cached annotations from docblock uuid
|
||||
*
|
||||
* @param string $key cache entry uuid
|
||||
* @return array cached annotation AST
|
||||
*/
|
||||
public function get($key) {
|
||||
$result = $this->getRedisKey($key)->getValue();
|
||||
if ($result === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Json::decode($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets cache
|
||||
*/
|
||||
public function clear() {
|
||||
/** @var array $keys */
|
||||
$keys = $this->getRedisKeysSet()->getValue();
|
||||
foreach ($keys as $key) {
|
||||
$this->getRedisKey($key)->delete();
|
||||
}
|
||||
}
|
||||
|
||||
private function getRedisKey(string $key): Key {
|
||||
return new Key('annotations', 'cache', $key);
|
||||
}
|
||||
|
||||
private function getRedisKeysSet(): Set {
|
||||
return new Set('annotations', 'cache', 'keys');
|
||||
}
|
||||
|
||||
}
|
@@ -6,46 +6,7 @@ use Yii;
|
||||
|
||||
class Key {
|
||||
|
||||
protected $key;
|
||||
|
||||
/**
|
||||
* @return Connection
|
||||
*/
|
||||
public function getRedis() {
|
||||
return Yii::$app->redis;
|
||||
}
|
||||
|
||||
public function getKey() : string {
|
||||
return $this->key;
|
||||
}
|
||||
|
||||
public function getValue() {
|
||||
return $this->getRedis()->get($this->key);
|
||||
}
|
||||
|
||||
public function setValue($value) {
|
||||
$this->getRedis()->set($this->key, $value);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function delete() {
|
||||
$this->getRedis()->del($this->key);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function exists() : bool {
|
||||
return (bool)$this->getRedis()->exists($this->key);
|
||||
}
|
||||
|
||||
public function expire(int $ttl) {
|
||||
$this->getRedis()->expire($this->key, $ttl);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function expireAt(int $unixTimestamp) {
|
||||
$this->getRedis()->expireat($this->key, $unixTimestamp);
|
||||
return $this;
|
||||
}
|
||||
private $key;
|
||||
|
||||
public function __construct(...$key) {
|
||||
if (empty($key)) {
|
||||
@@ -55,7 +16,43 @@ class Key {
|
||||
$this->key = $this->buildKey($key);
|
||||
}
|
||||
|
||||
private function buildKey(array $parts) {
|
||||
public function getRedis(): Connection {
|
||||
return Yii::$app->redis;
|
||||
}
|
||||
|
||||
public function getKey(): string {
|
||||
return $this->key;
|
||||
}
|
||||
|
||||
public function getValue() {
|
||||
return $this->getRedis()->get($this->key);
|
||||
}
|
||||
|
||||
public function setValue($value): self {
|
||||
$this->getRedis()->set($this->key, $value);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function delete(): self {
|
||||
$this->getRedis()->del([$this->getKey()]);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function exists(): bool {
|
||||
return (bool)$this->getRedis()->exists($this->key);
|
||||
}
|
||||
|
||||
public function expire(int $ttl): self {
|
||||
$this->getRedis()->expire($this->key, $ttl);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function expireAt(int $unixTimestamp): self {
|
||||
$this->getRedis()->expireat($this->key, $unixTimestamp);
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function buildKey(array $parts): string {
|
||||
$keyParts = [];
|
||||
foreach($parts as $part) {
|
||||
$keyParts[] = str_replace('_', ':', $part);
|
||||
|
@@ -6,34 +6,34 @@ use IteratorAggregate;
|
||||
|
||||
class Set extends Key implements IteratorAggregate {
|
||||
|
||||
public function add($value) {
|
||||
$this->getRedis()->sadd($this->key, $value);
|
||||
public function add($value): self {
|
||||
$this->getRedis()->sadd($this->getKey(), $value);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function remove($value) {
|
||||
$this->getRedis()->srem($this->key, $value);
|
||||
public function remove($value): self {
|
||||
$this->getRedis()->srem($this->getKey(), $value);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function members() {
|
||||
return $this->getRedis()->smembers($this->key);
|
||||
public function members(): array {
|
||||
return $this->getRedis()->smembers($this->getKey());
|
||||
}
|
||||
|
||||
public function getValue() {
|
||||
public function getValue(): array {
|
||||
return $this->members();
|
||||
}
|
||||
|
||||
public function exists(string $value = null) : bool {
|
||||
public function exists(string $value = null): bool {
|
||||
if ($value === null) {
|
||||
return parent::exists();
|
||||
} else {
|
||||
return (bool)$this->getRedis()->sismember($this->key, $value);
|
||||
}
|
||||
|
||||
return (bool)$this->getRedis()->sismember($this->getKey(), $value);
|
||||
}
|
||||
|
||||
public function diff(array $sets) {
|
||||
return $this->getRedis()->sdiff([$this->key, implode(' ', $sets)]);
|
||||
public function diff(array $sets): array {
|
||||
return $this->getRedis()->sdiff([$this->getKey(), implode(' ', $sets)]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
return [
|
||||
'version' => '1.1.18-dev',
|
||||
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
|
||||
'vendorPath' => dirname(__DIR__, 2) . '/vendor',
|
||||
'components' => [
|
||||
'cache' => [
|
||||
'class' => common\components\Redis\Cache::class,
|
||||
@@ -72,6 +72,11 @@ return [
|
||||
'oauth' => [
|
||||
'class' => api\components\OAuth2\Component::class,
|
||||
],
|
||||
'authManager' => [
|
||||
'class' => common\rbac\Manager::class,
|
||||
'itemFile' => '@common/rbac/.generated/items.php',
|
||||
'ruleFile' => '@common/rbac/.generated/rules.php',
|
||||
],
|
||||
],
|
||||
'container' => [
|
||||
'definitions' => [
|
||||
|
@@ -51,27 +51,18 @@ class Account extends ActiveRecord {
|
||||
const PASS_HASH_STRATEGY_OLD_ELY = 0;
|
||||
const PASS_HASH_STRATEGY_YII2 = 1;
|
||||
|
||||
public static function tableName() {
|
||||
public static function tableName(): string {
|
||||
return '{{%accounts}}';
|
||||
}
|
||||
|
||||
public function behaviors() {
|
||||
public function behaviors(): array {
|
||||
return [
|
||||
TimestampBehavior::class,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates password
|
||||
*
|
||||
* @param string $password password to validate
|
||||
* @param integer $passwordHashStrategy
|
||||
*
|
||||
* @return bool if password provided is valid for current user
|
||||
* @throws InvalidConfigException
|
||||
*/
|
||||
public function validatePassword($password, $passwordHashStrategy = NULL) : bool {
|
||||
if ($passwordHashStrategy === NULL) {
|
||||
public function validatePassword(string $password, int $passwordHashStrategy = null): bool {
|
||||
if ($passwordHashStrategy === null) {
|
||||
$passwordHashStrategy = $this->password_hash_strategy;
|
||||
}
|
||||
|
||||
@@ -88,17 +79,13 @@ class Account extends ActiveRecord {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $password
|
||||
* @throws InvalidConfigException
|
||||
*/
|
||||
public function setPassword($password) {
|
||||
public function setPassword(string $password): void {
|
||||
$this->password_hash_strategy = self::PASS_HASH_STRATEGY_YII2;
|
||||
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
|
||||
$this->password_changed_at = time();
|
||||
}
|
||||
|
||||
public function getEmailActivations() {
|
||||
public function getEmailActivations(): ActiveQuery {
|
||||
return $this->hasMany(EmailActivation::class, ['account_id' => 'id']);
|
||||
}
|
||||
|
||||
@@ -106,15 +93,15 @@ class Account extends ActiveRecord {
|
||||
return $this->hasMany(OauthSession::class, ['owner_id' => 'id'])->andWhere(['owner_type' => 'user']);
|
||||
}
|
||||
|
||||
public function getUsernameHistory() {
|
||||
public function getUsernameHistory(): ActiveQuery {
|
||||
return $this->hasMany(UsernameHistory::class, ['account_id' => 'id']);
|
||||
}
|
||||
|
||||
public function getSessions() {
|
||||
public function getSessions(): ActiveQuery {
|
||||
return $this->hasMany(AccountSession::class, ['account_id' => 'id']);
|
||||
}
|
||||
|
||||
public function getMinecraftAccessKeys() {
|
||||
public function getMinecraftAccessKeys(): ActiveQuery {
|
||||
return $this->hasMany(MinecraftAccessKey::class, ['account_id' => 'id']);
|
||||
}
|
||||
|
||||
@@ -123,7 +110,7 @@ class Account extends ActiveRecord {
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasMojangUsernameCollision() : bool {
|
||||
public function hasMojangUsernameCollision(): bool {
|
||||
return MojangUsername::find()
|
||||
->andWhere(['username' => $this->username])
|
||||
->exists();
|
||||
@@ -136,7 +123,7 @@ class Account extends ActiveRecord {
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getProfileLink() : string {
|
||||
public function getProfileLink(): string {
|
||||
return 'http://ely.by/u' . $this->id;
|
||||
}
|
||||
|
||||
@@ -148,15 +135,15 @@ class Account extends ActiveRecord {
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isAgreedWithActualRules() : bool {
|
||||
public function isAgreedWithActualRules(): bool {
|
||||
return $this->rules_agreement_version === LATEST_RULES_VERSION;
|
||||
}
|
||||
|
||||
public function setRegistrationIp($ip) {
|
||||
public function setRegistrationIp($ip): void {
|
||||
$this->registration_ip = $ip === null ? null : inet_pton($ip);
|
||||
}
|
||||
|
||||
public function getRegistrationIp() {
|
||||
public function getRegistrationIp(): ?string {
|
||||
return $this->registration_ip === null ? null : inet_ntop($this->registration_ip);
|
||||
}
|
||||
|
||||
|
23
common/models/OauthOwnerType.php
Normal file
23
common/models/OauthOwnerType.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
namespace common\models;
|
||||
|
||||
final class OauthOwnerType {
|
||||
|
||||
/**
|
||||
* Используется для сессий, принадлежащих непосредственно пользователям account.ely.by,
|
||||
* выполнивших парольную авторизацию и использующих web интерфейс
|
||||
*/
|
||||
public const ACCOUNT = 'accounts';
|
||||
|
||||
/**
|
||||
* Используется когда пользователь по протоколу oAuth2 authorization_code
|
||||
* разрешает приложению получить доступ и выполнять действия от своего имени
|
||||
*/
|
||||
public const USER = 'user';
|
||||
|
||||
/**
|
||||
* Используется для авторизованных по протоколу oAuth2 client_credentials
|
||||
*/
|
||||
public const CLIENT = 'client';
|
||||
|
||||
}
|
@@ -1,67 +0,0 @@
|
||||
<?php
|
||||
namespace common\models;
|
||||
|
||||
use common\components\Annotations\Reader;
|
||||
use ReflectionClass;
|
||||
use Yii;
|
||||
|
||||
class OauthScope {
|
||||
|
||||
/**
|
||||
* @owner user
|
||||
*/
|
||||
const OFFLINE_ACCESS = 'offline_access';
|
||||
/**
|
||||
* @owner user
|
||||
*/
|
||||
const MINECRAFT_SERVER_SESSION = 'minecraft_server_session';
|
||||
/**
|
||||
* @owner user
|
||||
*/
|
||||
const ACCOUNT_INFO = 'account_info';
|
||||
/**
|
||||
* @owner user
|
||||
*/
|
||||
const ACCOUNT_EMAIL = 'account_email';
|
||||
/**
|
||||
* @internal
|
||||
* @owner machine
|
||||
*/
|
||||
const ACCOUNT_BLOCK = 'account_block';
|
||||
/**
|
||||
* @internal
|
||||
* @owner machine
|
||||
*/
|
||||
const INTERNAL_ACCOUNT_INFO = 'internal_account_info';
|
||||
|
||||
public static function find(): OauthScopeQuery {
|
||||
return new OauthScopeQuery(static::queryScopes());
|
||||
}
|
||||
|
||||
private static function queryScopes(): array {
|
||||
$cacheKey = 'oauth-scopes-list';
|
||||
$scopes = false;
|
||||
if ($scopes === false) {
|
||||
$scopes = [];
|
||||
$reflection = new ReflectionClass(static::class);
|
||||
$constants = $reflection->getConstants();
|
||||
$reader = Reader::createFromDefaults();
|
||||
foreach ($constants as $constName => $value) {
|
||||
$annotations = $reader->getConstantAnnotations(static::class, $constName);
|
||||
$isInternal = $annotations->get('internal', false);
|
||||
$owner = $annotations->get('owner', 'user');
|
||||
$keyValue = [
|
||||
'value' => $value,
|
||||
'internal' => $isInternal,
|
||||
'owner' => $owner,
|
||||
];
|
||||
$scopes[$constName] = $keyValue;
|
||||
}
|
||||
|
||||
Yii::$app->cache->set($cacheKey, $scopes, 3600);
|
||||
}
|
||||
|
||||
return $scopes;
|
||||
}
|
||||
|
||||
}
|
@@ -3,14 +3,15 @@ namespace common\models;
|
||||
|
||||
use common\components\Redis\Set;
|
||||
use Yii;
|
||||
use yii\base\ErrorException;
|
||||
use yii\base\NotSupportedException;
|
||||
use yii\db\ActiveQuery;
|
||||
use yii\db\ActiveRecord;
|
||||
|
||||
/**
|
||||
* Поля:
|
||||
* @property integer $id
|
||||
* @property string $owner_type
|
||||
* @property string $owner_id
|
||||
* @property string $owner_type содержит одну из констант OauthOwnerType
|
||||
* @property string|null $owner_id
|
||||
* @property string $client_id
|
||||
* @property string $client_redirect_uri
|
||||
*
|
||||
@@ -21,42 +22,50 @@ use yii\db\ActiveRecord;
|
||||
*/
|
||||
class OauthSession extends ActiveRecord {
|
||||
|
||||
public static function tableName() {
|
||||
public static function tableName(): string {
|
||||
return '{{%oauth_sessions}}';
|
||||
}
|
||||
|
||||
public function getAccessTokens() {
|
||||
throw new ErrorException('This method is possible, but not implemented');
|
||||
}
|
||||
|
||||
public function getClient() {
|
||||
public function getClient(): ActiveQuery {
|
||||
return $this->hasOne(OauthClient::class, ['id' => 'client_id']);
|
||||
}
|
||||
|
||||
public function getAccount() {
|
||||
public function getAccount(): ActiveQuery {
|
||||
return $this->hasOne(Account::class, ['id' => 'owner_id']);
|
||||
}
|
||||
|
||||
public function getScopes() {
|
||||
public function getScopes(): Set {
|
||||
return new Set(static::getDb()->getSchema()->getRawTableName(static::tableName()), $this->id, 'scopes');
|
||||
}
|
||||
|
||||
public function beforeDelete() {
|
||||
public function getAccessTokens() {
|
||||
throw new NotSupportedException('This method is possible, but not implemented');
|
||||
}
|
||||
|
||||
public function beforeDelete(): bool {
|
||||
if (!$result = parent::beforeDelete()) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$this->getScopes()->delete();
|
||||
$this->clearScopes();
|
||||
$this->removeRefreshToken();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function removeRefreshToken(): void {
|
||||
/** @var \api\components\OAuth2\Storage\RefreshTokenStorage $refreshTokensStorage */
|
||||
$refreshTokensStorage = Yii::$app->oauth->getAuthServer()->getRefreshTokenStorage();
|
||||
$refreshTokensStorage = Yii::$app->oauth->getRefreshTokenStorage();
|
||||
$refreshTokensSet = $refreshTokensStorage->sessionHash($this->id);
|
||||
foreach ($refreshTokensSet->members() as $refreshTokenId) {
|
||||
$refreshTokensStorage->delete($refreshTokensStorage->get($refreshTokenId));
|
||||
}
|
||||
|
||||
$refreshTokensSet->delete();
|
||||
}
|
||||
|
||||
return true;
|
||||
public function clearScopes(): void {
|
||||
$this->getScopes()->delete();
|
||||
}
|
||||
|
||||
}
|
||||
|
2
common/rbac/.generated/.gitignore
vendored
Normal file
2
common/rbac/.generated/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
31
common/rbac/Manager.php
Normal file
31
common/rbac/Manager.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
namespace common\rbac;
|
||||
|
||||
use Yii;
|
||||
use yii\rbac\PhpManager;
|
||||
|
||||
class Manager extends PhpManager {
|
||||
|
||||
/**
|
||||
* В нашем приложении права выдаются не пользователям, а токенам, так что ожидаем
|
||||
* здесь $accessToken и извлекаем из него все присвоенные права.
|
||||
*
|
||||
* По каким-то причинам, в Yii механизм рекурсивной проверки прав требует, чтобы
|
||||
* массив с правами был проиндексирован по ключам этих самых прав, так что в
|
||||
* конце выворачиваем массив наизнанку.
|
||||
*
|
||||
* @param string $accessToken
|
||||
* @return string[]
|
||||
*/
|
||||
public function getAssignments($accessToken): array {
|
||||
$identity = Yii::$app->user->findIdentityByAccessToken($accessToken);
|
||||
/** @noinspection NullPointerExceptionInspection */
|
||||
$permissions = $identity->getAssignedPermissions();
|
||||
if (empty($permissions)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_flip($permissions);
|
||||
}
|
||||
|
||||
}
|
31
common/rbac/Permissions.php
Normal file
31
common/rbac/Permissions.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
namespace common\rbac;
|
||||
|
||||
final class Permissions {
|
||||
|
||||
// Top level Controller permissions
|
||||
public const OBTAIN_ACCOUNT_INFO = 'obtain_account_info';
|
||||
public const CHANGE_ACCOUNT_LANGUAGE = 'change_account_language';
|
||||
public const CHANGE_ACCOUNT_USERNAME = 'change_account_username';
|
||||
public const CHANGE_ACCOUNT_PASSWORD = 'change_account_password';
|
||||
public const CHANGE_ACCOUNT_EMAIL = 'change_account_email';
|
||||
public const MANAGE_TWO_FACTOR_AUTH = 'manage_two_factor_auth';
|
||||
public const BLOCK_ACCOUNT = 'block_account';
|
||||
public const COMPLETE_OAUTH_FLOW = 'complete_oauth_flow';
|
||||
|
||||
// Personal level controller permissions
|
||||
public const OBTAIN_OWN_ACCOUNT_INFO = 'obtain_own_account_info';
|
||||
public const OBTAIN_OWN_EXTENDED_ACCOUNT_INFO = 'obtain_own_extended_account_info';
|
||||
public const CHANGE_OWN_ACCOUNT_LANGUAGE = 'change_own_account_language';
|
||||
public const ACCEPT_NEW_PROJECT_RULES = 'accept_new_project_rules';
|
||||
public const CHANGE_OWN_ACCOUNT_USERNAME = 'change_own_account_username';
|
||||
public const CHANGE_OWN_ACCOUNT_PASSWORD = 'change_own_account_password';
|
||||
public const CHANGE_OWN_ACCOUNT_EMAIL = 'change_own_account_email';
|
||||
public const MANAGE_OWN_TWO_FACTOR_AUTH = 'manage_own_two_factor_auth';
|
||||
public const MINECRAFT_SERVER_SESSION = 'minecraft_server_session';
|
||||
|
||||
// Data permissions
|
||||
public const OBTAIN_ACCOUNT_EMAIL = 'obtain_account_email';
|
||||
public const OBTAIN_EXTENDED_ACCOUNT_INFO = 'obtain_account_extended_info';
|
||||
|
||||
}
|
8
common/rbac/Roles.php
Normal file
8
common/rbac/Roles.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
namespace common\rbac;
|
||||
|
||||
final class Roles {
|
||||
|
||||
public const ACCOUNTS_WEB_USER = 'accounts_web_user';
|
||||
|
||||
}
|
55
common/rbac/rules/AccountOwner.php
Normal file
55
common/rbac/rules/AccountOwner.php
Normal file
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
namespace common\rbac\rules;
|
||||
|
||||
use common\models\Account;
|
||||
use Yii;
|
||||
use yii\base\InvalidParamException;
|
||||
use yii\rbac\Rule;
|
||||
|
||||
class AccountOwner extends Rule {
|
||||
|
||||
public $name = 'account_owner';
|
||||
|
||||
/**
|
||||
* В нашем приложении права выдаются не пользователям, а токенам, так что ожидаем
|
||||
* здесь $accessToken, по которому дальше восстанавливаем аккаунт, если это возможно.
|
||||
*
|
||||
* @param string|int $accessToken
|
||||
* @param \yii\rbac\Item $item
|
||||
* @param array $params параметр accountId нужно передать обязательно как id аккаунта,
|
||||
* к которому выполняется запрос
|
||||
* параметр optionalRules позволяет отключить обязательность
|
||||
* принятия последней версии правил
|
||||
*
|
||||
* @return bool a value indicating whether the rule permits the auth item it is associated with.
|
||||
*/
|
||||
public function execute($accessToken, $item, $params): bool {
|
||||
$accountId = $params['accountId'] ?? null;
|
||||
if ($accountId === null) {
|
||||
throw new InvalidParamException('params don\'t contain required key: accountId');
|
||||
}
|
||||
|
||||
$identity = Yii::$app->user->findIdentityByAccessToken($accessToken);
|
||||
/** @noinspection NullPointerExceptionInspection это исключено, т.к. уже сработал authManager */
|
||||
$account = $identity->getAccount();
|
||||
if ($account === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($account->id !== (int)$accountId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($account->status !== Account::STATUS_ACTIVE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$actualRulesOptional = $params['optionalRules'] ?? false;
|
||||
if (!$actualRulesOptional && !$account->isAgreedWithActualRules()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user