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,8 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\components\ApiUser; |  | ||||||
|  |  | ||||||
| class AccessControl extends \yii\filters\AccessControl { |  | ||||||
|  |  | ||||||
|     public $user = 'apiUser'; |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -1,21 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\components\ApiUser; |  | ||||||
|  |  | ||||||
| use Yii; |  | ||||||
| use yii\rbac\CheckAccessInterface; |  | ||||||
|  |  | ||||||
| class AuthChecker implements CheckAccessInterface { |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     public function checkAccess($token, $permissionName, $params = []) : bool { |  | ||||||
|         $accessToken = Yii::$app->oauth->getAuthServer()->getAccessTokenStorage()->get($token); |  | ||||||
|         if ($accessToken === null) { |  | ||||||
|             return false; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return $accessToken->hasScope($permissionName); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -1,24 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\components\ApiUser; |  | ||||||
|  |  | ||||||
| use yii\web\User as YiiUserComponent; |  | ||||||
|  |  | ||||||
| /** |  | ||||||
|  * @property Identity|null $identity |  | ||||||
|  * |  | ||||||
|  * @method Identity|null getIdentity($autoRenew = true) |  | ||||||
|  * @method Identity|null loginByAccessToken($token, $type = null) |  | ||||||
|  */ |  | ||||||
| class Component extends YiiUserComponent { |  | ||||||
|  |  | ||||||
|     public $identityClass = Identity::class; |  | ||||||
|  |  | ||||||
|     public $enableSession = false; |  | ||||||
|  |  | ||||||
|     public $loginUrl = null; |  | ||||||
|  |  | ||||||
|     public function getAccessChecker() { |  | ||||||
|         return new AuthChecker(); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -2,9 +2,10 @@ | |||||||
| namespace api\components\OAuth2; | namespace api\components\OAuth2; | ||||||
|  |  | ||||||
| use api\components\OAuth2\Storage; | use api\components\OAuth2\Storage; | ||||||
| use api\components\OAuth2\Utils\KeyAlgorithm\UuidAlgorithm; |  | ||||||
| use League\OAuth2\Server\AuthorizationServer; | use League\OAuth2\Server\AuthorizationServer; | ||||||
| use League\OAuth2\Server\Util\SecureKey; | use League\OAuth2\Server\Storage\AccessTokenInterface; | ||||||
|  | use League\OAuth2\Server\Storage\RefreshTokenInterface; | ||||||
|  | use League\OAuth2\Server\Storage\SessionInterface; | ||||||
| use yii\base\Component as BaseComponent; | use yii\base\Component as BaseComponent; | ||||||
|  |  | ||||||
| /** | /** | ||||||
| @@ -34,11 +35,21 @@ class Component extends BaseComponent { | |||||||
|             $authServer->addGrantType(new Grants\ClientCredentialsGrant()); |             $authServer->addGrantType(new Grants\ClientCredentialsGrant()); | ||||||
|  |  | ||||||
|             $this->_authServer = $authServer; |             $this->_authServer = $authServer; | ||||||
|  |  | ||||||
|             SecureKey::setAlgorithm(new UuidAlgorithm()); |  | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         return $this->_authServer; |         return $this->_authServer; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|  |     public function getAccessTokenStorage(): AccessTokenInterface { | ||||||
|  |         return $this->getAuthServer()->getAccessTokenStorage(); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getRefreshTokenStorage(): RefreshTokenInterface { | ||||||
|  |         return $this->getAuthServer()->getRefreshTokenStorage(); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getSessionStorage(): SessionInterface { | ||||||
|  |         return $this->getAuthServer()->getSessionStorage(); | ||||||
|  |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -6,7 +6,7 @@ use api\components\OAuth2\Entities\AuthCodeEntity; | |||||||
| use api\components\OAuth2\Entities\ClientEntity; | use api\components\OAuth2\Entities\ClientEntity; | ||||||
| use api\components\OAuth2\Entities\RefreshTokenEntity; | use api\components\OAuth2\Entities\RefreshTokenEntity; | ||||||
| use api\components\OAuth2\Entities\SessionEntity; | use api\components\OAuth2\Entities\SessionEntity; | ||||||
| use common\models\OauthScope; | use api\components\OAuth2\Storage\ScopeStorage; | ||||||
| use League\OAuth2\Server\Entity\AuthCodeEntity as BaseAuthCodeEntity; | use League\OAuth2\Server\Entity\AuthCodeEntity as BaseAuthCodeEntity; | ||||||
| use League\OAuth2\Server\Entity\ClientEntity as BaseClientEntity; | use League\OAuth2\Server\Entity\ClientEntity as BaseClientEntity; | ||||||
| use League\OAuth2\Server\Event\ClientAuthenticationFailedEvent; | use League\OAuth2\Server\Event\ClientAuthenticationFailedEvent; | ||||||
| @@ -178,7 +178,7 @@ class AuthCodeGrant extends AbstractGrant { | |||||||
|  |  | ||||||
|         // Generate the access token |         // Generate the access token | ||||||
|         $accessToken = new AccessTokenEntity($this->server); |         $accessToken = new AccessTokenEntity($this->server); | ||||||
|         $accessToken->setId(SecureKey::generate()); // TODO: generate code based on permissions |         $accessToken->setId(SecureKey::generate()); | ||||||
|         $accessToken->setExpireTime($this->getAccessTokenTTL() + time()); |         $accessToken->setExpireTime($this->getAccessTokenTTL() + time()); | ||||||
|  |  | ||||||
|         foreach ($authCodeScopes as $authCodeScope) { |         foreach ($authCodeScopes as $authCodeScope) { | ||||||
| @@ -194,7 +194,7 @@ class AuthCodeGrant extends AbstractGrant { | |||||||
|         $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL()); |         $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL()); | ||||||
|  |  | ||||||
|         // Выдаём refresh_token, если запрошен offline_access |         // Выдаём refresh_token, если запрошен offline_access | ||||||
|         if (isset($accessToken->getScopes()[OauthScope::OFFLINE_ACCESS])) { |         if (isset($accessToken->getScopes()[ScopeStorage::OFFLINE_ACCESS])) { | ||||||
|             /** @var RefreshTokenGrant $refreshTokenGrant */ |             /** @var RefreshTokenGrant $refreshTokenGrant */ | ||||||
|             $refreshTokenGrant = $this->server->getGrantType('refresh_token'); |             $refreshTokenGrant = $this->server->getGrantType('refresh_token'); | ||||||
|             $refreshToken = new RefreshTokenEntity($this->server); |             $refreshToken = new RefreshTokenEntity($this->server); | ||||||
| @@ -223,12 +223,12 @@ class AuthCodeGrant extends AbstractGrant { | |||||||
|      * Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые. |      * Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые. | ||||||
|      * |      * | ||||||
|      * @param string       $scopeParam |      * @param string       $scopeParam | ||||||
|      * @param ClientEntity $client |      * @param BaseClientEntity $client | ||||||
|      * @param string $redirectUri |      * @param string $redirectUri | ||||||
|      * |      * | ||||||
|      * @return \League\OAuth2\Server\Entity\ScopeEntity[] |      * @return \League\OAuth2\Server\Entity\ScopeEntity[] | ||||||
|      */ |      */ | ||||||
|     public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null) { |     public function validateScopes($scopeParam = '', BaseClientEntity $client, $redirectUri = null) { | ||||||
|         $scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam); |         $scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam); | ||||||
|         return parent::validateScopes($scopes, $client, $redirectUri); |         return parent::validateScopes($scopes, $client, $redirectUri); | ||||||
|     } |     } | ||||||
|   | |||||||
| @@ -18,14 +18,12 @@ class ClientCredentialsGrant extends AbstractGrant { | |||||||
|      * @throws \League\OAuth2\Server\Exception\OAuthException |      * @throws \League\OAuth2\Server\Exception\OAuthException | ||||||
|      */ |      */ | ||||||
|     public function completeFlow(): array { |     public function completeFlow(): array { | ||||||
|         // Get the required params |  | ||||||
|         $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); |         $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); | ||||||
|         if ($clientId === null) { |         if ($clientId === null) { | ||||||
|             throw new Exception\InvalidRequestException('client_id'); |             throw new Exception\InvalidRequestException('client_id'); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         $clientSecret = $this->server->getRequest()->request->get('client_secret', |         $clientSecret = $this->server->getRequest()->request->get('client_secret'); | ||||||
|             $this->server->getRequest()->getPassword()); |  | ||||||
|         if ($clientSecret === null) { |         if ($clientSecret === null) { | ||||||
|             throw new Exception\InvalidRequestException('client_secret'); |             throw new Exception\InvalidRequestException('client_secret'); | ||||||
|         } |         } | ||||||
| @@ -74,12 +72,12 @@ class ClientCredentialsGrant extends AbstractGrant { | |||||||
|      * Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые. |      * Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые. | ||||||
|      * |      * | ||||||
|      * @param string       $scopeParam |      * @param string       $scopeParam | ||||||
|      * @param ClientEntity $client |      * @param BaseClientEntity $client | ||||||
|      * @param string $redirectUri |      * @param string $redirectUri | ||||||
|      * |      * | ||||||
|      * @return \League\OAuth2\Server\Entity\ScopeEntity[] |      * @return \League\OAuth2\Server\Entity\ScopeEntity[] | ||||||
|      */ |      */ | ||||||
|     public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null) { |     public function validateScopes($scopeParam = '', BaseClientEntity $client, $redirectUri = null) { | ||||||
|         $scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam); |         $scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam); | ||||||
|         return parent::validateScopes($scopes, $client, $redirectUri); |         return parent::validateScopes($scopes, $client, $redirectUri); | ||||||
|     } |     } | ||||||
|   | |||||||
| @@ -51,12 +51,12 @@ class RefreshTokenGrant extends AbstractGrant { | |||||||
|      * Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые. |      * Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые. | ||||||
|      * |      * | ||||||
|      * @param string       $scopeParam |      * @param string       $scopeParam | ||||||
|      * @param ClientEntity $client |      * @param BaseClientEntity $client | ||||||
|      * @param string $redirectUri |      * @param string $redirectUri | ||||||
|      * |      * | ||||||
|      * @return \League\OAuth2\Server\Entity\ScopeEntity[] |      * @return \League\OAuth2\Server\Entity\ScopeEntity[] | ||||||
|      */ |      */ | ||||||
|     public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null) { |     public function validateScopes($scopeParam = '', BaseClientEntity $client, $redirectUri = null) { | ||||||
|         $scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam); |         $scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam); | ||||||
|         return parent::validateScopes($scopes, $client, $redirectUri); |         return parent::validateScopes($scopes, $client, $redirectUri); | ||||||
|     } |     } | ||||||
| @@ -143,7 +143,7 @@ class RefreshTokenGrant extends AbstractGrant { | |||||||
|  |  | ||||||
|         // Generate a new access token and assign it the correct sessions |         // Generate a new access token and assign it the correct sessions | ||||||
|         $newAccessToken = new AccessTokenEntity($this->server); |         $newAccessToken = new AccessTokenEntity($this->server); | ||||||
|         $newAccessToken->setId(SecureKey::generate()); // TODO: generate based on permissions |         $newAccessToken->setId(SecureKey::generate()); | ||||||
|         $newAccessToken->setExpireTime($this->getAccessTokenTTL() + time()); |         $newAccessToken->setExpireTime($this->getAccessTokenTTL() + time()); | ||||||
|         $newAccessToken->setSession($session); |         $newAccessToken->setSession($session); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -3,46 +3,84 @@ namespace api\components\OAuth2\Storage; | |||||||
|  |  | ||||||
| use api\components\OAuth2\Entities\ClientEntity; | use api\components\OAuth2\Entities\ClientEntity; | ||||||
| use api\components\OAuth2\Entities\ScopeEntity; | use api\components\OAuth2\Entities\ScopeEntity; | ||||||
| use common\models\OauthScope; | use Assert\Assert; | ||||||
|  | use common\rbac\Permissions as P; | ||||||
| use League\OAuth2\Server\Storage\AbstractStorage; | use League\OAuth2\Server\Storage\AbstractStorage; | ||||||
| use League\OAuth2\Server\Storage\ScopeInterface; | use League\OAuth2\Server\Storage\ScopeInterface; | ||||||
| use yii\base\ErrorException; |  | ||||||
|  |  | ||||||
| class ScopeStorage extends AbstractStorage implements ScopeInterface { | class ScopeStorage extends AbstractStorage implements ScopeInterface { | ||||||
|  |  | ||||||
|  |     public const OFFLINE_ACCESS = 'offline_access'; | ||||||
|  |  | ||||||
|  |     private const PUBLIC_SCOPES_TO_INTERNAL_PERMISSIONS = [ | ||||||
|  |         'account_info' => P::OBTAIN_OWN_ACCOUNT_INFO, | ||||||
|  |         'account_email' => P::OBTAIN_ACCOUNT_EMAIL, | ||||||
|  |         'account_block' => P::BLOCK_ACCOUNT, | ||||||
|  |         'internal_account_info' => P::OBTAIN_EXTENDED_ACCOUNT_INFO, | ||||||
|  |     ]; | ||||||
|  |  | ||||||
|  |     private const AUTHORIZATION_CODE_PERMISSIONS = [ | ||||||
|  |         P::OBTAIN_OWN_ACCOUNT_INFO, | ||||||
|  |         P::OBTAIN_ACCOUNT_EMAIL, | ||||||
|  |         P::MINECRAFT_SERVER_SESSION, | ||||||
|  |         self::OFFLINE_ACCESS, | ||||||
|  |     ]; | ||||||
|  |  | ||||||
|  |     private const CLIENT_CREDENTIALS_PERMISSIONS = [ | ||||||
|  |     ]; | ||||||
|  |  | ||||||
|  |     private const CLIENT_CREDENTIALS_PERMISSIONS_INTERNAL = [ | ||||||
|  |         P::BLOCK_ACCOUNT, | ||||||
|  |         P::OBTAIN_EXTENDED_ACCOUNT_INFO, | ||||||
|  |     ]; | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * @inheritdoc |      * @param string $scope | ||||||
|  |      * @param string $grantType передаётся, если запрос поступает из grant. В этом случае нужно отфильтровать | ||||||
|  |      *                          только те права, которые можно получить на этом grant. | ||||||
|  |      * @param string $clientId | ||||||
|  |      * | ||||||
|  |      * @return ScopeEntity|null | ||||||
|      */ |      */ | ||||||
|     public function get($scope, $grantType = null, $clientId = null) { |     public function get($scope, $grantType = null, $clientId = null): ?ScopeEntity { | ||||||
|         $query = OauthScope::find(); |         $permission = $this->convertToInternalPermission($scope); | ||||||
|  |  | ||||||
|         if ($grantType === 'authorization_code') { |         if ($grantType === 'authorization_code') { | ||||||
|             $query->onlyPublic()->usersScopes(); |             $permissions = self::AUTHORIZATION_CODE_PERMISSIONS; | ||||||
|         } elseif ($grantType === 'client_credentials') { |         } elseif ($grantType === 'client_credentials') { | ||||||
|             $query->machineScopes(); |             $permissions = self::CLIENT_CREDENTIALS_PERMISSIONS; | ||||||
|             $isTrusted = false; |             $isTrusted = false; | ||||||
|             if ($clientId !== null) { |             if ($clientId !== null) { | ||||||
|  |                 /** @var ClientEntity $client */ | ||||||
|                 $client = $this->server->getClientStorage()->get($clientId); |                 $client = $this->server->getClientStorage()->get($clientId); | ||||||
|                 if (!$client instanceof ClientEntity) { |                 Assert::that($client)->isInstanceOf(ClientEntity::class); | ||||||
|                     throw new ErrorException('client storage must return instance of ' . ClientEntity::class); |  | ||||||
|                 } |  | ||||||
|  |  | ||||||
|                 $isTrusted = $client->isTrusted(); |                 $isTrusted = $client->isTrusted(); | ||||||
|             } |             } | ||||||
|  |  | ||||||
|             if (!$isTrusted) { |             if ($isTrusted) { | ||||||
|                 $query->onlyPublic(); |                 $permissions = array_merge($permissions, self::CLIENT_CREDENTIALS_PERMISSIONS_INTERNAL); | ||||||
|             } |             } | ||||||
|  |         } else { | ||||||
|  |             $permissions = array_merge( | ||||||
|  |                 self::AUTHORIZATION_CODE_PERMISSIONS, | ||||||
|  |                 self::CLIENT_CREDENTIALS_PERMISSIONS, | ||||||
|  |                 self::CLIENT_CREDENTIALS_PERMISSIONS_INTERNAL | ||||||
|  |             ); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         $scopes = $query->all(); |         if (!in_array($permission, $permissions, true)) { | ||||||
|         if (!in_array($scope, $scopes, true)) { |  | ||||||
|             return null; |             return null; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         $entity = new ScopeEntity($this->server); |         $entity = new ScopeEntity($this->server); | ||||||
|         $entity->setId($scope); |         $entity->setId($permission); | ||||||
|  |  | ||||||
|         return $entity; |         return $entity; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|  |     private function convertToInternalPermission(string $publicScope): string { | ||||||
|  |         return self::PUBLIC_SCOPES_TO_INTERNAL_PERMISSIONS[$publicScope] ?? $publicScope; | ||||||
|  |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,16 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\components\OAuth2\Utils\KeyAlgorithm; |  | ||||||
|  |  | ||||||
| use League\OAuth2\Server\Util\KeyAlgorithm\KeyAlgorithmInterface; |  | ||||||
| use Ramsey\Uuid\Uuid; |  | ||||||
|  |  | ||||||
| class UuidAlgorithm implements KeyAlgorithmInterface { |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     public function generate($len = 40) : string { |  | ||||||
|         return Uuid::uuid4()->toString(); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
							
								
								
									
										60
									
								
								api/components/User/AuthenticationResult.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										60
									
								
								api/components/User/AuthenticationResult.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,60 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\components\User; | ||||||
|  |  | ||||||
|  | use common\models\Account; | ||||||
|  | use common\models\AccountSession; | ||||||
|  | use Emarref\Jwt\Claim\Expiration; | ||||||
|  |  | ||||||
|  | class AuthenticationResult { | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @var Account | ||||||
|  |      */ | ||||||
|  |     private $account; | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @var string | ||||||
|  |      */ | ||||||
|  |     private $jwt; | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @var AccountSession|null | ||||||
|  |      */ | ||||||
|  |     private $session; | ||||||
|  |  | ||||||
|  |     public function __construct(Account $account, string $jwt, ?AccountSession $session) { | ||||||
|  |         $this->account = $account; | ||||||
|  |         $this->jwt = $jwt; | ||||||
|  |         $this->session = $session; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getAccount(): Account { | ||||||
|  |         return $this->account; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getJwt(): string { | ||||||
|  |         return $this->jwt; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getSession(): ?AccountSession { | ||||||
|  |         return $this->session; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getAsResponse() { | ||||||
|  |         $token = (new Jwt())->deserialize($this->getJwt()); | ||||||
|  |  | ||||||
|  |         /** @noinspection NullPointerExceptionInspection */ | ||||||
|  |         $response = [ | ||||||
|  |             'access_token' => $this->getJwt(), | ||||||
|  |             'expires_in' => $token->getPayload()->findClaimByName(Expiration::NAME)->getValue() - time(), | ||||||
|  |         ]; | ||||||
|  |  | ||||||
|  |         $session = $this->getSession(); | ||||||
|  |         if ($session !== null) { | ||||||
|  |             $response['refresh_token'] = $session->refresh_token; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $response; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -1,8 +1,10 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\components\User; | namespace api\components\User; | ||||||
|  |  | ||||||
| use api\models\AccountIdentity; | use api\exceptions\ThisShouldNotHappenException; | ||||||
|  | use common\models\Account; | ||||||
| use common\models\AccountSession; | use common\models\AccountSession; | ||||||
|  | use common\rbac\Roles as R; | ||||||
| use DateInterval; | use DateInterval; | ||||||
| use DateTime; | use DateTime; | ||||||
| use Emarref\Jwt\Algorithm\AlgorithmInterface; | use Emarref\Jwt\Algorithm\AlgorithmInterface; | ||||||
| @@ -10,34 +12,33 @@ use Emarref\Jwt\Algorithm\Hs256; | |||||||
| use Emarref\Jwt\Claim; | use Emarref\Jwt\Claim; | ||||||
| use Emarref\Jwt\Encryption\Factory as EncryptionFactory; | use Emarref\Jwt\Encryption\Factory as EncryptionFactory; | ||||||
| use Emarref\Jwt\Exception\VerificationException; | use Emarref\Jwt\Exception\VerificationException; | ||||||
| use Emarref\Jwt\Jwt; |  | ||||||
| use Emarref\Jwt\Token; | use Emarref\Jwt\Token; | ||||||
| use Emarref\Jwt\Verification\Context as VerificationContext; | use Emarref\Jwt\Verification\Context as VerificationContext; | ||||||
|  | use Exception; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; |  | ||||||
| use yii\base\InvalidConfigException; | use yii\base\InvalidConfigException; | ||||||
| use yii\web\IdentityInterface; |  | ||||||
| use yii\web\User as YiiUserComponent; | use yii\web\User as YiiUserComponent; | ||||||
|  |  | ||||||
| /** | /** | ||||||
|  * @property AccountSession|null $activeSession |  * @property AccountSession|null $activeSession | ||||||
|  * @property AccountIdentity|null $identity |  * @property IdentityInterface|null $identity | ||||||
|  * |  * | ||||||
|  * @method AccountIdentity|null loginByAccessToken($token, $type = null) |  * @method IdentityInterface|null loginByAccessToken($token, $type = null) | ||||||
|  * @method AccountIdentity|null getIdentity($autoRenew = true) |  * @method IdentityInterface|null getIdentity($autoRenew = true) | ||||||
|  */ |  */ | ||||||
| class Component extends YiiUserComponent { | class Component extends YiiUserComponent { | ||||||
|  |  | ||||||
|     const TERMINATE_MINECRAFT_SESSIONS = 1; |     const KEEP_MINECRAFT_SESSIONS = 1; | ||||||
|     const TERMINATE_SITE_SESSIONS = 2; |     const KEEP_SITE_SESSIONS = 2; | ||||||
|     const DO_NOT_TERMINATE_CURRENT_SESSION = 4; |     const KEEP_CURRENT_SESSION = 4; | ||||||
|     const TERMINATE_ALL = self::TERMINATE_MINECRAFT_SESSIONS | self::TERMINATE_SITE_SESSIONS; |  | ||||||
|  |     const JWT_SUBJECT_PREFIX = 'ely|'; | ||||||
|  |  | ||||||
|     public $enableSession = false; |     public $enableSession = false; | ||||||
|  |  | ||||||
|     public $loginUrl = null; |     public $loginUrl = null; | ||||||
|  |  | ||||||
|     public $identityClass = AccountIdentity::class; |     public $identityClass = Identity::class; | ||||||
|  |  | ||||||
|     public $secret; |     public $secret; | ||||||
|  |  | ||||||
| @@ -45,6 +46,11 @@ class Component extends YiiUserComponent { | |||||||
|  |  | ||||||
|     public $sessionTimeout = 'P7D'; |     public $sessionTimeout = 'P7D'; | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @var Token[] | ||||||
|  |      */ | ||||||
|  |     private static $parsedTokensCache = []; | ||||||
|  |  | ||||||
|     public function init() { |     public function init() { | ||||||
|         parent::init(); |         parent::init(); | ||||||
|         if (!$this->secret) { |         if (!$this->secret) { | ||||||
| @@ -52,72 +58,60 @@ class Component extends YiiUserComponent { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     public function findIdentityByAccessToken(string $accessToken): ?IdentityInterface { | ||||||
|      * @param IdentityInterface $identity |         /** @var \api\components\User\IdentityInterface|string $identityClass */ | ||||||
|      * @param bool              $rememberMe |         $identityClass = $this->identityClass; | ||||||
|      * |         try { | ||||||
|      * @return LoginResult|bool |             return $identityClass::findIdentityByAccessToken($accessToken); | ||||||
|      * @throws ErrorException |         } catch (Exception $e) { | ||||||
|      */ |             Yii::error($e); | ||||||
|     public function login(IdentityInterface $identity, $rememberMe = false) { |             return null; | ||||||
|         if (!$this->beforeLogin($identity, false, $rememberMe)) { |  | ||||||
|             return false; |  | ||||||
|         } |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|         $this->switchIdentity($identity, 0); |     public function createJwtAuthenticationToken(Account $account, bool $rememberMe): AuthenticationResult { | ||||||
|  |  | ||||||
|         $id = $identity->getId(); |  | ||||||
|         $ip = Yii::$app->request->userIP; |         $ip = Yii::$app->request->userIP; | ||||||
|         $token = $this->createToken($identity); |         $token = $this->createToken($account); | ||||||
|         if ($rememberMe) { |         if ($rememberMe) { | ||||||
|             $session = new AccountSession(); |             $session = new AccountSession(); | ||||||
|             $session->account_id = $id; |             $session->account_id = $account->id; | ||||||
|             $session->setIp($ip); |             $session->setIp($ip); | ||||||
|             $session->generateRefreshToken(); |             $session->generateRefreshToken(); | ||||||
|             if (!$session->save()) { |             if (!$session->save()) { | ||||||
|                 throw new ErrorException('Cannot save account session model'); |                 throw new ThisShouldNotHappenException('Cannot save account session model'); | ||||||
|             } |             } | ||||||
|  |  | ||||||
|             $token->addClaim(new SessionIdClaim($session->id)); |             $token->addClaim(new Claim\JwtId($session->id)); | ||||||
|         } else { |         } else { | ||||||
|             $session = null; |             $session = null; | ||||||
|             // Если мы не сохраняем сессию, то токен должен жить подольше, чтобы |             // Если мы не сохраняем сессию, то токен должен жить подольше, | ||||||
|             // не прогорала сессия во время работы с аккаунтом |             // чтобы не прогорала сессия во время работы с аккаунтом | ||||||
|             $token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout)))); |             $token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout)))); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         $jwt = $this->serializeToken($token); |         $jwt = $this->serializeToken($token); | ||||||
|  |  | ||||||
|         Yii::info("User '{$id}' logged in from {$ip}.", __METHOD__); |         return new AuthenticationResult($account, $jwt, $session); | ||||||
|  |  | ||||||
|         $result = new LoginResult($identity, $jwt, $session); |  | ||||||
|         $this->afterLogin($identity, false, $rememberMe); |  | ||||||
|  |  | ||||||
|         return $result; |  | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function renew(AccountSession $session): RenewResult { |     public function renewJwtAuthenticationToken(AccountSession $session): AuthenticationResult { | ||||||
|         $account = $session->account; |  | ||||||
|         $transaction = Yii::$app->db->beginTransaction(); |         $transaction = Yii::$app->db->beginTransaction(); | ||||||
|         try { |  | ||||||
|             $identity = new AccountIdentity($account->attributes); |  | ||||||
|             $token = $this->createToken($identity); |  | ||||||
|             $jwt = $this->serializeToken($token); |  | ||||||
|  |  | ||||||
|             $result = new RenewResult($identity, $jwt); |         $account = $session->account; | ||||||
|  |         $token = $this->createToken($account); | ||||||
|  |         $token->addClaim(new Claim\JwtId($session->id)); | ||||||
|  |         $jwt = $this->serializeToken($token); | ||||||
|  |  | ||||||
|             $session->setIp(Yii::$app->request->userIP); |         $result = new AuthenticationResult($account, $jwt, $session); | ||||||
|             $session->last_refreshed_at = time(); |  | ||||||
|             if (!$session->save()) { |  | ||||||
|                 throw new ErrorException('Cannot update session info'); |  | ||||||
|             } |  | ||||||
|  |  | ||||||
|             $transaction->commit(); |         $session->setIp(Yii::$app->request->userIP); | ||||||
|         } catch (ErrorException $e) { |         $session->last_refreshed_at = time(); | ||||||
|             $transaction->rollBack(); |         if (!$session->save()) { | ||||||
|             throw $e; |             throw new ThisShouldNotHappenException('Cannot update session info'); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|  |         $transaction->commit(); | ||||||
|  |  | ||||||
|         return $result; |         return $result; | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -126,15 +120,22 @@ class Component extends YiiUserComponent { | |||||||
|      * @return Token распаршенный токен |      * @return Token распаршенный токен | ||||||
|      * @throws VerificationException если один из Claims не пройдёт проверку |      * @throws VerificationException если один из Claims не пройдёт проверку | ||||||
|      */ |      */ | ||||||
|     public function parseToken(string $jwtString) : Token { |     public function parseToken(string $jwtString): Token { | ||||||
|         $hostInfo = Yii::$app->request->hostInfo; |         $token = &self::$parsedTokensCache[$jwtString]; | ||||||
|  |         if ($token === null) { | ||||||
|  |             $hostInfo = Yii::$app->request->hostInfo; | ||||||
|  |  | ||||||
|         $jwt = new Jwt(); |             $jwt = new Jwt(); | ||||||
|         $token = $jwt->deserialize($jwtString); |             $notVerifiedToken = $jwt->deserialize($jwtString); | ||||||
|         $context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm())); |  | ||||||
|         $context->setAudience($hostInfo); |             $context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm())); | ||||||
|         $context->setIssuer($hostInfo); |             $context->setAudience($hostInfo); | ||||||
|         $jwt->verify($token, $context); |             $context->setIssuer($hostInfo); | ||||||
|  |             $context->setSubject(self::JWT_SUBJECT_PREFIX); | ||||||
|  |             $jwt->verify($notVerifiedToken, $context); | ||||||
|  |  | ||||||
|  |             $token = $notVerifiedToken; | ||||||
|  |         } | ||||||
|  |  | ||||||
|         return $token; |         return $token; | ||||||
|     } |     } | ||||||
| @@ -150,19 +151,23 @@ class Component extends YiiUserComponent { | |||||||
|      * |      * | ||||||
|      * @return AccountSession|null |      * @return AccountSession|null | ||||||
|      */ |      */ | ||||||
|     public function getActiveSession() { |     public function getActiveSession(): ?AccountSession { | ||||||
|         if ($this->getIsGuest()) { |         if ($this->getIsGuest()) { | ||||||
|             return null; |             return null; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         $bearer = $this->getBearerToken(); |         $bearer = $this->getBearerToken(); | ||||||
|  |         if ($bearer === null) { | ||||||
|  |             return null; | ||||||
|  |         } | ||||||
|  |  | ||||||
|         try { |         try { | ||||||
|             $token = $this->parseToken($bearer); |             $token = $this->parseToken($bearer); | ||||||
|         } catch (VerificationException $e) { |         } catch (VerificationException $e) { | ||||||
|             return null; |             return null; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         $sessionId = $token->getPayload()->findClaimByName(SessionIdClaim::NAME); |         $sessionId = $token->getPayload()->findClaimByName(Claim\JwtId::NAME); | ||||||
|         if ($sessionId === null) { |         if ($sessionId === null) { | ||||||
|             return null; |             return null; | ||||||
|         } |         } | ||||||
| @@ -170,35 +175,38 @@ class Component extends YiiUserComponent { | |||||||
|         return AccountSession::findOne($sessionId->getValue()); |         return AccountSession::findOne($sessionId->getValue()); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function terminateSessions(int $mode = self::TERMINATE_ALL | self::DO_NOT_TERMINATE_CURRENT_SESSION): void { |     public function terminateSessions(Account $account, int $mode = 0): void { | ||||||
|         $identity = $this->getIdentity(); |         $currentSession = null; | ||||||
|         $activeSession = ($mode & self::DO_NOT_TERMINATE_CURRENT_SESSION) ? $this->getActiveSession() : null; |         if ($mode & self::KEEP_CURRENT_SESSION) { | ||||||
|         if ($mode & self::TERMINATE_SITE_SESSIONS) { |             $currentSession = $this->getActiveSession(); | ||||||
|             foreach ($identity->sessions as $session) { |         } | ||||||
|                 if ($activeSession === null || $activeSession->id !== $session->id) { |  | ||||||
|  |         if (!($mode & self::KEEP_SITE_SESSIONS)) { | ||||||
|  |             foreach ($account->sessions as $session) { | ||||||
|  |                 if ($currentSession === null || $currentSession->id !== $session->id) { | ||||||
|                     $session->delete(); |                     $session->delete(); | ||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         if ($mode & self::TERMINATE_MINECRAFT_SESSIONS) { |         if (!($mode & self::KEEP_MINECRAFT_SESSIONS)) { | ||||||
|             foreach ($identity->minecraftAccessKeys as $minecraftAccessKey) { |             foreach ($account->minecraftAccessKeys as $minecraftAccessKey) { | ||||||
|                 $minecraftAccessKey->delete(); |                 $minecraftAccessKey->delete(); | ||||||
|             } |             } | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getAlgorithm() : AlgorithmInterface { |     public function getAlgorithm(): AlgorithmInterface { | ||||||
|         return new Hs256($this->secret); |         return new Hs256($this->secret); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     protected function serializeToken(Token $token) : string { |     protected function serializeToken(Token $token): string { | ||||||
|         return (new Jwt())->serialize($token, EncryptionFactory::create($this->getAlgorithm())); |         return (new Jwt())->serialize($token, EncryptionFactory::create($this->getAlgorithm())); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     protected function createToken(IdentityInterface $identity) : Token { |     protected function createToken(Account $account): Token { | ||||||
|         $token = new Token(); |         $token = new Token(); | ||||||
|         foreach($this->getClaims($identity) as $claim) { |         foreach($this->getClaims($account) as $claim) { | ||||||
|             $token->addClaim($claim); |             $token->addClaim($claim); | ||||||
|         } |         } | ||||||
|  |  | ||||||
| @@ -206,25 +214,23 @@ class Component extends YiiUserComponent { | |||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * @param IdentityInterface $identity |      * @param Account $account | ||||||
|      * @return Claim\AbstractClaim[] |      * @return Claim\AbstractClaim[] | ||||||
|      */ |      */ | ||||||
|     protected function getClaims(IdentityInterface $identity) { |     protected function getClaims(Account $account): array { | ||||||
|         $currentTime = new DateTime(); |         $currentTime = new DateTime(); | ||||||
|         $hostInfo = Yii::$app->request->hostInfo; |         $hostInfo = Yii::$app->request->hostInfo; | ||||||
|  |  | ||||||
|         return [ |         return [ | ||||||
|  |             new ScopesClaim([R::ACCOUNTS_WEB_USER]), | ||||||
|             new Claim\Audience($hostInfo), |             new Claim\Audience($hostInfo), | ||||||
|             new Claim\Issuer($hostInfo), |             new Claim\Issuer($hostInfo), | ||||||
|             new Claim\IssuedAt($currentTime), |             new Claim\IssuedAt($currentTime), | ||||||
|             new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))), |             new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))), | ||||||
|             new Claim\JwtId($identity->getId()), |             new Claim\Subject(self::JWT_SUBJECT_PREFIX . $account->id), | ||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @return ?string |  | ||||||
|      */ |  | ||||||
|     private function getBearerToken() { |     private function getBearerToken() { | ||||||
|         $authHeader = Yii::$app->request->getHeaders()->get('Authorization'); |         $authHeader = Yii::$app->request->getHeaders()->get('Authorization'); | ||||||
|         if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) { |         if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) { | ||||||
|   | |||||||
| @@ -1,20 +1,15 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\components\ApiUser; | namespace api\components\User; | ||||||
| 
 | 
 | ||||||
| use api\components\OAuth2\Entities\AccessTokenEntity; | use api\components\OAuth2\Entities\AccessTokenEntity; | ||||||
| use common\models\Account; | use common\models\Account; | ||||||
| use common\models\OauthClient; |  | ||||||
| use common\models\OauthSession; | use common\models\OauthSession; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\base\NotSupportedException; | use yii\base\NotSupportedException; | ||||||
| use yii\web\IdentityInterface; |  | ||||||
| use yii\web\UnauthorizedHttpException; | use yii\web\UnauthorizedHttpException; | ||||||
| 
 | 
 | ||||||
| /** | /** | ||||||
|  * @property Account           $account |  * @property Account $account | ||||||
|  * @property OauthClient       $client |  | ||||||
|  * @property OauthSession      $session |  | ||||||
|  * @property AccessTokenEntity $accessToken |  | ||||||
|  */ |  */ | ||||||
| class Identity implements IdentityInterface { | class Identity implements IdentityInterface { | ||||||
| 
 | 
 | ||||||
| @@ -25,44 +20,43 @@ class Identity implements IdentityInterface { | |||||||
| 
 | 
 | ||||||
|     /** |     /** | ||||||
|      * @inheritdoc |      * @inheritdoc | ||||||
|  |      * @throws \yii\web\UnauthorizedHttpException | ||||||
|  |      * @return IdentityInterface | ||||||
|      */ |      */ | ||||||
|     public static function findIdentityByAccessToken($token, $type = null): self { |     public static function findIdentityByAccessToken($token, $type = null): IdentityInterface { | ||||||
|  |         if ($token === null) { | ||||||
|  |             throw new UnauthorizedHttpException('Incorrect token'); | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         // Speed-improved analogue of the `count(explode('.', $token)) === 3`
 | ||||||
|  |         if (substr_count($token, '.') === 2) { | ||||||
|  |             return JwtIdentity::findIdentityByAccessToken($token, $type); | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|         /** @var AccessTokenEntity|null $model */ |         /** @var AccessTokenEntity|null $model */ | ||||||
|         $model = Yii::$app->oauth->getAuthServer()->getAccessTokenStorage()->get($token); |         $model = Yii::$app->oauth->getAccessTokenStorage()->get($token); | ||||||
|         if ($model === null) { |         if ($model === null) { | ||||||
|             throw new UnauthorizedHttpException('Incorrect token'); |             throw new UnauthorizedHttpException('Incorrect token'); | ||||||
|         } elseif ($model->isExpired()) { |         } | ||||||
|  | 
 | ||||||
|  |         if ($model->isExpired()) { | ||||||
|             throw new UnauthorizedHttpException('Token expired'); |             throw new UnauthorizedHttpException('Token expired'); | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         return new static($model); |         return new static($model); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private function __construct(AccessTokenEntity $accessToken) { |     public function getAccount(): ?Account { | ||||||
|         $this->_accessToken = $accessToken; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function getAccount(): Account { |  | ||||||
|         return $this->getSession()->account; |         return $this->getSession()->account; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function getClient(): OauthClient { |  | ||||||
|         return $this->getSession()->client; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function getSession(): OauthSession { |  | ||||||
|         return OauthSession::findOne($this->_accessToken->getSessionId()); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function getAccessToken(): AccessTokenEntity { |  | ||||||
|         return $this->_accessToken; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     /** |     /** | ||||||
|      * Этот метод используется для получения токена, к которому привязаны права. |      * @return string[] | ||||||
|      * У нас права привязываются к токенам, так что возвращаем именно его id. |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |      */ | ||||||
|  |     public function getAssignedPermissions(): array { | ||||||
|  |         return array_keys($this->_accessToken->getScopes()); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|     public function getId(): string { |     public function getId(): string { | ||||||
|         return $this->_accessToken->getId(); |         return $this->_accessToken->getId(); | ||||||
|     } |     } | ||||||
| @@ -79,4 +73,12 @@ class Identity implements IdentityInterface { | |||||||
|         throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); |         throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|  |     private function __construct(AccessTokenEntity $accessToken) { | ||||||
|  |         $this->_accessToken = $accessToken; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     private function getSession(): OauthSession { | ||||||
|  |         return OauthSession::findOne($this->_accessToken->getSessionId()); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
| } | } | ||||||
							
								
								
									
										32
									
								
								api/components/User/IdentityInterface.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										32
									
								
								api/components/User/IdentityInterface.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,32 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\components\User; | ||||||
|  |  | ||||||
|  | use common\models\Account; | ||||||
|  |  | ||||||
|  | interface IdentityInterface extends \yii\web\IdentityInterface { | ||||||
|  |  | ||||||
|  |     public static function findIdentityByAccessToken($token, $type = null): IdentityInterface; | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * Этот метод используется для получения токена, к которому привязаны права. | ||||||
|  |      * У нас права привязываются к токенам, так что возвращаем именно его id. | ||||||
|  |      * | ||||||
|  |      * @return string | ||||||
|  |      */ | ||||||
|  |     public function getId(): string; | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * Метод возвращает аккаунт, который привязан к текущему токену. | ||||||
|  |      * Но не исключено, что токен был выдан и без привязки к аккаунту, так что | ||||||
|  |      * следует это учитывать. | ||||||
|  |      * | ||||||
|  |      * @return Account|null | ||||||
|  |      */ | ||||||
|  |     public function getAccount(): ?Account; | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @return string[] | ||||||
|  |      */ | ||||||
|  |     public function getAssignedPermissions(): array; | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										23
									
								
								api/components/User/Jwt.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										23
									
								
								api/components/User/Jwt.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,23 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\components\User; | ||||||
|  |  | ||||||
|  | use Emarref\Jwt\Verification\Context; | ||||||
|  | use Emarref\Jwt\Verification\SubjectVerifier; | ||||||
|  |  | ||||||
|  | class Jwt extends \Emarref\Jwt\Jwt { | ||||||
|  |  | ||||||
|  |     protected function getVerifiers(Context $context): array { | ||||||
|  |         $verifiers = parent::getVerifiers($context); | ||||||
|  |         foreach ($verifiers as $i => $verifier) { | ||||||
|  |             if (!$verifier instanceof SubjectVerifier) { | ||||||
|  |                 continue; | ||||||
|  |             } | ||||||
|  |  | ||||||
|  |             $verifiers[$i] = new SubjectPrefixVerifier($context->getSubject()); | ||||||
|  |             break; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $verifiers; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										94
									
								
								api/components/User/JwtIdentity.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										94
									
								
								api/components/User/JwtIdentity.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,94 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\components\User; | ||||||
|  |  | ||||||
|  | use common\models\Account; | ||||||
|  | use Emarref\Jwt\Claim\Subject; | ||||||
|  | use Emarref\Jwt\Exception\ExpiredException; | ||||||
|  | use Emarref\Jwt\Token; | ||||||
|  | use Exception; | ||||||
|  | use Yii; | ||||||
|  | use yii\base\NotSupportedException; | ||||||
|  | use yii\helpers\StringHelper; | ||||||
|  | use yii\web\UnauthorizedHttpException; | ||||||
|  |  | ||||||
|  | class JwtIdentity implements IdentityInterface { | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @var string | ||||||
|  |      */ | ||||||
|  |     private $rawToken; | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @var Token | ||||||
|  |      */ | ||||||
|  |     private $token; | ||||||
|  |  | ||||||
|  |     public static function findIdentityByAccessToken($rawToken, $type = null): IdentityInterface { | ||||||
|  |         /** @var \api\components\User\Component $component */ | ||||||
|  |         $component = Yii::$app->user; | ||||||
|  |         try { | ||||||
|  |             $token = $component->parseToken($rawToken); | ||||||
|  |         } catch (ExpiredException $e) { | ||||||
|  |             throw new UnauthorizedHttpException('Token expired'); | ||||||
|  |         } catch (Exception $e) { | ||||||
|  |             Yii::error($e); | ||||||
|  |             throw new UnauthorizedHttpException('Incorrect token'); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return new self($rawToken, $token); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getAccount(): ?Account { | ||||||
|  |         /** @var Subject $subject */ | ||||||
|  |         $subject = $this->token->getPayload()->findClaimByName(Subject::NAME); | ||||||
|  |         if ($subject === null) { | ||||||
|  |             return null; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         $value = $subject->getValue(); | ||||||
|  |         if (!StringHelper::startsWith($value, Component::JWT_SUBJECT_PREFIX)) { | ||||||
|  |             Yii::warning('Unknown jwt subject: ' . $value); | ||||||
|  |             return null; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         $accountId = (int)mb_substr($value, mb_strlen(Component::JWT_SUBJECT_PREFIX)); | ||||||
|  |         $account = Account::findOne($accountId); | ||||||
|  |         if ($account === null) { | ||||||
|  |             return null; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $account; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getAssignedPermissions(): array { | ||||||
|  |         /** @var Subject $scopesClaim */ | ||||||
|  |         $scopesClaim = $this->token->getPayload()->findClaimByName(ScopesClaim::NAME); | ||||||
|  |         if ($scopesClaim === null) { | ||||||
|  |             return []; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return explode(',', $scopesClaim->getValue()); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getId(): string { | ||||||
|  |         return $this->rawToken; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getAuthKey() { | ||||||
|  |         throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function validateAuthKey($authKey) { | ||||||
|  |         throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public static function findIdentity($id) { | ||||||
|  |         throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     private function __construct(string $rawToken, Token $token) { | ||||||
|  |         $this->rawToken = $rawToken; | ||||||
|  |         $this->token = $token; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -1,67 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\components\User; |  | ||||||
|  |  | ||||||
| use common\models\AccountSession; |  | ||||||
| use DateInterval; |  | ||||||
| use DateTime; |  | ||||||
| use Yii; |  | ||||||
| use yii\web\IdentityInterface; |  | ||||||
|  |  | ||||||
| class LoginResult { |  | ||||||
|     /** |  | ||||||
|      * @var IdentityInterface |  | ||||||
|      */ |  | ||||||
|     private $identity; |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @var string |  | ||||||
|      */ |  | ||||||
|     private $jwt; |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @var AccountSession|null |  | ||||||
|      */ |  | ||||||
|     private $session; |  | ||||||
|  |  | ||||||
|     public function __construct(IdentityInterface $identity, string $jwt, AccountSession $session = null) { |  | ||||||
|         $this->identity = $identity; |  | ||||||
|         $this->jwt = $jwt; |  | ||||||
|         $this->session = $session; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getIdentity() : IdentityInterface { |  | ||||||
|         return $this->identity; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getJwt() : string { |  | ||||||
|         return $this->jwt; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @return AccountSession|null |  | ||||||
|      */ |  | ||||||
|     public function getSession() { |  | ||||||
|         return $this->session; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getAsResponse() { |  | ||||||
|         /** @var Component $component */ |  | ||||||
|         $component = Yii::$app->user; |  | ||||||
|  |  | ||||||
|         $now = new DateTime(); |  | ||||||
|         $expiresIn = (clone $now)->add(new DateInterval($component->expirationTimeout)); |  | ||||||
|  |  | ||||||
|         $response = [ |  | ||||||
|             'access_token' => $this->getJwt(), |  | ||||||
|             'expires_in' => $expiresIn->getTimestamp() - $now->getTimestamp(), |  | ||||||
|         ]; |  | ||||||
|  |  | ||||||
|         $session = $this->getSession(); |  | ||||||
|         if ($session !== null) { |  | ||||||
|             $response['refresh_token'] = $session->refresh_token; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return $response; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -1,47 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\components\User; |  | ||||||
|  |  | ||||||
| use DateInterval; |  | ||||||
| use DateTime; |  | ||||||
| use Yii; |  | ||||||
| use yii\web\IdentityInterface; |  | ||||||
|  |  | ||||||
| class RenewResult { |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @var IdentityInterface |  | ||||||
|      */ |  | ||||||
|     private $identity; |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @var string |  | ||||||
|      */ |  | ||||||
|     private $jwt; |  | ||||||
|  |  | ||||||
|     public function __construct(IdentityInterface $identity, string $jwt) { |  | ||||||
|         $this->identity = $identity; |  | ||||||
|         $this->jwt = $jwt; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getIdentity() : IdentityInterface { |  | ||||||
|         return $this->identity; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getJwt() : string { |  | ||||||
|         return $this->jwt; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getAsResponse() { |  | ||||||
|         /** @var Component $component */ |  | ||||||
|         $component = Yii::$app->user; |  | ||||||
|  |  | ||||||
|         $now = new DateTime(); |  | ||||||
|         $expiresIn = (clone $now)->add(new DateInterval($component->expirationTimeout)); |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'access_token' => $this->getJwt(), |  | ||||||
|             'expires_in' => $expiresIn->getTimestamp() - $now->getTimestamp(), |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
							
								
								
									
										30
									
								
								api/components/User/ScopesClaim.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										30
									
								
								api/components/User/ScopesClaim.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,30 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\components\User; | ||||||
|  |  | ||||||
|  | use Emarref\Jwt\Claim\AbstractClaim; | ||||||
|  |  | ||||||
|  | class ScopesClaim extends AbstractClaim { | ||||||
|  |  | ||||||
|  |     const NAME = 'ely-scopes'; | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * ScopesClaim constructor. | ||||||
|  |      * | ||||||
|  |      * @param array|string $value | ||||||
|  |      */ | ||||||
|  |     public function __construct($value = null) { | ||||||
|  |         if (is_array($value)) { | ||||||
|  |             $value = implode(',', $value); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         parent::__construct($value); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @inheritdoc | ||||||
|  |      */ | ||||||
|  |     public function getName(): string { | ||||||
|  |         return self::NAME; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -1,17 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\components\User; |  | ||||||
|  |  | ||||||
| use Emarref\Jwt\Claim\AbstractClaim; |  | ||||||
|  |  | ||||||
| class SessionIdClaim extends AbstractClaim { |  | ||||||
|  |  | ||||||
|     const NAME = 'sid'; |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     public function getName() { |  | ||||||
|         return self::NAME; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
							
								
								
									
										28
									
								
								api/components/User/SubjectPrefixVerifier.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								api/components/User/SubjectPrefixVerifier.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,28 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\components\User; | ||||||
|  |  | ||||||
|  | use Emarref\Jwt\Claim\Subject; | ||||||
|  | use Emarref\Jwt\Exception\InvalidSubjectException; | ||||||
|  | use Emarref\Jwt\Token; | ||||||
|  | use Emarref\Jwt\Verification\VerifierInterface; | ||||||
|  | use yii\helpers\StringHelper; | ||||||
|  |  | ||||||
|  | class SubjectPrefixVerifier implements VerifierInterface { | ||||||
|  |  | ||||||
|  |     private $subjectPrefix; | ||||||
|  |  | ||||||
|  |     public function __construct(string $subjectPrefix) { | ||||||
|  |         $this->subjectPrefix = $subjectPrefix; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function verify(Token $token): void { | ||||||
|  |         /** @var Subject $subjectClaim */ | ||||||
|  |         $subjectClaim = $token->getPayload()->findClaimByName(Subject::NAME); | ||||||
|  |         $subject = ($subjectClaim === null) ? null : $subjectClaim->getValue(); | ||||||
|  |  | ||||||
|  |         if (!StringHelper::startsWith($subject, $this->subjectPrefix)) { | ||||||
|  |             throw new InvalidSubjectException; | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -15,9 +15,6 @@ return [ | |||||||
|             'class' => api\components\User\Component::class, |             'class' => api\components\User\Component::class, | ||||||
|             'secret' => getenv('JWT_USER_SECRET'), |             'secret' => getenv('JWT_USER_SECRET'), | ||||||
|         ], |         ], | ||||||
|         'apiUser' => [ |  | ||||||
|             'class' => api\components\ApiUser\Component::class, |  | ||||||
|         ], |  | ||||||
|         'log' => [ |         'log' => [ | ||||||
|             'traceLevel' => YII_DEBUG ? 3 : 0, |             'traceLevel' => YII_DEBUG ? 3 : 0, | ||||||
|             'targets' => [ |             'targets' => [ | ||||||
| @@ -85,14 +82,9 @@ return [ | |||||||
|             'class' => api\modules\authserver\Module::class, |             'class' => api\modules\authserver\Module::class, | ||||||
|             'host' => $params['authserverHost'], |             'host' => $params['authserverHost'], | ||||||
|         ], |         ], | ||||||
|         'session' => [ |         'session' => api\modules\session\Module::class, | ||||||
|             'class' => api\modules\session\Module::class, |         'mojang' => api\modules\mojang\Module::class, | ||||||
|         ], |         'internal' => api\modules\internal\Module::class, | ||||||
|         'mojang' => [ |         'accounts' => api\modules\accounts\Module::class, | ||||||
|             'class' => api\modules\mojang\Module::class, |  | ||||||
|         ], |  | ||||||
|         'internal' => [ |  | ||||||
|             'class' => api\modules\internal\Module::class, |  | ||||||
|         ], |  | ||||||
|     ], |     ], | ||||||
| ]; | ]; | ||||||
|   | |||||||
| @@ -3,15 +3,16 @@ | |||||||
|  * @var array $params |  * @var array $params | ||||||
|  */ |  */ | ||||||
| return [ | return [ | ||||||
|     '/accounts/change-email/initialize' => 'accounts/change-email-initialize', |  | ||||||
|     '/accounts/change-email/submit-new-email' => 'accounts/change-email-submit-new-email', |  | ||||||
|     '/accounts/change-email/confirm-new-email' => 'accounts/change-email-confirm-new-email', |  | ||||||
|  |  | ||||||
|     'POST /two-factor-auth' => 'two-factor-auth/activate', |  | ||||||
|     'DELETE /two-factor-auth' => 'two-factor-auth/disable', |  | ||||||
|  |  | ||||||
|     '/oauth2/v1/<action>' => 'oauth/<action>', |     '/oauth2/v1/<action>' => 'oauth/<action>', | ||||||
|  |  | ||||||
|  |     'GET /v1/accounts/<id:\d+>' => 'accounts/default/get', | ||||||
|  |     'GET /v1/accounts/<id:\d+>/two-factor-auth' => 'accounts/default/get-two-factor-auth-credentials', | ||||||
|  |     'POST /v1/accounts/<id:\d+>/two-factor-auth' => 'accounts/default/enable-two-factor-auth', | ||||||
|  |     'DELETE /v1/accounts/<id:\d+>/two-factor-auth' => 'accounts/default/disable-two-factor-auth', | ||||||
|  |     'POST /v1/accounts/<id:\d+>/ban' => 'accounts/default/ban', | ||||||
|  |     'DELETE /v1/accounts/<id:\d+>/ban' => 'accounts/default/pardon', | ||||||
|  |     '/v1/accounts/<id:\d+>/<action>' => 'accounts/default/<action>', | ||||||
|  |  | ||||||
|     '/account/v1/info' => 'identity-info/index', |     '/account/v1/info' => 'identity-info/index', | ||||||
|  |  | ||||||
|     '/minecraft/session/join' => 'session/session/join', |     '/minecraft/session/join' => 'session/session/join', | ||||||
|   | |||||||
| @@ -1,201 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\controllers; |  | ||||||
|  |  | ||||||
| use api\filters\ActiveUserRule; |  | ||||||
| use api\models\profile\AcceptRulesForm; |  | ||||||
| use api\models\profile\ChangeEmail\ConfirmNewEmailForm; |  | ||||||
| use api\models\profile\ChangeEmail\InitStateForm; |  | ||||||
| use api\models\profile\ChangeEmail\NewEmailForm; |  | ||||||
| use api\models\profile\ChangeLanguageForm; |  | ||||||
| use api\models\profile\ChangePasswordForm; |  | ||||||
| use api\models\profile\ChangeUsernameForm; |  | ||||||
| use common\helpers\Error as E; |  | ||||||
| use common\models\Account; |  | ||||||
| use Yii; |  | ||||||
| use yii\filters\AccessControl; |  | ||||||
| use yii\helpers\ArrayHelper; |  | ||||||
|  |  | ||||||
| class AccountsController extends Controller { |  | ||||||
|  |  | ||||||
|     public function behaviors() { |  | ||||||
|         return ArrayHelper::merge(parent::behaviors(), [ |  | ||||||
|             'access' => [ |  | ||||||
|                 'class' => AccessControl::class, |  | ||||||
|                 'rules' => [ |  | ||||||
|                     [ |  | ||||||
|                         'actions' => ['current', 'accept-rules'], |  | ||||||
|                         'allow' => true, |  | ||||||
|                         'roles' => ['@'], |  | ||||||
|                     ], |  | ||||||
|                     [ |  | ||||||
|                         'class' => ActiveUserRule::class, |  | ||||||
|                         'actions' => [ |  | ||||||
|                             'change-password', |  | ||||||
|                             'change-username', |  | ||||||
|                             'change-email-initialize', |  | ||||||
|                             'change-email-submit-new-email', |  | ||||||
|                             'change-email-confirm-new-email', |  | ||||||
|                             'change-lang', |  | ||||||
|                         ], |  | ||||||
|                     ], |  | ||||||
|                 ], |  | ||||||
|             ], |  | ||||||
|         ]); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function verbs() { |  | ||||||
|         return [ |  | ||||||
|             'current' => ['GET'], |  | ||||||
|             'change-password' => ['POST'], |  | ||||||
|             'change-username' => ['POST'], |  | ||||||
|             'change-email-initialize' => ['POST'], |  | ||||||
|             'change-email-submit-new-email' => ['POST'], |  | ||||||
|             'change-email-confirm-new-email' => ['POST'], |  | ||||||
|             'change-lang' => ['POST'], |  | ||||||
|             'accept-rules' => ['POST'], |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionCurrent() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'id' => $account->id, |  | ||||||
|             'uuid' => $account->uuid, |  | ||||||
|             'username' => $account->username, |  | ||||||
|             'email' => $account->email, |  | ||||||
|             'lang' => $account->lang, |  | ||||||
|             'isActive' => $account->status === Account::STATUS_ACTIVE, |  | ||||||
|             'passwordChangedAt' => $account->password_changed_at, |  | ||||||
|             'hasMojangUsernameCollision' => $account->hasMojangUsernameCollision(), |  | ||||||
|             'shouldAcceptRules' => !$account->isAgreedWithActualRules(), |  | ||||||
|             'isOtpEnabled' => (bool)$account->is_otp_enabled, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionChangePassword() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new ChangePasswordForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->changePassword()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionChangeUsername() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new ChangeUsernameForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->change()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionChangeEmailInitialize() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new InitStateForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->sendCurrentEmailConfirmation()) { |  | ||||||
|             $data = [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|  |  | ||||||
|             if (ArrayHelper::getValue($data['errors'], 'email') === E::RECENTLY_SENT_MESSAGE) { |  | ||||||
|                 $emailActivation = $model->getEmailActivation(); |  | ||||||
|                 $data['data'] = [ |  | ||||||
|                     'canRepeatIn' => $emailActivation->canRepeatIn(), |  | ||||||
|                     'repeatFrequency' => $emailActivation->repeatTimeout, |  | ||||||
|                 ]; |  | ||||||
|             } |  | ||||||
|  |  | ||||||
|             return $data; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionChangeEmailSubmitNewEmail() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new NewEmailForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->sendNewEmailConfirmation()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionChangeEmailConfirmNewEmail() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new ConfirmNewEmailForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->changeEmail()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|             'data' => [ |  | ||||||
|                 'email' => $account->email, |  | ||||||
|             ], |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionChangeLang() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new ChangeLanguageForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->applyLanguage()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionAcceptRules() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new AcceptRulesForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->agreeWithLatestRules()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -1,31 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\controllers; |  | ||||||
|  |  | ||||||
| use Yii; |  | ||||||
| use yii\filters\auth\HttpBearerAuth; |  | ||||||
|  |  | ||||||
| /** |  | ||||||
|  * Поведения: |  | ||||||
|  * @mixin \yii\filters\ContentNegotiator |  | ||||||
|  * @mixin \yii\filters\VerbFilter |  | ||||||
|  * @mixin HttpBearerAuth |  | ||||||
|  */ |  | ||||||
| class ApiController extends \yii\rest\Controller { |  | ||||||
|  |  | ||||||
|     public function behaviors() { |  | ||||||
|         $parentBehaviors = parent::behaviors(); |  | ||||||
|         // Добавляем авторизатор для входа по Bearer токенам |  | ||||||
|         $parentBehaviors['authenticator'] = [ |  | ||||||
|             'class' => HttpBearerAuth::class, |  | ||||||
|             'user' => Yii::$app->apiUser, |  | ||||||
|         ]; |  | ||||||
|  |  | ||||||
|         // xml нам не понадобится |  | ||||||
|         unset($parentBehaviors['contentNegotiator']['formats']['application/xml']); |  | ||||||
|         // rate limiter здесь не применяется |  | ||||||
|         unset($parentBehaviors['rateLimiter']); |  | ||||||
|  |  | ||||||
|         return $parentBehaviors; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -14,7 +14,7 @@ use yii\helpers\ArrayHelper; | |||||||
|  |  | ||||||
| class AuthenticationController extends Controller { | class AuthenticationController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         return ArrayHelper::merge(parent::behaviors(), [ |         return ArrayHelper::merge(parent::behaviors(), [ | ||||||
|             'authenticator' => [ |             'authenticator' => [ | ||||||
|                 'only' => ['logout'], |                 'only' => ['logout'], | ||||||
| @@ -139,9 +139,12 @@ class AuthenticationController extends Controller { | |||||||
|             ]; |             ]; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|  |         $response = $result->getAsResponse(); | ||||||
|  |         unset($response['refresh_token']); | ||||||
|  |  | ||||||
|         return array_merge([ |         return array_merge([ | ||||||
|             'success' => true, |             'success' => true, | ||||||
|         ], $result->getAsResponse()); |         ], $response); | ||||||
|     } |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -12,7 +12,7 @@ use yii\filters\auth\HttpBearerAuth; | |||||||
|  */ |  */ | ||||||
| class Controller extends \yii\rest\Controller { | class Controller extends \yii\rest\Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         $parentBehaviors = parent::behaviors(); |         $parentBehaviors = parent::behaviors(); | ||||||
|         // Добавляем авторизатор для входа по jwt токенам |         // Добавляем авторизатор для входа по jwt токенам | ||||||
|         $parentBehaviors['authenticator'] = [ |         $parentBehaviors['authenticator'] = [ | ||||||
|   | |||||||
| @@ -7,7 +7,7 @@ use yii\helpers\ArrayHelper; | |||||||
|  |  | ||||||
| class FeedbackController extends Controller { | class FeedbackController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         return ArrayHelper::merge(parent::behaviors(), [ |         return ArrayHelper::merge(parent::behaviors(), [ | ||||||
|             'authenticator' => [ |             'authenticator' => [ | ||||||
|                 'optional' => ['index'], |                 'optional' => ['index'], | ||||||
|   | |||||||
| @@ -1,14 +1,15 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\controllers; | namespace api\controllers; | ||||||
|  |  | ||||||
| use api\components\ApiUser\AccessControl; | use api\models\OauthAccountInfo; | ||||||
| use common\models\OauthScope as S; | use common\rbac\Permissions as P; | ||||||
| use Yii; | use Yii; | ||||||
|  | use yii\filters\AccessControl; | ||||||
| use yii\helpers\ArrayHelper; | use yii\helpers\ArrayHelper; | ||||||
|  |  | ||||||
| class IdentityInfoController extends ApiController { | class IdentityInfoController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         return ArrayHelper::merge(parent::behaviors(), [ |         return ArrayHelper::merge(parent::behaviors(), [ | ||||||
|             'access' => [ |             'access' => [ | ||||||
|                 'class' => AccessControl::class, |                 'class' => AccessControl::class, | ||||||
| @@ -16,29 +17,22 @@ class IdentityInfoController extends ApiController { | |||||||
|                     [ |                     [ | ||||||
|                         'actions' => ['index'], |                         'actions' => ['index'], | ||||||
|                         'allow' => true, |                         'allow' => true, | ||||||
|                         'roles' => [S::ACCOUNT_INFO], |                         'roles' => [P::OBTAIN_ACCOUNT_INFO], | ||||||
|  |                         'roleParams' => function() { | ||||||
|  |                             /** @noinspection NullPointerExceptionInspection */ | ||||||
|  |                             return [ | ||||||
|  |                                 'accountId' => Yii::$app->user->getIdentity()->getAccount()->id, | ||||||
|  |                             ]; | ||||||
|  |                         }, | ||||||
|                     ], |                     ], | ||||||
|                 ], |                 ], | ||||||
|             ], |             ], | ||||||
|         ]); |         ]); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function actionIndex() { |     public function actionIndex(): array { | ||||||
|         $account = Yii::$app->apiUser->getIdentity()->getAccount(); |         /** @noinspection NullPointerExceptionInspection */ | ||||||
|         $response = [ |         return (new OauthAccountInfo(Yii::$app->user->getIdentity()->getAccount()))->info(); | ||||||
|             'id' => $account->id, |  | ||||||
|             'uuid' => $account->uuid, |  | ||||||
|             'username' => $account->username, |  | ||||||
|             'registeredAt' => $account->created_at, |  | ||||||
|             'profileLink' => $account->getProfileLink(), |  | ||||||
|             'preferredLanguage' => $account->lang, |  | ||||||
|         ]; |  | ||||||
|  |  | ||||||
|         if (Yii::$app->apiUser->can(S::ACCOUNT_EMAIL)) { |  | ||||||
|             $response['email'] = $account->email; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return $response; |  | ||||||
|     } |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,8 +1,8 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\controllers; | namespace api\controllers; | ||||||
|  |  | ||||||
| use api\filters\ActiveUserRule; |  | ||||||
| use api\models\OauthProcess; | use api\models\OauthProcess; | ||||||
|  | use common\rbac\Permissions as P; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\filters\AccessControl; | use yii\filters\AccessControl; | ||||||
| use yii\helpers\ArrayHelper; | use yii\helpers\ArrayHelper; | ||||||
| @@ -19,8 +19,14 @@ class OauthController extends Controller { | |||||||
|                 'only' => ['complete'], |                 'only' => ['complete'], | ||||||
|                 'rules' => [ |                 'rules' => [ | ||||||
|                     [ |                     [ | ||||||
|                         'class' => ActiveUserRule::class, |                         'allow' => true, | ||||||
|                         'actions' => ['complete'], |                         'actions' => ['complete'], | ||||||
|  |                         'roles' => [P::COMPLETE_OAUTH_FLOW], | ||||||
|  |                         'roleParams' => function() { | ||||||
|  |                             return [ | ||||||
|  |                                 'accountId' => Yii::$app->user->identity->getAccount()->id, | ||||||
|  |                             ]; | ||||||
|  |                         }, | ||||||
|                     ], |                     ], | ||||||
|                 ], |                 ], | ||||||
|             ], |             ], | ||||||
|   | |||||||
| @@ -7,7 +7,7 @@ use yii\helpers\ArrayHelper; | |||||||
|  |  | ||||||
| class OptionsController extends Controller { | class OptionsController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         return ArrayHelper::merge(parent::behaviors(), [ |         return ArrayHelper::merge(parent::behaviors(), [ | ||||||
|             'authenticator' => [ |             'authenticator' => [ | ||||||
|                 'except' => ['index'], |                 'except' => ['index'], | ||||||
|   | |||||||
| @@ -11,7 +11,7 @@ use yii\helpers\ArrayHelper; | |||||||
|  |  | ||||||
| class SignupController extends Controller { | class SignupController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         return ArrayHelper::merge(parent::behaviors(), [ |         return ArrayHelper::merge(parent::behaviors(), [ | ||||||
|             'authenticator' => [ |             'authenticator' => [ | ||||||
|                 'except' => ['index', 'repeat-message', 'confirm'], |                 'except' => ['index', 'repeat-message', 'confirm'], | ||||||
|   | |||||||
| @@ -1,75 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\controllers; |  | ||||||
|  |  | ||||||
| use api\filters\ActiveUserRule; |  | ||||||
| use api\models\profile\TwoFactorAuthForm; |  | ||||||
| use Yii; |  | ||||||
| use yii\filters\AccessControl; |  | ||||||
| use yii\helpers\ArrayHelper; |  | ||||||
|  |  | ||||||
| class TwoFactorAuthController extends Controller { |  | ||||||
|  |  | ||||||
|     public $defaultAction = 'credentials'; |  | ||||||
|  |  | ||||||
|     public function behaviors() { |  | ||||||
|         return ArrayHelper::merge(parent::behaviors(), [ |  | ||||||
|             'access' => [ |  | ||||||
|                 'class' => AccessControl::class, |  | ||||||
|                 'rules' => [ |  | ||||||
|                     [ |  | ||||||
|                         'allow' => true, |  | ||||||
|                         'class' => ActiveUserRule::class, |  | ||||||
|                     ], |  | ||||||
|                 ], |  | ||||||
|             ], |  | ||||||
|         ]); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function verbs() { |  | ||||||
|         return [ |  | ||||||
|             'credentials' => ['GET'], |  | ||||||
|             'activate' => ['POST'], |  | ||||||
|             'disable' => ['DELETE'], |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionCredentials() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new TwoFactorAuthForm($account); |  | ||||||
|  |  | ||||||
|         return $model->getCredentials(); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionActivate() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new TwoFactorAuthForm($account, ['scenario' => TwoFactorAuthForm::SCENARIO_ACTIVATE]); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->activate()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionDisable() { |  | ||||||
|         $account = Yii::$app->user->identity; |  | ||||||
|         $model = new TwoFactorAuthForm($account, ['scenario' => TwoFactorAuthForm::SCENARIO_DISABLE]); |  | ||||||
|         $model->load(Yii::$app->request->getBodyParams()); |  | ||||||
|         if (!$model->disable()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -6,6 +6,6 @@ namespace api\exceptions; | |||||||
|  * но теоретически может произойти. Целью является отлавливание таких участков и доработка логики, |  * но теоретически может произойти. Целью является отлавливание таких участков и доработка логики, | ||||||
|  * если такие ситуации всё же будут иметь место случаться. |  * если такие ситуации всё же будут иметь место случаться. | ||||||
|  */ |  */ | ||||||
| class ThisShouldNotHaveHappenedException extends Exception { | class ThisShouldNotHappenException extends Exception { | ||||||
| 
 | 
 | ||||||
| } | } | ||||||
| @@ -1,28 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\filters; |  | ||||||
|  |  | ||||||
| use common\models\Account; |  | ||||||
| use Yii; |  | ||||||
| use yii\filters\AccessRule; |  | ||||||
|  |  | ||||||
| class ActiveUserRule extends AccessRule { |  | ||||||
|  |  | ||||||
|     public $roles = ['@']; |  | ||||||
|  |  | ||||||
|     public $allow = true; |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     protected function matchCustom($action) { |  | ||||||
|         $account = $this->getIdentity(); |  | ||||||
|  |  | ||||||
|         return $account->status === Account::STATUS_ACTIVE |  | ||||||
|             && $account->isAgreedWithActualRules(); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     protected function getIdentity() { |  | ||||||
|         return Yii::$app->getUser()->getIdentity(); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -1,68 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\filters; |  | ||||||
|  |  | ||||||
| use Yii; |  | ||||||
| use yii\base\ActionFilter; |  | ||||||
| use yii\web\ForbiddenHttpException; |  | ||||||
|  |  | ||||||
| // TODO: покрыть тестами |  | ||||||
| class RequestFilter extends ActionFilter { |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @var string[] список IP адресов, с которых допустимо запрашивать указанные action'ы. |  | ||||||
|      * Каждый элемент массива представляет из себя один IP фильтр, который может быть точным IP адресом |  | ||||||
|      * или задавать маску адресов (например, 192.168.0.*) для покрытия сегмента сети. |  | ||||||
|      * Стандартным значением является `['127.0.0.1', '::1']`, что значит, что доступ разрешон только |  | ||||||
|      * с localhost'а. |  | ||||||
|      */ |  | ||||||
|     public $allowedIPs = ['127.0.0.1', '::1']; |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @var string[] список имён хостов, с которых можно запрашивать указанные action'ы. |  | ||||||
|      * Каждый элемент массива задаёт имя хоста, которое будет преобразовано в IP адрес, который |  | ||||||
|      * и будет сравниваться с IP адресом пользователя. Это полезно при использовании DNS (DDNS) для |  | ||||||
|      * организации динамического доступа. |  | ||||||
|      * Стандартным значением является `[]`, что означает, что хосты не проверяются. |  | ||||||
|      */ |  | ||||||
|     public $allowedHosts = []; |  | ||||||
|  |  | ||||||
|     public function beforeAction($action) { |  | ||||||
|         $ip = Yii::$app->getRequest()->getUserIP(); |  | ||||||
|         if ($this->checkIp($ip) || $this->checkByHost($ip)) { |  | ||||||
|             return true; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         Yii::warning( |  | ||||||
|             'Access to ' . $action->controller->id . '::' . $action->id . |  | ||||||
|             ' is denied due to IP address restriction. The requesting IP address is ' . $ip, |  | ||||||
|             __METHOD__ |  | ||||||
|         ); |  | ||||||
|  |  | ||||||
|         throw new ForbiddenHttpException('You are not allowed to access this page.'); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     protected function checkIp(string $ip) : bool { |  | ||||||
|         foreach ($this->allowedIPs as $filter) { |  | ||||||
|             if ($filter === '*' |  | ||||||
|              || $filter === $ip |  | ||||||
|              || (($pos = strpos($filter, '*')) !== false && !strncmp($ip, $filter, $pos)) |  | ||||||
|             ) { |  | ||||||
|                 return true; |  | ||||||
|             } |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return false; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     protected function checkByHost(string $ip) : bool { |  | ||||||
|         foreach ($this->allowedHosts as $hostname) { |  | ||||||
|             $filter = gethostbyname($hostname); |  | ||||||
|             if ($filter === $ip) { |  | ||||||
|                 return true; |  | ||||||
|             } |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return false; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -1,67 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\models; |  | ||||||
|  |  | ||||||
| use common\models\Account; |  | ||||||
| use Emarref\Jwt\Claim\JwtId; |  | ||||||
| use Emarref\Jwt\Exception\ExpiredException; |  | ||||||
| use Yii; |  | ||||||
| use yii\base\NotSupportedException; |  | ||||||
| use yii\web\IdentityInterface; |  | ||||||
| use yii\web\UnauthorizedHttpException; |  | ||||||
|  |  | ||||||
| class AccountIdentity extends Account implements IdentityInterface { |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     public static function findIdentityByAccessToken($token, $type = null) { |  | ||||||
|         /** @var \api\components\User\Component $component */ |  | ||||||
|         $component = Yii::$app->user; |  | ||||||
|         try { |  | ||||||
|             $token = $component->parseToken($token); |  | ||||||
|         } catch (ExpiredException $e) { |  | ||||||
|             throw new UnauthorizedHttpException('Token expired'); |  | ||||||
|         } catch (\Exception $e) { |  | ||||||
|             throw new UnauthorizedHttpException('Incorrect token'); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         // Если исключение выше не случилось, то значит всё оке |  | ||||||
|         /** @var JwtId $jti */ |  | ||||||
|         $jti = $token->getPayload()->findClaimByName(JwtId::NAME); |  | ||||||
|         $account = static::findOne($jti->getValue()); |  | ||||||
|         if ($account === null) { |  | ||||||
|             throw new UnauthorizedHttpException('Invalid token'); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return $account; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     public function getId() { |  | ||||||
|         return $this->id; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     public static function findIdentity($id) { |  | ||||||
|         return static::findOne($id); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     public function getAuthKey() { |  | ||||||
|         throw new NotSupportedException('This method used for cookie auth, except we using JWT tokens'); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @inheritdoc |  | ||||||
|      */ |  | ||||||
|     public function validateAuthKey($authKey) { |  | ||||||
|         throw new NotSupportedException('This method used for cookie auth, except we using JWT tokens'); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
							
								
								
									
										28
									
								
								api/models/OauthAccountInfo.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								api/models/OauthAccountInfo.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,28 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\models; | ||||||
|  |  | ||||||
|  | use api\models\base\BaseAccountForm; | ||||||
|  | use api\modules\accounts\models\AccountInfo; | ||||||
|  | use common\models\Account; | ||||||
|  |  | ||||||
|  | class OauthAccountInfo extends BaseAccountForm { | ||||||
|  |  | ||||||
|  |     private $model; | ||||||
|  |  | ||||||
|  |     public function __construct(Account $account, array $config = []) { | ||||||
|  |         parent::__construct($account, $config); | ||||||
|  |         $this->model = new AccountInfo($account); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function info(): array { | ||||||
|  |         $response = $this->model->info(); | ||||||
|  |  | ||||||
|  |         $response['profileLink'] = $response['elyProfileLink']; | ||||||
|  |         unset($response['elyProfileLink']); | ||||||
|  |         $response['preferredLanguage'] = $response['lang']; | ||||||
|  |         unset($response['lang']); | ||||||
|  |  | ||||||
|  |         return $response; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -83,7 +83,7 @@ class OauthProcess { | |||||||
|         try { |         try { | ||||||
|             $grant = $this->getAuthorizationCodeGrant(); |             $grant = $this->getAuthorizationCodeGrant(); | ||||||
|             $authParams = $grant->checkAuthorizeParams(); |             $authParams = $grant->checkAuthorizeParams(); | ||||||
|             $account = Yii::$app->user->identity; |             $account = Yii::$app->user->identity->getAccount(); | ||||||
|             /** @var \common\models\OauthClient $clientModel */ |             /** @var \common\models\OauthClient $clientModel */ | ||||||
|             $clientModel = OauthClient::findOne($authParams->getClient()->getId()); |             $clientModel = OauthClient::findOne($authParams->getClient()->getId()); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,9 +1,8 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\models\authentication; | namespace api\models\authentication; | ||||||
|  |  | ||||||
| use api\models\AccountIdentity; |  | ||||||
| use api\models\base\ApiForm; | use api\models\base\ApiForm; | ||||||
| use api\models\profile\ChangeUsernameForm; | use api\modules\accounts\models\ChangeUsernameForm; | ||||||
| use api\validators\EmailActivationKeyValidator; | use api\validators\EmailActivationKeyValidator; | ||||||
| use common\models\Account; | use common\models\Account; | ||||||
| use common\models\EmailActivation; | use common\models\EmailActivation; | ||||||
| @@ -14,14 +13,14 @@ class ConfirmEmailForm extends ApiForm { | |||||||
|  |  | ||||||
|     public $key; |     public $key; | ||||||
|  |  | ||||||
|     public function rules() { |     public function rules(): array { | ||||||
|         return [ |         return [ | ||||||
|             ['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION], |             ['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION], | ||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * @return \api\components\User\LoginResult|bool |      * @return \api\components\User\AuthenticationResult|bool | ||||||
|      * @throws ErrorException |      * @throws ErrorException | ||||||
|      */ |      */ | ||||||
|     public function confirm() { |     public function confirm() { | ||||||
| @@ -48,7 +47,7 @@ class ConfirmEmailForm extends ApiForm { | |||||||
|  |  | ||||||
|         $transaction->commit(); |         $transaction->commit(); | ||||||
|  |  | ||||||
|         return Yii::$app->user->login(new AccountIdentity($account->attributes), true); |         return Yii::$app->user->createJwtAuthenticationToken($account, true); | ||||||
|     } |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -101,7 +101,7 @@ class ForgotPasswordForm extends ApiForm { | |||||||
|         return true; |         return true; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getLogin() { |     public function getLogin(): string { | ||||||
|         return $this->login; |         return $this->login; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,7 +1,6 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\models\authentication; | namespace api\models\authentication; | ||||||
|  |  | ||||||
| use api\models\AccountIdentity; |  | ||||||
| use api\models\base\ApiForm; | use api\models\base\ApiForm; | ||||||
| use api\validators\TotpValidator; | use api\validators\TotpValidator; | ||||||
| use common\helpers\Error as E; | use common\helpers\Error as E; | ||||||
| @@ -9,9 +8,6 @@ use api\traits\AccountFinder; | |||||||
| use common\models\Account; | use common\models\Account; | ||||||
| use Yii; | use Yii; | ||||||
|  |  | ||||||
| /** |  | ||||||
|  * @method AccountIdentity|null getAccount() |  | ||||||
|  */ |  | ||||||
| class LoginForm extends ApiForm { | class LoginForm extends ApiForm { | ||||||
|     use AccountFinder; |     use AccountFinder; | ||||||
|  |  | ||||||
| @@ -86,12 +82,12 @@ class LoginForm extends ApiForm { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getLogin() { |     public function getLogin(): string { | ||||||
|         return $this->login; |         return $this->login; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * @return \api\components\User\LoginResult|bool |      * @return \api\components\User\AuthenticationResult|bool | ||||||
|      */ |      */ | ||||||
|     public function login() { |     public function login() { | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
| @@ -104,11 +100,7 @@ class LoginForm extends ApiForm { | |||||||
|             $account->save(); |             $account->save(); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         return Yii::$app->user->login($account, $this->rememberMe); |         return Yii::$app->user->createJwtAuthenticationToken($account, $this->rememberMe); | ||||||
|     } |  | ||||||
|  |  | ||||||
|     protected function getAccountClassName() { |  | ||||||
|         return AccountIdentity::class; |  | ||||||
|     } |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,7 +1,6 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\models\authentication; | namespace api\models\authentication; | ||||||
|  |  | ||||||
| use api\models\AccountIdentity; |  | ||||||
| use api\models\base\ApiForm; | use api\models\base\ApiForm; | ||||||
| use api\validators\EmailActivationKeyValidator; | use api\validators\EmailActivationKeyValidator; | ||||||
| use common\helpers\Error as E; | use common\helpers\Error as E; | ||||||
| @@ -37,7 +36,7 @@ class RecoverPasswordForm extends ApiForm { | |||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * @return \api\components\User\LoginResult|bool |      * @return \api\components\User\AuthenticationResult|bool | ||||||
|      * @throws ErrorException |      * @throws ErrorException | ||||||
|      */ |      */ | ||||||
|     public function recoverPassword() { |     public function recoverPassword() { | ||||||
| @@ -61,7 +60,7 @@ class RecoverPasswordForm extends ApiForm { | |||||||
|  |  | ||||||
|         $transaction->commit(); |         $transaction->commit(); | ||||||
|  |  | ||||||
|         return Yii::$app->user->login(new AccountIdentity($account->attributes), false); |         return Yii::$app->user->createJwtAuthenticationToken($account, false); | ||||||
|     } |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -32,7 +32,7 @@ class RefreshTokenForm extends ApiForm { | |||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * @return \api\components\User\RenewResult|bool |      * @return \api\components\User\AuthenticationResult|bool | ||||||
|      */ |      */ | ||||||
|     public function renew() { |     public function renew() { | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
| @@ -42,7 +42,7 @@ class RefreshTokenForm extends ApiForm { | |||||||
|         /** @var \api\components\User\Component $component */ |         /** @var \api\components\User\Component $component */ | ||||||
|         $component = Yii::$app->user; |         $component = Yii::$app->user; | ||||||
|  |  | ||||||
|         return $component->renew($this->getSession()); |         return $component->renewJwtAuthenticationToken($this->getSession()); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|   | |||||||
							
								
								
									
										22
									
								
								api/models/base/BaseAccountForm.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										22
									
								
								api/models/base/BaseAccountForm.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,22 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\models\base; | ||||||
|  |  | ||||||
|  | use common\models\Account; | ||||||
|  |  | ||||||
|  | class BaseAccountForm extends ApiForm { | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @var Account | ||||||
|  |      */ | ||||||
|  |     private $account; | ||||||
|  |  | ||||||
|  |     public function __construct(Account $account, array $config = []) { | ||||||
|  |         parent::__construct($config); | ||||||
|  |         $this->account = $account; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getAccount(): Account { | ||||||
|  |         return $this->account; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -1,35 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\models\profile; |  | ||||||
|  |  | ||||||
| use api\models\base\ApiForm; |  | ||||||
| use common\models\Account; |  | ||||||
| use yii\base\ErrorException; |  | ||||||
| use const \common\LATEST_RULES_VERSION; |  | ||||||
|  |  | ||||||
| class AcceptRulesForm extends ApiForm { |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @var Account |  | ||||||
|      */ |  | ||||||
|     private $account; |  | ||||||
|  |  | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         $this->account = $account; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function agreeWithLatestRules() : bool { |  | ||||||
|         $account = $this->getAccount(); |  | ||||||
|         $account->rules_agreement_version = LATEST_RULES_VERSION; |  | ||||||
|         if (!$account->save()) { |  | ||||||
|             throw new ErrorException('Cannot set user rules version'); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return true; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getAccount() : Account { |  | ||||||
|         return $this->account; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -1,45 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\models\profile; |  | ||||||
|  |  | ||||||
| use api\models\base\ApiForm; |  | ||||||
| use common\models\Account; |  | ||||||
| use common\validators\LanguageValidator; |  | ||||||
| use yii\base\ErrorException; |  | ||||||
|  |  | ||||||
| class ChangeLanguageForm extends ApiForm { |  | ||||||
|  |  | ||||||
|     public $lang; |  | ||||||
|  |  | ||||||
|     private $account; |  | ||||||
|  |  | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         $this->account = $account; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function rules() { |  | ||||||
|         return [ |  | ||||||
|             ['lang', 'required'], |  | ||||||
|             ['lang', LanguageValidator::class], |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function applyLanguage() : bool { |  | ||||||
|         if (!$this->validate()) { |  | ||||||
|             return false; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         $account = $this->getAccount(); |  | ||||||
|         $account->lang = $this->lang; |  | ||||||
|         if (!$account->save()) { |  | ||||||
|             throw new ErrorException('Cannot change user language'); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return true; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getAccount() : Account { |  | ||||||
|         return $this->account; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
| @@ -1,181 +0,0 @@ | |||||||
| <?php |  | ||||||
| namespace api\models\profile; |  | ||||||
|  |  | ||||||
| use api\models\base\ApiForm; |  | ||||||
| use api\validators\TotpValidator; |  | ||||||
| use api\validators\PasswordRequiredValidator; |  | ||||||
| use BaconQrCode\Common\ErrorCorrectionLevel; |  | ||||||
| use BaconQrCode\Encoder\Encoder; |  | ||||||
| use BaconQrCode\Renderer\Color\Rgb; |  | ||||||
| use BaconQrCode\Renderer\Image\Svg; |  | ||||||
| use BaconQrCode\Writer; |  | ||||||
| use common\components\Qr\ElyDecorator; |  | ||||||
| use common\helpers\Error as E; |  | ||||||
| use common\models\Account; |  | ||||||
| use OTPHP\TOTP; |  | ||||||
| use ParagonIE\ConstantTime\Encoding; |  | ||||||
| use Yii; |  | ||||||
| use yii\base\ErrorException; |  | ||||||
|  |  | ||||||
| class TwoFactorAuthForm extends ApiForm { |  | ||||||
|  |  | ||||||
|     const SCENARIO_ACTIVATE = 'enable'; |  | ||||||
|     const SCENARIO_DISABLE = 'disable'; |  | ||||||
|  |  | ||||||
|     public $totp; |  | ||||||
|  |  | ||||||
|     public $timestamp; |  | ||||||
|  |  | ||||||
|     public $password; |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @var Account |  | ||||||
|      */ |  | ||||||
|     private $account; |  | ||||||
|  |  | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         $this->account = $account; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function rules(): array { |  | ||||||
|         $bothScenarios = [self::SCENARIO_ACTIVATE, self::SCENARIO_DISABLE]; |  | ||||||
|         return [ |  | ||||||
|             ['timestamp', 'integer', 'on' => [self::SCENARIO_ACTIVATE]], |  | ||||||
|             ['account', 'validateOtpDisabled', 'on' => self::SCENARIO_ACTIVATE], |  | ||||||
|             ['account', 'validateOtpEnabled', 'on' => self::SCENARIO_DISABLE], |  | ||||||
|             ['totp', 'required', 'message' => E::TOTP_REQUIRED, 'on' => $bothScenarios], |  | ||||||
|             ['totp', TotpValidator::class, 'on' => $bothScenarios, |  | ||||||
|                 'account' => $this->account, |  | ||||||
|                 'timestamp' => function() { |  | ||||||
|                     return $this->timestamp; |  | ||||||
|                 }, |  | ||||||
|             ], |  | ||||||
|             ['password', PasswordRequiredValidator::class, 'account' => $this->account, 'on' => $bothScenarios], |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getCredentials(): array { |  | ||||||
|         if (empty($this->account->otp_secret)) { |  | ||||||
|             $this->setOtpSecret(); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         $provisioningUri = $this->getTotp()->getProvisioningUri(); |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'qr' => 'data:image/svg+xml,' . trim($this->drawQrCode($provisioningUri)), |  | ||||||
|             'uri' => $provisioningUri, |  | ||||||
|             'secret' => $this->account->otp_secret, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function activate(): bool { |  | ||||||
|         if ($this->scenario !== self::SCENARIO_ACTIVATE || !$this->validate()) { |  | ||||||
|             return false; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         $transaction = Yii::$app->db->beginTransaction(); |  | ||||||
|  |  | ||||||
|         $account = $this->account; |  | ||||||
|         $account->is_otp_enabled = true; |  | ||||||
|         if (!$account->save()) { |  | ||||||
|             throw new ErrorException('Cannot enable otp for account'); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         Yii::$app->user->terminateSessions(); |  | ||||||
|  |  | ||||||
|         $transaction->commit(); |  | ||||||
|  |  | ||||||
|         return true; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function disable(): bool { |  | ||||||
|         if ($this->scenario !== self::SCENARIO_DISABLE || !$this->validate()) { |  | ||||||
|             return false; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         $account = $this->account; |  | ||||||
|         $account->is_otp_enabled = false; |  | ||||||
|         $account->otp_secret = null; |  | ||||||
|         if (!$account->save()) { |  | ||||||
|             throw new ErrorException('Cannot disable otp for account'); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return true; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function validateOtpDisabled($attribute) { |  | ||||||
|         if ($this->account->is_otp_enabled) { |  | ||||||
|             $this->addError($attribute, E::OTP_ALREADY_ENABLED); |  | ||||||
|         } |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function validateOtpEnabled($attribute) { |  | ||||||
|         if (!$this->account->is_otp_enabled) { |  | ||||||
|             $this->addError($attribute, E::OTP_NOT_ENABLED); |  | ||||||
|         } |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function getAccount(): Account { |  | ||||||
|         return $this->account; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @return TOTP |  | ||||||
|      */ |  | ||||||
|     public function getTotp(): TOTP { |  | ||||||
|         $totp = TOTP::create($this->account->otp_secret); |  | ||||||
|         $totp->setLabel($this->account->email); |  | ||||||
|         $totp->setIssuer('Ely.by'); |  | ||||||
|  |  | ||||||
|         return $totp; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function drawQrCode(string $content): string { |  | ||||||
|         $content = $this->forceMinimalQrContentLength($content); |  | ||||||
|  |  | ||||||
|         $renderer = new Svg(); |  | ||||||
|         $renderer->setMargin(0); |  | ||||||
|         $renderer->setForegroundColor(new Rgb(32, 126, 92)); |  | ||||||
|         $renderer->addDecorator(new ElyDecorator()); |  | ||||||
|  |  | ||||||
|         $writer = new Writer($renderer); |  | ||||||
|  |  | ||||||
|         return $writer->writeString($content, Encoder::DEFAULT_BYTE_MODE_ECODING, ErrorCorrectionLevel::H); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * otp_secret кодируется в Base32, т.к. после кодирования в результурющей строке нет символов, |  | ||||||
|      * которые можно перепутать (1 и l, O и 0, и т.д.). Отрицательной стороной является то, что итоговая |  | ||||||
|      * строка составляет 160% от исходной. Поэтому, генерируя исходный приватный ключ, мы должны обеспечить |  | ||||||
|      * ему такую длину, чтобы 160% его длины было равно запрошенному значению |  | ||||||
|      * |  | ||||||
|      * @param int $length |  | ||||||
|      * @throws ErrorException |  | ||||||
|      */ |  | ||||||
|     protected function setOtpSecret(int $length = 24): void { |  | ||||||
|         $randomBytesLength = ceil($length / 1.6); |  | ||||||
|         $randomBase32 = trim(Encoding::base32EncodeUpper(random_bytes($randomBytesLength)), '='); |  | ||||||
|         $this->account->otp_secret = substr($randomBase32, 0, $length); |  | ||||||
|         if (!$this->account->save()) { |  | ||||||
|             throw new ErrorException('Cannot set account otp_secret'); |  | ||||||
|         } |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * В используемой либе для рендеринга QR кода нет возможности указать QR code version. |  | ||||||
|      * http://www.qrcode.com/en/about/version.html |  | ||||||
|      * По какой-то причине 7 и 8 версии не читаются вовсе, с логотипом или без. |  | ||||||
|      * Поэтому нужно иначально привести строку к длинне 9 версии (91), добавляя к концу |  | ||||||
|      * строки необходимое количество символов "#". Этот символ используется, т.к. нашим |  | ||||||
|      * контентом является ссылка и чтобы не вводить лишние параметры мы помечаем добавочную |  | ||||||
|      * часть как хеш часть и все программы для чтения QR кодов продолжают свою работу. |  | ||||||
|      * |  | ||||||
|      * @param string $content |  | ||||||
|      * @return string |  | ||||||
|      */ |  | ||||||
|     private function forceMinimalQrContentLength(string $content): string { |  | ||||||
|         return str_pad($content, 91, '#'); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
|   | |||||||
							
								
								
									
										10
									
								
								api/modules/accounts/Module.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								api/modules/accounts/Module.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,10 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts; | ||||||
|  |  | ||||||
|  | use yii\base\Module as BaseModule; | ||||||
|  |  | ||||||
|  | class Module extends BaseModule { | ||||||
|  |  | ||||||
|  |     public $id = 'accounts'; | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/AcceptRulesAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/AcceptRulesAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\AcceptRulesForm; | ||||||
|  |  | ||||||
|  | class AcceptRulesAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return AcceptRulesForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/BanAccountAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/BanAccountAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\BanAccountForm; | ||||||
|  |  | ||||||
|  | class BanAccountAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return BanAccountForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										73
									
								
								api/modules/accounts/actions/BaseAccountAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										73
									
								
								api/modules/accounts/actions/BaseAccountAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,73 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\AccountActionForm; | ||||||
|  | use common\models\Account; | ||||||
|  | use Yii; | ||||||
|  | use yii\base\Action; | ||||||
|  | use yii\web\NotFoundHttpException; | ||||||
|  |  | ||||||
|  | abstract class BaseAccountAction extends Action { | ||||||
|  |  | ||||||
|  |     final public function run(int $id): array { | ||||||
|  |         $className = $this->getFormClassName(); | ||||||
|  |         /** @var AccountActionForm $model */ | ||||||
|  |         $model = new $className($this->findAccount($id)); | ||||||
|  |         $model->load($this->getRequestData()); | ||||||
|  |         if (!$model->performAction()) { | ||||||
|  |             return $this->formatFailedResult($model); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $this->formatSuccessResult($model); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     abstract protected function getFormClassName(): string; | ||||||
|  |  | ||||||
|  |     public function getRequestData(): array { | ||||||
|  |         return Yii::$app->request->post(); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getSuccessResultData(AccountActionForm $model): array { | ||||||
|  |         return []; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function getFailedResultData(AccountActionForm $model): array { | ||||||
|  |         return []; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     private function formatFailedResult(AccountActionForm $model): array { | ||||||
|  |         $response = [ | ||||||
|  |             'success' => false, | ||||||
|  |             'errors' => $model->getFirstErrors(), | ||||||
|  |         ]; | ||||||
|  |  | ||||||
|  |         $data = $this->getFailedResultData($model); | ||||||
|  |         if (!empty($data)) { | ||||||
|  |             $response['data'] = $data; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $response; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     private function formatSuccessResult(AccountActionForm $model): array { | ||||||
|  |         $response = [ | ||||||
|  |             'success' => true, | ||||||
|  |         ]; | ||||||
|  |         $data = $this->getSuccessResultData($model); | ||||||
|  |         if (!empty($data)) { | ||||||
|  |             $response['data'] = $data; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $response; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     private function findAccount(int $id): Account { | ||||||
|  |         $account = Account::findOne($id); | ||||||
|  |         if ($account === null) { | ||||||
|  |             throw new NotFoundHttpException(); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $account; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										23
									
								
								api/modules/accounts/actions/ChangeEmailAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										23
									
								
								api/modules/accounts/actions/ChangeEmailAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,23 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\AccountActionForm; | ||||||
|  | use api\modules\accounts\models\ChangeEmailForm; | ||||||
|  |  | ||||||
|  | class ChangeEmailAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return ChangeEmailForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @param ChangeEmailForm|AccountActionForm $model | ||||||
|  |      * @return array | ||||||
|  |      */ | ||||||
|  |     public function getSuccessResultData(AccountActionForm $model): array { | ||||||
|  |         return [ | ||||||
|  |             'email' => $model->getAccount()->email, | ||||||
|  |         ]; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/ChangeLanguageAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/ChangeLanguageAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\ChangeLanguageForm; | ||||||
|  |  | ||||||
|  | class ChangeLanguageAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return ChangeLanguageForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/ChangePasswordAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/ChangePasswordAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\ChangePasswordForm; | ||||||
|  |  | ||||||
|  | class ChangePasswordAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return ChangePasswordForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/ChangeUsernameAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/ChangeUsernameAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\ChangeUsernameForm; | ||||||
|  |  | ||||||
|  | class ChangeUsernameAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return ChangeUsernameForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/DisableTwoFactorAuthAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/DisableTwoFactorAuthAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\DisableTwoFactorAuthForm; | ||||||
|  |  | ||||||
|  | class DisableTwoFactorAuthAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return DisableTwoFactorAuthForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										32
									
								
								api/modules/accounts/actions/EmailVerificationAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										32
									
								
								api/modules/accounts/actions/EmailVerificationAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,32 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\AccountActionForm; | ||||||
|  | use api\modules\accounts\models\SendEmailVerificationForm; | ||||||
|  | use common\helpers\Error as E; | ||||||
|  |  | ||||||
|  | class EmailVerificationAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return SendEmailVerificationForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @param SendEmailVerificationForm|AccountActionForm $model | ||||||
|  |      * @return array | ||||||
|  |      */ | ||||||
|  |     public function getFailedResultData(AccountActionForm $model): array { | ||||||
|  |         $emailError = $model->getFirstError('email'); | ||||||
|  |         if ($emailError !== E::RECENTLY_SENT_MESSAGE) { | ||||||
|  |             return []; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         $emailActivation = $model->getEmailActivation(); | ||||||
|  |  | ||||||
|  |         return [ | ||||||
|  |             'canRepeatIn' => $emailActivation->canRepeatIn(), | ||||||
|  |             'repeatFrequency' => $emailActivation->repeatTimeout, | ||||||
|  |         ]; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/EnableTwoFactorAuthAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/EnableTwoFactorAuthAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\EnableTwoFactorAuthForm; | ||||||
|  |  | ||||||
|  | class EnableTwoFactorAuthAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return EnableTwoFactorAuthForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/NewEmailVerificationAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/NewEmailVerificationAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\SendNewEmailVerificationForm; | ||||||
|  |  | ||||||
|  | class NewEmailVerificationAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return SendNewEmailVerificationForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										12
									
								
								api/modules/accounts/actions/PardonAccountAction.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								api/modules/accounts/actions/PardonAccountAction.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\actions; | ||||||
|  |  | ||||||
|  | use api\modules\accounts\models\PardonAccountForm; | ||||||
|  |  | ||||||
|  | class PardonAccountAction extends BaseAccountAction { | ||||||
|  |  | ||||||
|  |     protected function getFormClassName(): string { | ||||||
|  |         return PardonAccountForm::class; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										133
									
								
								api/modules/accounts/controllers/DefaultController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										133
									
								
								api/modules/accounts/controllers/DefaultController.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,133 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\controllers; | ||||||
|  |  | ||||||
|  | use api\controllers\Controller; | ||||||
|  | use api\modules\accounts\actions; | ||||||
|  | use api\modules\accounts\models\AccountInfo; | ||||||
|  | use api\modules\accounts\models\TwoFactorAuthInfo; | ||||||
|  | use common\models\Account; | ||||||
|  | use common\rbac\Permissions as P; | ||||||
|  | use Yii; | ||||||
|  | use yii\filters\AccessControl; | ||||||
|  | use yii\helpers\ArrayHelper; | ||||||
|  | use yii\web\NotFoundHttpException; | ||||||
|  |  | ||||||
|  | class DefaultController extends Controller { | ||||||
|  |  | ||||||
|  |     public function behaviors(): array { | ||||||
|  |         $paramsCallback = function() { | ||||||
|  |             return [ | ||||||
|  |                 'accountId' => Yii::$app->request->get('id'), | ||||||
|  |             ]; | ||||||
|  |         }; | ||||||
|  |  | ||||||
|  |         return ArrayHelper::merge(Controller::behaviors(), [ | ||||||
|  |             'access' => [ | ||||||
|  |                 'class' => AccessControl::class, | ||||||
|  |                 'rules' => [ | ||||||
|  |                     [ | ||||||
|  |                         'allow' => true, | ||||||
|  |                         'actions' => ['get'], | ||||||
|  |                         'roles' => [P::OBTAIN_ACCOUNT_INFO], | ||||||
|  |                         'roleParams' => function() use ($paramsCallback) { | ||||||
|  |                             return array_merge($paramsCallback(), [ | ||||||
|  |                                 'optionalRules' => true, | ||||||
|  |                             ]); | ||||||
|  |                         }, | ||||||
|  |                     ], | ||||||
|  |                     [ | ||||||
|  |                         'allow' => true, | ||||||
|  |                         'actions' => ['username'], | ||||||
|  |                         'roles' => [P::CHANGE_ACCOUNT_USERNAME], | ||||||
|  |                         'roleParams' => $paramsCallback, | ||||||
|  |                     ], | ||||||
|  |                     [ | ||||||
|  |                         'allow' => true, | ||||||
|  |                         'actions' => ['password'], | ||||||
|  |                         'roles' => [P::CHANGE_ACCOUNT_PASSWORD], | ||||||
|  |                         'roleParams' => $paramsCallback, | ||||||
|  |                     ], | ||||||
|  |                     [ | ||||||
|  |                         'allow' => true, | ||||||
|  |                         'actions' => ['language'], | ||||||
|  |                         'roles' => [P::CHANGE_ACCOUNT_LANGUAGE], | ||||||
|  |                         'roleParams' => $paramsCallback, | ||||||
|  |                     ], | ||||||
|  |                     [ | ||||||
|  |                         'allow' => true, | ||||||
|  |                         'actions' => [ | ||||||
|  |                             'email', | ||||||
|  |                             'email-verification', | ||||||
|  |                             'new-email-verification', | ||||||
|  |                         ], | ||||||
|  |                         'roles' => [P::CHANGE_ACCOUNT_EMAIL], | ||||||
|  |                         'roleParams' => $paramsCallback, | ||||||
|  |                     ], | ||||||
|  |                     [ | ||||||
|  |                         'allow' => true, | ||||||
|  |                         'actions' => ['rules'], | ||||||
|  |                         'roles' => [P::ACCEPT_NEW_PROJECT_RULES], | ||||||
|  |                         'roleParams' => function() use ($paramsCallback) { | ||||||
|  |                             return array_merge($paramsCallback(), [ | ||||||
|  |                                 'optionalRules' => true, | ||||||
|  |                             ]); | ||||||
|  |                         }, | ||||||
|  |                     ], | ||||||
|  |                     [ | ||||||
|  |                         'allow' => true, | ||||||
|  |                         'actions' => [ | ||||||
|  |                             'get-two-factor-auth-credentials', | ||||||
|  |                             'enable-two-factor-auth', | ||||||
|  |                             'disable-two-factor-auth', | ||||||
|  |                         ], | ||||||
|  |                         'roles' => [P::MANAGE_TWO_FACTOR_AUTH], | ||||||
|  |                         'roleParams' => $paramsCallback, | ||||||
|  |                     ], | ||||||
|  |                     [ | ||||||
|  |                         'allow' => true, | ||||||
|  |                         'actions' => [ | ||||||
|  |                             'ban', | ||||||
|  |                             'pardon', | ||||||
|  |                         ], | ||||||
|  |                         'roles' => [P::BLOCK_ACCOUNT], | ||||||
|  |                         'roleParams' => $paramsCallback, | ||||||
|  |                     ], | ||||||
|  |                 ], | ||||||
|  |             ], | ||||||
|  |         ]); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function actions(): array { | ||||||
|  |         return [ | ||||||
|  |             'username' => actions\ChangeUsernameAction::class, | ||||||
|  |             'password' => actions\ChangePasswordAction::class, | ||||||
|  |             'language' => actions\ChangeLanguageAction::class, | ||||||
|  |             'email' => actions\ChangeEmailAction::class, | ||||||
|  |             'email-verification' => actions\EmailVerificationAction::class, | ||||||
|  |             'new-email-verification' => actions\NewEmailVerificationAction::class, | ||||||
|  |             'rules' => actions\AcceptRulesAction::class, | ||||||
|  |             'enable-two-factor-auth' => actions\EnableTwoFactorAuthAction::class, | ||||||
|  |             'disable-two-factor-auth' => actions\DisableTwoFactorAuthAction::class, | ||||||
|  |             'ban' => actions\BanAccountAction::class, | ||||||
|  |             'pardon' => actions\PardonAccountAction::class, | ||||||
|  |         ]; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function actionGet(int $id): array { | ||||||
|  |         return (new AccountInfo($this->findAccount($id)))->info(); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function actionGetTwoFactorAuthCredentials(int $id): array { | ||||||
|  |         return (new TwoFactorAuthInfo($this->findAccount($id)))->getCredentials(); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     private function findAccount(int $id): Account { | ||||||
|  |         $account = Account::findOne($id); | ||||||
|  |         if ($account === null) { | ||||||
|  |             throw new NotFoundHttpException(); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $account; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										19
									
								
								api/modules/accounts/models/AcceptRulesForm.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								api/modules/accounts/models/AcceptRulesForm.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,19 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\models; | ||||||
|  |  | ||||||
|  | use yii\base\ErrorException; | ||||||
|  | use const \common\LATEST_RULES_VERSION; | ||||||
|  |  | ||||||
|  | class AcceptRulesForm extends AccountActionForm { | ||||||
|  |  | ||||||
|  |     public function performAction(): bool { | ||||||
|  |         $account = $this->getAccount(); | ||||||
|  |         $account->rules_agreement_version = LATEST_RULES_VERSION; | ||||||
|  |         if (!$account->save()) { | ||||||
|  |             throw new ErrorException('Cannot set user rules version'); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return true; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										10
									
								
								api/modules/accounts/models/AccountActionForm.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								api/modules/accounts/models/AccountActionForm.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,10 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\models; | ||||||
|  |  | ||||||
|  | use api\models\base\BaseAccountForm; | ||||||
|  |  | ||||||
|  | abstract class AccountActionForm extends BaseAccountForm { | ||||||
|  |  | ||||||
|  |     abstract public function performAction(): bool; | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										54
									
								
								api/modules/accounts/models/AccountInfo.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										54
									
								
								api/modules/accounts/models/AccountInfo.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,54 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\models; | ||||||
|  |  | ||||||
|  | use api\models\base\BaseAccountForm; | ||||||
|  | use common\models\Account; | ||||||
|  | use common\rbac\Permissions as P; | ||||||
|  | use yii\di\Instance; | ||||||
|  | use yii\web\User; | ||||||
|  |  | ||||||
|  | class AccountInfo extends BaseAccountForm { | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * @var User|string | ||||||
|  |      */ | ||||||
|  |     public $user = 'user'; | ||||||
|  |  | ||||||
|  |     public function init() { | ||||||
|  |         parent::init(); | ||||||
|  |         $this->user = Instance::ensure($this->user, User::class); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function info(): array { | ||||||
|  |         $account = $this->getAccount(); | ||||||
|  |  | ||||||
|  |         $response = [ | ||||||
|  |             'id' => $account->id, | ||||||
|  |             'uuid' => $account->uuid, | ||||||
|  |             'username' => $account->username, | ||||||
|  |             'isOtpEnabled' => (bool)$account->is_otp_enabled, | ||||||
|  |             'registeredAt' => $account->created_at, | ||||||
|  |             'lang' => $account->lang, | ||||||
|  |             'elyProfileLink' => $account->getProfileLink(), | ||||||
|  |         ]; | ||||||
|  |  | ||||||
|  |         $authManagerParams = [ | ||||||
|  |             'accountId' => $account->id, | ||||||
|  |             'optionalRules' => true, | ||||||
|  |         ]; | ||||||
|  |  | ||||||
|  |         if ($this->user->can(P::OBTAIN_ACCOUNT_EMAIL, $authManagerParams)) { | ||||||
|  |             $response['email'] = $account->email; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         if ($this->user->can(P::OBTAIN_EXTENDED_ACCOUNT_INFO, $authManagerParams)) { | ||||||
|  |             $response['isActive'] = $account->status === Account::STATUS_ACTIVE; | ||||||
|  |             $response['passwordChangedAt'] = $account->password_changed_at; | ||||||
|  |             $response['hasMojangUsernameCollision'] = $account->hasMojangUsernameCollision(); | ||||||
|  |             $response['shouldAcceptRules'] = !$account->isAgreedWithActualRules(); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return $response; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -1,7 +1,6 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\modules\internal\models; | namespace api\modules\accounts\models; | ||||||
| 
 | 
 | ||||||
| use api\models\base\ApiForm; |  | ||||||
| use api\modules\internal\helpers\Error as E; | use api\modules\internal\helpers\Error as E; | ||||||
| use common\helpers\Amqp; | use common\helpers\Amqp; | ||||||
| use common\models\Account; | use common\models\Account; | ||||||
| @@ -10,7 +9,7 @@ use PhpAmqpLib\Message\AMQPMessage; | |||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; | use yii\base\ErrorException; | ||||||
| 
 | 
 | ||||||
| class BanForm extends ApiForm { | class BanAccountForm extends AccountActionForm { | ||||||
| 
 | 
 | ||||||
|     public const DURATION_FOREVER = -1; |     public const DURATION_FOREVER = -1; | ||||||
| 
 | 
 | ||||||
| @@ -31,11 +30,6 @@ class BanForm extends ApiForm { | |||||||
|      */ |      */ | ||||||
|     public $message = ''; |     public $message = ''; | ||||||
| 
 | 
 | ||||||
|     /** |  | ||||||
|      * @var Account |  | ||||||
|      */ |  | ||||||
|     private $account; |  | ||||||
| 
 |  | ||||||
|     public function rules(): array { |     public function rules(): array { | ||||||
|         return [ |         return [ | ||||||
|             [['duration'], 'integer', 'min' => self::DURATION_FOREVER], |             [['duration'], 'integer', 'min' => self::DURATION_FOREVER], | ||||||
| @@ -44,24 +38,20 @@ class BanForm extends ApiForm { | |||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function getAccount(): Account { |  | ||||||
|         return $this->account; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function validateAccountActivity() { |     public function validateAccountActivity() { | ||||||
|         if ($this->account->status === Account::STATUS_BANNED) { |         if ($this->getAccount()->status === Account::STATUS_BANNED) { | ||||||
|             $this->addError('account', E::ACCOUNT_ALREADY_BANNED); |             $this->addError('account', E::ACCOUNT_ALREADY_BANNED); | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function ban(): bool { |     public function performAction(): bool { | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
|             return false; |             return false; | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         $transaction = Yii::$app->db->beginTransaction(); |         $transaction = Yii::$app->db->beginTransaction(); | ||||||
| 
 | 
 | ||||||
|         $account = $this->account; |         $account = $this->getAccount(); | ||||||
|         $account->status = Account::STATUS_BANNED; |         $account->status = Account::STATUS_BANNED; | ||||||
|         if (!$account->save()) { |         if (!$account->save()) { | ||||||
|             throw new ErrorException('Cannot ban account'); |             throw new ErrorException('Cannot ban account'); | ||||||
| @@ -76,7 +66,7 @@ class BanForm extends ApiForm { | |||||||
| 
 | 
 | ||||||
|     public function createTask(): void { |     public function createTask(): void { | ||||||
|         $model = new AccountBanned(); |         $model = new AccountBanned(); | ||||||
|         $model->accountId = $this->account->id; |         $model->accountId = $this->getAccount()->id; | ||||||
|         $model->duration = $this->duration; |         $model->duration = $this->duration; | ||||||
|         $model->message = $this->message; |         $model->message = $this->message; | ||||||
| 
 | 
 | ||||||
| @@ -87,9 +77,4 @@ class BanForm extends ApiForm { | |||||||
|         Amqp::sendToEventsExchange('accounts.account-banned', $message); |         Amqp::sendToEventsExchange('accounts.account-banned', $message); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         $this->account = $account; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
| } | } | ||||||
| @@ -1,39 +1,25 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\models\profile\ChangeEmail; | namespace api\modules\accounts\models; | ||||||
| 
 | 
 | ||||||
| use api\models\base\ApiForm; |  | ||||||
| use api\validators\EmailActivationKeyValidator; | use api\validators\EmailActivationKeyValidator; | ||||||
| use common\helpers\Amqp; | use common\helpers\Amqp; | ||||||
| use common\models\Account; |  | ||||||
| use common\models\amqp\EmailChanged; | use common\models\amqp\EmailChanged; | ||||||
| use common\models\EmailActivation; | use common\models\EmailActivation; | ||||||
| use PhpAmqpLib\Message\AMQPMessage; | use PhpAmqpLib\Message\AMQPMessage; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; | use yii\base\ErrorException; | ||||||
| 
 | 
 | ||||||
| class ConfirmNewEmailForm extends ApiForm { | class ChangeEmailForm extends AccountActionForm { | ||||||
| 
 | 
 | ||||||
|     public $key; |     public $key; | ||||||
| 
 | 
 | ||||||
|     /** |     public function rules(): array { | ||||||
|      * @var Account |  | ||||||
|      */ |  | ||||||
|     private $account; |  | ||||||
| 
 |  | ||||||
|     public function rules() { |  | ||||||
|         return [ |         return [ | ||||||
|             ['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION], |             ['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION], | ||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     /** |     public function performAction(): bool { | ||||||
|      * @return Account |  | ||||||
|      */ |  | ||||||
|     public function getAccount(): Account { |  | ||||||
|         return $this->account; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function changeEmail(): bool { |  | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
|             return false; |             return false; | ||||||
|         } |         } | ||||||
| @@ -58,13 +44,7 @@ class ConfirmNewEmailForm extends ApiForm { | |||||||
|         return true; |         return true; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     /** |     public function createTask(int $accountId, string $newEmail, string $oldEmail): void { | ||||||
|      * @param integer $accountId |  | ||||||
|      * @param string  $newEmail |  | ||||||
|      * @param string  $oldEmail |  | ||||||
|      * @throws \PhpAmqpLib\Exception\AMQPExceptionInterface |  | ||||||
|      */ |  | ||||||
|     public function createTask($accountId, $newEmail, $oldEmail) { |  | ||||||
|         $model = new EmailChanged; |         $model = new EmailChanged; | ||||||
|         $model->accountId = $accountId; |         $model->accountId = $accountId; | ||||||
|         $model->oldEmail = $oldEmail; |         $model->oldEmail = $oldEmail; | ||||||
| @@ -77,9 +57,4 @@ class ConfirmNewEmailForm extends ApiForm { | |||||||
|         Amqp::sendToEventsExchange('accounts.email-changed', $message); |         Amqp::sendToEventsExchange('accounts.email-changed', $message); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         $this->account = $account; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
| } | } | ||||||
							
								
								
									
										32
									
								
								api/modules/accounts/models/ChangeLanguageForm.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										32
									
								
								api/modules/accounts/models/ChangeLanguageForm.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,32 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\models; | ||||||
|  |  | ||||||
|  | use api\exceptions\ThisShouldNotHappenException; | ||||||
|  | use common\validators\LanguageValidator; | ||||||
|  |  | ||||||
|  | class ChangeLanguageForm extends AccountActionForm { | ||||||
|  |  | ||||||
|  |     public $lang; | ||||||
|  |  | ||||||
|  |     public function rules(): array { | ||||||
|  |         return [ | ||||||
|  |             ['lang', 'required'], | ||||||
|  |             ['lang', LanguageValidator::class], | ||||||
|  |         ]; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function performAction(): bool { | ||||||
|  |         if (!$this->validate()) { | ||||||
|  |             return false; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         $account = $this->getAccount(); | ||||||
|  |         $account->lang = $this->lang; | ||||||
|  |         if (!$account->save()) { | ||||||
|  |             throw new ThisShouldNotHappenException('Cannot change user language'); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return true; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -1,16 +1,15 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\models\profile; | namespace api\modules\accounts\models; | ||||||
| 
 | 
 | ||||||
| use api\models\base\ApiForm; | use api\components\User\Component; | ||||||
|  | use api\exceptions\ThisShouldNotHappenException; | ||||||
| use api\validators\PasswordRequiredValidator; | use api\validators\PasswordRequiredValidator; | ||||||
| use common\helpers\Error as E; | use common\helpers\Error as E; | ||||||
| use common\models\Account; |  | ||||||
| use common\validators\PasswordValidator; | use common\validators\PasswordValidator; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; |  | ||||||
| use yii\helpers\ArrayHelper; | use yii\helpers\ArrayHelper; | ||||||
| 
 | 
 | ||||||
| class ChangePasswordForm extends ApiForm { | class ChangePasswordForm extends AccountActionForm { | ||||||
| 
 | 
 | ||||||
|     public $newPassword; |     public $newPassword; | ||||||
| 
 | 
 | ||||||
| @@ -20,31 +19,23 @@ class ChangePasswordForm extends ApiForm { | |||||||
| 
 | 
 | ||||||
|     public $password; |     public $password; | ||||||
| 
 | 
 | ||||||
|     /** |  | ||||||
|      * @var \common\models\Account |  | ||||||
|      */ |  | ||||||
|     private $_account; |  | ||||||
| 
 |  | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         $this->_account = $account; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     /** |     /** | ||||||
|      * @inheritdoc |      * @inheritdoc | ||||||
|      */ |      */ | ||||||
|     public function rules() { |     public function rules(): array { | ||||||
|         return ArrayHelper::merge(parent::rules(), [ |         return ArrayHelper::merge(parent::rules(), [ | ||||||
|             ['newPassword', 'required', 'message' => E::NEW_PASSWORD_REQUIRED], |             ['newPassword', 'required', 'message' => E::NEW_PASSWORD_REQUIRED], | ||||||
|             ['newRePassword', 'required', 'message' => E::NEW_RE_PASSWORD_REQUIRED], |             ['newRePassword', 'required', 'message' => E::NEW_RE_PASSWORD_REQUIRED], | ||||||
|             ['newPassword', PasswordValidator::class], |             ['newPassword', PasswordValidator::class], | ||||||
|             ['newRePassword', 'validatePasswordAndRePasswordMatch'], |             ['newRePassword', 'validatePasswordAndRePasswordMatch'], | ||||||
|             ['logoutAll', 'boolean'], |             ['logoutAll', 'boolean'], | ||||||
|             ['password', PasswordRequiredValidator::class, 'account' => $this->_account], |             ['password', PasswordRequiredValidator::class, 'account' => $this->getAccount(), 'when' => function() { | ||||||
|  |                 return !$this->hasErrors(); | ||||||
|  |             }], | ||||||
|         ]); |         ]); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function validatePasswordAndRePasswordMatch($attribute) { |     public function validatePasswordAndRePasswordMatch($attribute): void { | ||||||
|         if (!$this->hasErrors($attribute)) { |         if (!$this->hasErrors($attribute)) { | ||||||
|             if ($this->newPassword !== $this->newRePassword) { |             if ($this->newPassword !== $this->newRePassword) { | ||||||
|                 $this->addError($attribute, E::NEW_RE_PASSWORD_DOES_NOT_MATCH); |                 $this->addError($attribute, E::NEW_RE_PASSWORD_DOES_NOT_MATCH); | ||||||
| @@ -52,25 +43,22 @@ class ChangePasswordForm extends ApiForm { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     /** |     public function performAction(): bool { | ||||||
|      * @return bool |  | ||||||
|      * @throws ErrorException |  | ||||||
|      */ |  | ||||||
|     public function changePassword() : bool { |  | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
|             return false; |             return false; | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         $transaction = Yii::$app->db->beginTransaction(); |         $transaction = Yii::$app->db->beginTransaction(); | ||||||
|         $account = $this->_account; | 
 | ||||||
|  |         $account = $this->getAccount(); | ||||||
|         $account->setPassword($this->newPassword); |         $account->setPassword($this->newPassword); | ||||||
| 
 | 
 | ||||||
|         if ($this->logoutAll) { |         if ($this->logoutAll) { | ||||||
|             Yii::$app->user->terminateSessions(); |             Yii::$app->user->terminateSessions($account, Component::KEEP_CURRENT_SESSION); | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         if (!$account->save()) { |         if (!$account->save()) { | ||||||
|             throw new ErrorException('Cannot save user model'); |             throw new ThisShouldNotHappenException('Cannot save user model'); | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         $transaction->commit(); |         $transaction->commit(); | ||||||
| @@ -78,8 +66,4 @@ class ChangePasswordForm extends ApiForm { | |||||||
|         return true; |         return true; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     protected function getAccount() : Account { |  | ||||||
|         return $this->_account; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
| } | } | ||||||
| @@ -1,76 +1,60 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\models\profile; | namespace api\modules\accounts\models; | ||||||
| 
 | 
 | ||||||
| use api\models\base\ApiForm; | use api\exceptions\ThisShouldNotHappenException; | ||||||
| use api\validators\PasswordRequiredValidator; | use api\validators\PasswordRequiredValidator; | ||||||
| use common\helpers\Amqp; | use common\helpers\Amqp; | ||||||
| use common\models\Account; |  | ||||||
| use common\models\amqp\UsernameChanged; | use common\models\amqp\UsernameChanged; | ||||||
| use common\models\UsernameHistory; | use common\models\UsernameHistory; | ||||||
| use common\validators\UsernameValidator; | use common\validators\UsernameValidator; | ||||||
| use Exception; |  | ||||||
| use PhpAmqpLib\Message\AMQPMessage; | use PhpAmqpLib\Message\AMQPMessage; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; | use yii\base\ErrorException; | ||||||
| 
 | 
 | ||||||
| class ChangeUsernameForm extends ApiForm { | class ChangeUsernameForm extends AccountActionForm { | ||||||
| 
 | 
 | ||||||
|     public $username; |     public $username; | ||||||
| 
 | 
 | ||||||
|     public $password; |     public $password; | ||||||
| 
 | 
 | ||||||
|     /** |  | ||||||
|      * @var Account |  | ||||||
|      */ |  | ||||||
|     private $account; |  | ||||||
| 
 |  | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         parent::__construct($config); |  | ||||||
|         $this->account = $account; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function rules(): array { |     public function rules(): array { | ||||||
|         return [ |         return [ | ||||||
|             ['username', UsernameValidator::class, 'accountCallback' => function() { |             ['username', UsernameValidator::class, 'accountCallback' => function() { | ||||||
|                 return $this->account->id; |                 return $this->getAccount()->id; | ||||||
|             }], |             }], | ||||||
|             ['password', PasswordRequiredValidator::class], |             ['password', PasswordRequiredValidator::class, 'account' => $this->getAccount()], | ||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function change(): bool { |     public function performAction(): bool { | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
|             return false; |             return false; | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         $account = $this->account; |         $account = $this->getAccount(); | ||||||
|         if ($this->username === $account->username) { |         if ($this->username === $account->username) { | ||||||
|             return true; |             return true; | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         $transaction = Yii::$app->db->beginTransaction(); |         $transaction = Yii::$app->db->beginTransaction(); | ||||||
|         try { |  | ||||||
|             $oldNickname = $account->username; |  | ||||||
|             $account->username = $this->username; |  | ||||||
|             if (!$account->save()) { |  | ||||||
|                 throw new ErrorException('Cannot save account model with new username'); |  | ||||||
|             } |  | ||||||
| 
 | 
 | ||||||
|             $usernamesHistory = new UsernameHistory(); |         $oldNickname = $account->username; | ||||||
|             $usernamesHistory->account_id = $account->id; |         $account->username = $this->username; | ||||||
|             $usernamesHistory->username = $account->username; |         if (!$account->save()) { | ||||||
|             if (!$usernamesHistory->save()) { |             throw new ThisShouldNotHappenException('Cannot save account model with new username'); | ||||||
|                 throw new ErrorException('Cannot save username history record'); |  | ||||||
|             } |  | ||||||
| 
 |  | ||||||
|             $this->createEventTask($account->id, $account->username, $oldNickname); |  | ||||||
| 
 |  | ||||||
|             $transaction->commit(); |  | ||||||
|         } catch (Exception $e) { |  | ||||||
|             $transaction->rollBack(); |  | ||||||
|             throw $e; |  | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|  |         $usernamesHistory = new UsernameHistory(); | ||||||
|  |         $usernamesHistory->account_id = $account->id; | ||||||
|  |         $usernamesHistory->username = $account->username; | ||||||
|  |         if (!$usernamesHistory->save()) { | ||||||
|  |             throw new ErrorException('Cannot save username history record'); | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         $this->createEventTask($account->id, $account->username, $oldNickname); | ||||||
|  | 
 | ||||||
|  |         $transaction->commit(); | ||||||
|  | 
 | ||||||
|         return true; |         return true; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| @@ -80,10 +64,11 @@ class ChangeUsernameForm extends ApiForm { | |||||||
|      * @param integer $accountId |      * @param integer $accountId | ||||||
|      * @param string  $newNickname |      * @param string  $newNickname | ||||||
|      * @param string  $oldNickname |      * @param string  $oldNickname | ||||||
|      * @throws \PhpAmqpLib\Exception\AMQPExceptionInterface |      * | ||||||
|  |      * @throws \PhpAmqpLib\Exception\AMQPExceptionInterface|\yii\base\Exception | ||||||
|      */ |      */ | ||||||
|     public function createEventTask($accountId, $newNickname, $oldNickname) { |     public function createEventTask($accountId, $newNickname, $oldNickname): void { | ||||||
|         $model = new UsernameChanged; |         $model = new UsernameChanged(); | ||||||
|         $model->accountId = $accountId; |         $model->accountId = $accountId; | ||||||
|         $model->oldUsername = $oldNickname; |         $model->oldUsername = $oldNickname; | ||||||
|         $model->newUsername = $newNickname; |         $model->newUsername = $newNickname; | ||||||
							
								
								
									
										45
									
								
								api/modules/accounts/models/DisableTwoFactorAuthForm.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										45
									
								
								api/modules/accounts/models/DisableTwoFactorAuthForm.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,45 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\models; | ||||||
|  |  | ||||||
|  | use api\exceptions\ThisShouldNotHappenException; | ||||||
|  | use api\validators\PasswordRequiredValidator; | ||||||
|  | use api\validators\TotpValidator; | ||||||
|  | use common\helpers\Error as E; | ||||||
|  |  | ||||||
|  | class DisableTwoFactorAuthForm extends AccountActionForm { | ||||||
|  |  | ||||||
|  |     public $totp; | ||||||
|  |  | ||||||
|  |     public $password; | ||||||
|  |  | ||||||
|  |     public function rules(): array { | ||||||
|  |         return [ | ||||||
|  |             ['account', 'validateOtpEnabled'], | ||||||
|  |             ['totp', 'required', 'message' => E::TOTP_REQUIRED], | ||||||
|  |             ['totp', TotpValidator::class, 'account' => $this->getAccount()], | ||||||
|  |             ['password', PasswordRequiredValidator::class, 'account' => $this->getAccount()], | ||||||
|  |         ]; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function performAction(): bool { | ||||||
|  |         if (!$this->validate()) { | ||||||
|  |             return false; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         $account = $this->getAccount(); | ||||||
|  |         $account->is_otp_enabled = false; | ||||||
|  |         $account->otp_secret = null; | ||||||
|  |         if (!$account->save()) { | ||||||
|  |             throw new ThisShouldNotHappenException('Cannot disable otp for account'); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         return true; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function validateOtpEnabled($attribute): void { | ||||||
|  |         if (!$this->getAccount()->is_otp_enabled) { | ||||||
|  |             $this->addError($attribute, E::OTP_NOT_ENABLED); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										52
									
								
								api/modules/accounts/models/EnableTwoFactorAuthForm.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										52
									
								
								api/modules/accounts/models/EnableTwoFactorAuthForm.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,52 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\models; | ||||||
|  |  | ||||||
|  | use api\components\User\Component; | ||||||
|  | use api\exceptions\ThisShouldNotHappenException; | ||||||
|  | use api\validators\PasswordRequiredValidator; | ||||||
|  | use api\validators\TotpValidator; | ||||||
|  | use common\helpers\Error as E; | ||||||
|  | use Yii; | ||||||
|  |  | ||||||
|  | class EnableTwoFactorAuthForm extends AccountActionForm { | ||||||
|  |  | ||||||
|  |     public $totp; | ||||||
|  |  | ||||||
|  |     public $password; | ||||||
|  |  | ||||||
|  |     public function rules(): array { | ||||||
|  |         return [ | ||||||
|  |             ['account', 'validateOtpDisabled'], | ||||||
|  |             ['totp', 'required', 'message' => E::TOTP_REQUIRED], | ||||||
|  |             ['totp', TotpValidator::class, 'account' => $this->getAccount()], | ||||||
|  |             ['password', PasswordRequiredValidator::class, 'account' => $this->getAccount()], | ||||||
|  |         ]; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function performAction(): bool { | ||||||
|  |         if (!$this->validate()) { | ||||||
|  |             return false; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         $transaction = Yii::$app->db->beginTransaction(); | ||||||
|  |  | ||||||
|  |         $account = $this->getAccount(); | ||||||
|  |         $account->is_otp_enabled = true; | ||||||
|  |         if (!$account->save()) { | ||||||
|  |             throw new ThisShouldNotHappenException('Cannot enable otp for account'); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         Yii::$app->user->terminateSessions($account, Component::KEEP_CURRENT_SESSION); | ||||||
|  |  | ||||||
|  |         $transaction->commit(); | ||||||
|  |  | ||||||
|  |         return true; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     public function validateOtpDisabled($attribute): void { | ||||||
|  |         if ($this->getAccount()->is_otp_enabled) { | ||||||
|  |             $this->addError($attribute, E::OTP_ALREADY_ENABLED); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -1,7 +1,6 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\modules\internal\models; | namespace api\modules\accounts\models; | ||||||
| 
 | 
 | ||||||
| use api\models\base\ApiForm; |  | ||||||
| use api\modules\internal\helpers\Error as E; | use api\modules\internal\helpers\Error as E; | ||||||
| use common\helpers\Amqp; | use common\helpers\Amqp; | ||||||
| use common\models\Account; | use common\models\Account; | ||||||
| @@ -10,12 +9,7 @@ use PhpAmqpLib\Message\AMQPMessage; | |||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; | use yii\base\ErrorException; | ||||||
| 
 | 
 | ||||||
| class PardonForm extends ApiForm { | class PardonAccountForm extends AccountActionForm { | ||||||
| 
 |  | ||||||
|     /** |  | ||||||
|      * @var Account |  | ||||||
|      */ |  | ||||||
|     private $account; |  | ||||||
| 
 | 
 | ||||||
|     public function rules(): array { |     public function rules(): array { | ||||||
|         return [ |         return [ | ||||||
| @@ -23,24 +17,20 @@ class PardonForm extends ApiForm { | |||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function getAccount(): Account { |  | ||||||
|         return $this->account; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function validateAccountBanned(): void { |     public function validateAccountBanned(): void { | ||||||
|         if ($this->account->status !== Account::STATUS_BANNED) { |         if ($this->getAccount()->status !== Account::STATUS_BANNED) { | ||||||
|             $this->addError('account', E::ACCOUNT_NOT_BANNED); |             $this->addError('account', E::ACCOUNT_NOT_BANNED); | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function pardon(): bool { |     public function performAction(): bool { | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
|             return false; |             return false; | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         $transaction = Yii::$app->db->beginTransaction(); |         $transaction = Yii::$app->db->beginTransaction(); | ||||||
| 
 | 
 | ||||||
|         $account = $this->account; |         $account = $this->getAccount(); | ||||||
|         $account->status = Account::STATUS_ACTIVE; |         $account->status = Account::STATUS_ACTIVE; | ||||||
|         if (!$account->save()) { |         if (!$account->save()) { | ||||||
|             throw new ErrorException('Cannot pardon account'); |             throw new ErrorException('Cannot pardon account'); | ||||||
| @@ -55,7 +45,7 @@ class PardonForm extends ApiForm { | |||||||
| 
 | 
 | ||||||
|     public function createTask(): void { |     public function createTask(): void { | ||||||
|         $model = new AccountPardoned(); |         $model = new AccountPardoned(); | ||||||
|         $model->accountId = $this->account->id; |         $model->accountId = $this->getAccount()->id; | ||||||
| 
 | 
 | ||||||
|         $message = Amqp::getInstance()->prepareMessage($model, [ |         $message = Amqp::getInstance()->prepareMessage($model, [ | ||||||
|             'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT, |             'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT, | ||||||
| @@ -64,9 +54,4 @@ class PardonForm extends ApiForm { | |||||||
|         Amqp::sendToEventsExchange('accounts.account-pardoned', $message); |         Amqp::sendToEventsExchange('accounts.account-pardoned', $message); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         $this->account = $account; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
| } | } | ||||||
| @@ -1,43 +1,31 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\models\profile\ChangeEmail; | namespace api\modules\accounts\models; | ||||||
| 
 | 
 | ||||||
|  | use api\exceptions\ThisShouldNotHappenException; | ||||||
| use common\emails\EmailHelper; | use common\emails\EmailHelper; | ||||||
| use api\models\base\ApiForm; |  | ||||||
| use api\validators\PasswordRequiredValidator; | use api\validators\PasswordRequiredValidator; | ||||||
| use common\helpers\Error as E; | use common\helpers\Error as E; | ||||||
| use common\models\Account; |  | ||||||
| use common\models\confirmations\CurrentEmailConfirmation; | use common\models\confirmations\CurrentEmailConfirmation; | ||||||
| use common\models\EmailActivation; | use common\models\EmailActivation; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; |  | ||||||
| use yii\base\Exception; |  | ||||||
| 
 | 
 | ||||||
| class InitStateForm extends ApiForm { | class SendEmailVerificationForm extends AccountActionForm { | ||||||
| 
 |  | ||||||
|     public $email; |  | ||||||
| 
 | 
 | ||||||
|     public $password; |     public $password; | ||||||
| 
 | 
 | ||||||
|     private $account; |     /** | ||||||
|  |      * @var null meta-поле, чтобы заставить yii валидировать и публиковать ошибки, связанные с отправленными email | ||||||
|  |      */ | ||||||
|  |     public $email; | ||||||
| 
 | 
 | ||||||
|     public function __construct(Account $account, array $config = []) { |     public function rules(): array { | ||||||
|         $this->account = $account; |  | ||||||
|         $this->email = $account->email; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function getAccount() : Account { |  | ||||||
|         return $this->account; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function rules() { |  | ||||||
|         return [ |         return [ | ||||||
|             ['email', 'validateFrequency'], |             ['email', 'validateFrequency', 'skipOnEmpty' => false], | ||||||
|             ['password', PasswordRequiredValidator::class, 'account' => $this->account], |             ['password', PasswordRequiredValidator::class, 'account' => $this->getAccount()], | ||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function validateFrequency($attribute) { |     public function validateFrequency($attribute): void { | ||||||
|         if (!$this->hasErrors()) { |         if (!$this->hasErrors()) { | ||||||
|             $emailConfirmation = $this->getEmailActivation(); |             $emailConfirmation = $this->getEmailActivation(); | ||||||
|             if ($emailConfirmation !== null && !$emailConfirmation->canRepeat()) { |             if ($emailConfirmation !== null && !$emailConfirmation->canRepeat()) { | ||||||
| @@ -46,46 +34,35 @@ class InitStateForm extends ApiForm { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function sendCurrentEmailConfirmation() : bool { |     public function performAction(): bool { | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
|             return false; |             return false; | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         $transaction = Yii::$app->db->beginTransaction(); |         $transaction = Yii::$app->db->beginTransaction(); | ||||||
|         try { |  | ||||||
|             $this->removeOldCode(); |  | ||||||
|             $activation = $this->createCode(); |  | ||||||
| 
 | 
 | ||||||
|             EmailHelper::changeEmailConfirmCurrent($activation); |         $this->removeOldCode(); | ||||||
|  |         $activation = $this->createCode(); | ||||||
| 
 | 
 | ||||||
|             $transaction->commit(); |         EmailHelper::changeEmailConfirmCurrent($activation); | ||||||
|         } catch (Exception $e) { | 
 | ||||||
|             $transaction->rollBack(); |         $transaction->commit(); | ||||||
|             throw $e; |  | ||||||
|         } |  | ||||||
| 
 | 
 | ||||||
|         return true; |         return true; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     /** |     public function createCode(): CurrentEmailConfirmation { | ||||||
|      * @return CurrentEmailConfirmation |  | ||||||
|      * @throws ErrorException |  | ||||||
|      */ |  | ||||||
|     public function createCode() : CurrentEmailConfirmation { |  | ||||||
|         $account = $this->getAccount(); |         $account = $this->getAccount(); | ||||||
|         $emailActivation = new CurrentEmailConfirmation(); |         $emailActivation = new CurrentEmailConfirmation(); | ||||||
|         $emailActivation->account_id = $account->id; |         $emailActivation->account_id = $account->id; | ||||||
|         if (!$emailActivation->save()) { |         if (!$emailActivation->save()) { | ||||||
|             throw new ErrorException('Cannot save email activation model'); |             throw new ThisShouldNotHappenException('Cannot save email activation model'); | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         return $emailActivation; |         return $emailActivation; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     /** |     public function removeOldCode(): void { | ||||||
|      * Удаляет старый ключ активации, если он существует |  | ||||||
|      */ |  | ||||||
|     public function removeOldCode() { |  | ||||||
|         $emailActivation = $this->getEmailActivation(); |         $emailActivation = $this->getEmailActivation(); | ||||||
|         if ($emailActivation === null) { |         if ($emailActivation === null) { | ||||||
|             return; |             return; | ||||||
| @@ -99,10 +76,8 @@ class InitStateForm extends ApiForm { | |||||||
|      * Метод предназначен для проверки, не слишком ли часто отправляются письма о смене E-mail. |      * Метод предназначен для проверки, не слишком ли часто отправляются письма о смене E-mail. | ||||||
|      * Проверяем тип подтверждения нового E-mail, поскольку при переходе на этот этап, активация предыдущего |      * Проверяем тип подтверждения нового E-mail, поскольку при переходе на этот этап, активация предыдущего | ||||||
|      * шага удаляется. |      * шага удаляется. | ||||||
|      * @return EmailActivation|null |  | ||||||
|      * @throws ErrorException |  | ||||||
|      */ |      */ | ||||||
|     public function getEmailActivation() { |     public function getEmailActivation(): ?EmailActivation { | ||||||
|         return $this->getAccount() |         return $this->getAccount() | ||||||
|             ->getEmailActivations() |             ->getEmailActivations() | ||||||
|             ->andWhere([ |             ->andWhere([ | ||||||
| @@ -1,39 +1,28 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\models\profile\ChangeEmail; | namespace api\modules\accounts\models; | ||||||
| 
 | 
 | ||||||
|  | use api\exceptions\ThisShouldNotHappenException; | ||||||
| use common\emails\EmailHelper; | use common\emails\EmailHelper; | ||||||
| use api\models\base\ApiForm; |  | ||||||
| use api\validators\EmailActivationKeyValidator; | use api\validators\EmailActivationKeyValidator; | ||||||
| use common\models\Account; |  | ||||||
| use common\models\confirmations\NewEmailConfirmation; | use common\models\confirmations\NewEmailConfirmation; | ||||||
| use common\models\EmailActivation; | use common\models\EmailActivation; | ||||||
| use common\validators\EmailValidator; | use common\validators\EmailValidator; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; |  | ||||||
| 
 | 
 | ||||||
| class NewEmailForm extends ApiForm { | class SendNewEmailVerificationForm extends AccountActionForm { | ||||||
| 
 | 
 | ||||||
|     public $key; |     public $key; | ||||||
| 
 | 
 | ||||||
|     public $email; |     public $email; | ||||||
| 
 | 
 | ||||||
|     /** |     public function rules(): array { | ||||||
|      * @var Account |  | ||||||
|      */ |  | ||||||
|     private $account; |  | ||||||
| 
 |  | ||||||
|     public function rules() { |  | ||||||
|         return [ |         return [ | ||||||
|             ['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION], |             ['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION], | ||||||
|             ['email', EmailValidator::class], |             ['email', EmailValidator::class], | ||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function getAccount(): Account { |     public function performAction(): bool { | ||||||
|         return $this->account; |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     public function sendNewEmailConfirmation(): bool { |  | ||||||
|         if (!$this->validate()) { |         if (!$this->validate()) { | ||||||
|             return false; |             return false; | ||||||
|         } |         } | ||||||
| @@ -53,24 +42,15 @@ class NewEmailForm extends ApiForm { | |||||||
|         return true; |         return true; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     /** |     public function createCode(): NewEmailConfirmation { | ||||||
|      * @return NewEmailConfirmation |  | ||||||
|      * @throws ErrorException |  | ||||||
|      */ |  | ||||||
|     public function createCode() { |  | ||||||
|         $emailActivation = new NewEmailConfirmation(); |         $emailActivation = new NewEmailConfirmation(); | ||||||
|         $emailActivation->account_id = $this->getAccount()->id; |         $emailActivation->account_id = $this->getAccount()->id; | ||||||
|         $emailActivation->newEmail = $this->email; |         $emailActivation->newEmail = $this->email; | ||||||
|         if (!$emailActivation->save()) { |         if (!$emailActivation->save()) { | ||||||
|             throw new ErrorException('Cannot save email activation model'); |             throw new ThisShouldNotHappenException('Cannot save email activation model'); | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         return $emailActivation; |         return $emailActivation; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public function __construct(Account $account, array $config = []) { |  | ||||||
|         $this->account = $account; |  | ||||||
|         parent::__construct($config); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
| } | } | ||||||
							
								
								
									
										20
									
								
								api/modules/accounts/models/TotpHelper.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										20
									
								
								api/modules/accounts/models/TotpHelper.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,20 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\models; | ||||||
|  |  | ||||||
|  | use common\models\Account; | ||||||
|  | use OTPHP\TOTP; | ||||||
|  |  | ||||||
|  | trait TotpHelper { | ||||||
|  |  | ||||||
|  |     protected function getTotp(): TOTP { | ||||||
|  |         $account = $this->getAccount(); | ||||||
|  |         $totp = TOTP::create($account->otp_secret); | ||||||
|  |         $totp->setLabel($account->email); | ||||||
|  |         $totp->setIssuer('Ely.by'); | ||||||
|  |  | ||||||
|  |         return $totp; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     abstract public function getAccount(): Account; | ||||||
|  |  | ||||||
|  | } | ||||||
							
								
								
									
										80
									
								
								api/modules/accounts/models/TwoFactorAuthInfo.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										80
									
								
								api/modules/accounts/models/TwoFactorAuthInfo.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,80 @@ | |||||||
|  | <?php | ||||||
|  | namespace api\modules\accounts\models; | ||||||
|  |  | ||||||
|  | use api\exceptions\ThisShouldNotHappenException; | ||||||
|  | use api\models\base\BaseAccountForm; | ||||||
|  | use BaconQrCode\Common\ErrorCorrectionLevel; | ||||||
|  | use BaconQrCode\Encoder\Encoder; | ||||||
|  | use BaconQrCode\Renderer\Color\Rgb; | ||||||
|  | use BaconQrCode\Renderer\Image\Svg; | ||||||
|  | use BaconQrCode\Writer; | ||||||
|  | use common\components\Qr\ElyDecorator; | ||||||
|  | use ParagonIE\ConstantTime\Base32; | ||||||
|  |  | ||||||
|  | class TwoFactorAuthInfo extends BaseAccountForm { | ||||||
|  |     use TotpHelper; | ||||||
|  |  | ||||||
|  |     public function getCredentials(): array { | ||||||
|  |         if (empty($this->getAccount()->otp_secret)) { | ||||||
|  |             $this->setOtpSecret(); | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         $provisioningUri = $this->getTotp()->getProvisioningUri(); | ||||||
|  |  | ||||||
|  |         return [ | ||||||
|  |             'qr' => 'data:image/svg+xml,' . trim($this->drawQrCode($provisioningUri)), | ||||||
|  |             'uri' => $provisioningUri, | ||||||
|  |             'secret' => $this->getAccount()->otp_secret, | ||||||
|  |         ]; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     private function drawQrCode(string $content): string { | ||||||
|  |         $content = $this->forceMinimalQrContentLength($content); | ||||||
|  |  | ||||||
|  |         $renderer = new Svg(); | ||||||
|  |         $renderer->setForegroundColor(new Rgb(32, 126, 92)); | ||||||
|  |         $renderer->setMargin(0); | ||||||
|  |         $renderer->addDecorator(new ElyDecorator()); | ||||||
|  |  | ||||||
|  |         $writer = new Writer($renderer); | ||||||
|  |  | ||||||
|  |         return $writer->writeString($content, Encoder::DEFAULT_BYTE_MODE_ECODING, ErrorCorrectionLevel::H); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * otp_secret кодируется в Base32, т.к. после кодирования в результурющей строке нет символов, | ||||||
|  |      * которые можно перепутать (1 и l, O и 0, и т.д.). Отрицательной стороной является то, что итоговая | ||||||
|  |      * строка составляет 160% от исходной. Поэтому, генерируя исходный приватный ключ, мы должны обеспечить | ||||||
|  |      * ему такую длину, чтобы 160% его длины было равно запрошенному значению | ||||||
|  |      * | ||||||
|  |      * @param int $length | ||||||
|  |      * | ||||||
|  |      * @throws ThisShouldNotHappenException | ||||||
|  |      */ | ||||||
|  |     private function setOtpSecret(int $length = 24): void { | ||||||
|  |         $account = $this->getAccount(); | ||||||
|  |         $randomBytesLength = ceil($length / 1.6); | ||||||
|  |         $randomBase32 = trim(Base32::encodeUpper(random_bytes($randomBytesLength)), '='); | ||||||
|  |         $account->otp_secret = substr($randomBase32, 0, $length); | ||||||
|  |         if (!$account->save()) { | ||||||
|  |             throw new ThisShouldNotHappenException('Cannot set account otp_secret'); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * В используемой либе для рендеринга QR кода нет возможности указать QR code version. | ||||||
|  |      * http://www.qrcode.com/en/about/version.html | ||||||
|  |      * По какой-то причине 7 и 8 версии не читаются вовсе, с логотипом или без. | ||||||
|  |      * Поэтому нужно иначально привести строку к длинне 9 версии (91), добавляя к концу | ||||||
|  |      * строки необходимое количество символов "#". Этот символ используется, т.к. нашим | ||||||
|  |      * контентом является ссылка и чтобы не вводить лишние параметры мы помечаем добавочную | ||||||
|  |      * часть как хеш часть и все программы для чтения QR кодов продолжают свою работу. | ||||||
|  |      * | ||||||
|  |      * @param string $content | ||||||
|  |      * @return string | ||||||
|  |      */ | ||||||
|  |     private function forceMinimalQrContentLength(string $content): string { | ||||||
|  |         return str_pad($content, 91, '#'); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  | } | ||||||
| @@ -7,7 +7,7 @@ use Yii; | |||||||
|  |  | ||||||
| class AuthenticationController extends Controller { | class AuthenticationController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         $behaviors = parent::behaviors(); |         $behaviors = parent::behaviors(); | ||||||
|         unset($behaviors['authenticator']); |         unset($behaviors['authenticator']); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,58 +1,42 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\modules\internal\controllers; | namespace api\modules\internal\controllers; | ||||||
|  |  | ||||||
| use api\components\ApiUser\AccessControl; |  | ||||||
| use api\controllers\Controller; | use api\controllers\Controller; | ||||||
| use api\modules\internal\models\BanForm; |  | ||||||
| use api\modules\internal\models\PardonForm; |  | ||||||
| use common\models\Account; | use common\models\Account; | ||||||
| use common\models\OauthScope as S; | use common\rbac\Permissions as P; | ||||||
| use Yii; | use yii\filters\AccessControl; | ||||||
| use yii\helpers\ArrayHelper; | use yii\helpers\ArrayHelper; | ||||||
| use yii\web\BadRequestHttpException; | use yii\web\BadRequestHttpException; | ||||||
| use yii\web\NotFoundHttpException; | use yii\web\NotFoundHttpException; | ||||||
|  |  | ||||||
| class AccountsController extends Controller { | class AccountsController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         return ArrayHelper::merge(parent::behaviors(), [ |         return ArrayHelper::merge(parent::behaviors(), [ | ||||||
|             'authenticator' => [ |  | ||||||
|                 'user' => Yii::$app->apiUser, |  | ||||||
|             ], |  | ||||||
|             'access' => [ |             'access' => [ | ||||||
|                 'class' => AccessControl::class, |                 'class' => AccessControl::class, | ||||||
|                 'rules' => [ |                 'rules' => [ | ||||||
|                     [ |  | ||||||
|                         'actions' => ['ban'], |  | ||||||
|                         'allow' => true, |  | ||||||
|                         'roles' => [S::ACCOUNT_BLOCK], |  | ||||||
|                     ], |  | ||||||
|                     [ |                     [ | ||||||
|                         'actions' => ['info'], |                         'actions' => ['info'], | ||||||
|                         'allow' => true, |                         'allow' => true, | ||||||
|                         'roles' => [S::INTERNAL_ACCOUNT_INFO], |                         'roles' => [P::OBTAIN_EXTENDED_ACCOUNT_INFO], | ||||||
|  |                         'roleParams' => function() { | ||||||
|  |                             return [ | ||||||
|  |                                 'accountId' => 0, | ||||||
|  |                             ]; | ||||||
|  |                         }, | ||||||
|                     ], |                     ], | ||||||
|                 ], |                 ], | ||||||
|             ], |             ], | ||||||
|         ]); |         ]); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function verbs() { |     public function verbs(): array { | ||||||
|         return [ |         return [ | ||||||
|             'ban' => ['POST', 'DELETE'], |  | ||||||
|             'info' => ['GET'], |             'info' => ['GET'], | ||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function actionBan(int $accountId) { |  | ||||||
|         $account = $this->findAccount($accountId); |  | ||||||
|         if (Yii::$app->request->isPost) { |  | ||||||
|             return $this->banAccount($account); |  | ||||||
|         } else { |  | ||||||
|             return $this->pardonAccount($account); |  | ||||||
|         } |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function actionInfo(int $id = null, string $username = null, string $uuid = null) { |     public function actionInfo(int $id = null, string $username = null, string $uuid = null) { | ||||||
|         if ($id !== null) { |         if ($id !== null) { | ||||||
|             $account = Account::findOne($id); |             $account = Account::findOne($id); | ||||||
| @@ -76,43 +60,4 @@ class AccountsController extends Controller { | |||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     private function banAccount(Account $account) { |  | ||||||
|         $model = new BanForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->ban()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     private function pardonAccount(Account $account) { |  | ||||||
|         $model = new PardonForm($account); |  | ||||||
|         $model->load(Yii::$app->request->post()); |  | ||||||
|         if (!$model->pardon()) { |  | ||||||
|             return [ |  | ||||||
|                 'success' => false, |  | ||||||
|                 'errors' => $model->getFirstErrors(), |  | ||||||
|             ]; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return [ |  | ||||||
|             'success' => true, |  | ||||||
|         ]; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     private function findAccount(int $accountId): Account { |  | ||||||
|         $account = Account::findOne($accountId); |  | ||||||
|         if ($account === null) { |  | ||||||
|             throw new NotFoundHttpException(); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         return $account; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -10,7 +10,7 @@ use yii\web\Response; | |||||||
|  |  | ||||||
| class ApiController extends Controller { | class ApiController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         $behaviors = parent::behaviors(); |         $behaviors = parent::behaviors(); | ||||||
|         unset($behaviors['authenticator']); |         unset($behaviors['authenticator']); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,7 +1,7 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\modules\session\controllers; | namespace api\modules\session\controllers; | ||||||
|  |  | ||||||
| use api\controllers\ApiController; | use api\controllers\Controller; | ||||||
| use api\modules\session\exceptions\ForbiddenOperationException; | use api\modules\session\exceptions\ForbiddenOperationException; | ||||||
| use api\modules\session\exceptions\IllegalArgumentException; | use api\modules\session\exceptions\IllegalArgumentException; | ||||||
| use api\modules\session\exceptions\SessionServerException; | use api\modules\session\exceptions\SessionServerException; | ||||||
| @@ -17,9 +17,9 @@ use Ramsey\Uuid\Uuid; | |||||||
| use Yii; | use Yii; | ||||||
| use yii\web\Response; | use yii\web\Response; | ||||||
|  |  | ||||||
| class SessionController extends ApiController { | class SessionController extends Controller { | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         $behaviors = parent::behaviors(); |         $behaviors = parent::behaviors(); | ||||||
|         unset($behaviors['authenticator']); |         unset($behaviors['authenticator']); | ||||||
|         $behaviors['rateLimiting'] = [ |         $behaviors['rateLimiting'] = [ | ||||||
|   | |||||||
| @@ -18,7 +18,7 @@ class HasJoinedForm extends Model { | |||||||
|         parent::__construct($config); |         parent::__construct($config); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function hasJoined() : Account { |     public function hasJoined(): Account { | ||||||
|         if (!$this->protocol->validate()) { |         if (!$this->protocol->validate()) { | ||||||
|             throw new IllegalArgumentException(); |             throw new IllegalArgumentException(); | ||||||
|         } |         } | ||||||
|   | |||||||
| @@ -7,10 +7,10 @@ use api\modules\session\models\protocols\JoinInterface; | |||||||
| use api\modules\session\Module as Session; | use api\modules\session\Module as Session; | ||||||
| use api\modules\session\validators\RequiredValidator; | use api\modules\session\validators\RequiredValidator; | ||||||
| use common\helpers\StringHelper; | use common\helpers\StringHelper; | ||||||
| use common\models\OauthScope as S; | use common\rbac\Permissions as P; | ||||||
| use common\validators\UuidValidator; |  | ||||||
| use common\models\Account; | use common\models\Account; | ||||||
| use common\models\MinecraftAccessKey; | use common\models\MinecraftAccessKey; | ||||||
|  | use Ramsey\Uuid\Uuid; | ||||||
| use Yii; | use Yii; | ||||||
| use yii\base\ErrorException; | use yii\base\ErrorException; | ||||||
| use yii\base\Model; | use yii\base\Model; | ||||||
| @@ -84,16 +84,7 @@ class JoinForm extends Model { | |||||||
|             return; |             return; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         if ($attribute === 'selectedProfile' && !StringHelper::isUuid($this->selectedProfile)) { |         if ($this->$attribute === Uuid::NIL) { | ||||||
|             // Это нормально. Там может быть ник игрока, если это Legacy авторизация |  | ||||||
|             return; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         $validator = new UuidValidator(); |  | ||||||
|         $validator->allowNil = false; |  | ||||||
|         $validator->validateAttribute($this, $attribute); |  | ||||||
|  |  | ||||||
|         if ($this->hasErrors($attribute)) { |  | ||||||
|             throw new IllegalArgumentException(); |             throw new IllegalArgumentException(); | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| @@ -105,9 +96,17 @@ class JoinForm extends Model { | |||||||
|         $accessToken = $this->accessToken; |         $accessToken = $this->accessToken; | ||||||
|         /** @var MinecraftAccessKey|null $accessModel */ |         /** @var MinecraftAccessKey|null $accessModel */ | ||||||
|         $accessModel = MinecraftAccessKey::findOne($accessToken); |         $accessModel = MinecraftAccessKey::findOne($accessToken); | ||||||
|         if ($accessModel === null) { |         if ($accessModel !== null) { | ||||||
|  |             /** @var MinecraftAccessKey|\api\components\OAuth2\Entities\AccessTokenEntity $accessModel */ | ||||||
|  |             if ($accessModel->isExpired()) { | ||||||
|  |                 Session::error("User with access_token = '{$accessToken}' failed join by expired access_token."); | ||||||
|  |                 throw new ForbiddenOperationException('Expired access_token.'); | ||||||
|  |             } | ||||||
|  |  | ||||||
|  |             $account = $accessModel->account; | ||||||
|  |         } else { | ||||||
|             try { |             try { | ||||||
|                 $identity = Yii::$app->apiUser->loginByAccessToken($accessToken); |                 $identity = Yii::$app->user->loginByAccessToken($accessToken); | ||||||
|             } catch (UnauthorizedHttpException $e) { |             } catch (UnauthorizedHttpException $e) { | ||||||
|                 $identity = null; |                 $identity = null; | ||||||
|             } |             } | ||||||
| @@ -117,21 +116,12 @@ class JoinForm extends Model { | |||||||
|                 throw new ForbiddenOperationException('Invalid access_token.'); |                 throw new ForbiddenOperationException('Invalid access_token.'); | ||||||
|             } |             } | ||||||
|  |  | ||||||
|             if (!Yii::$app->apiUser->can(S::MINECRAFT_SERVER_SESSION)) { |             if (!Yii::$app->user->can(P::MINECRAFT_SERVER_SESSION)) { | ||||||
|                 Session::error("User with access_token = '{$accessToken}' doesn't have enough scopes to make join."); |                 Session::error("User with access_token = '{$accessToken}' doesn't have enough scopes to make join."); | ||||||
|                 throw new ForbiddenOperationException('The token does not have required scope.'); |                 throw new ForbiddenOperationException('The token does not have required scope.'); | ||||||
|             } |             } | ||||||
|  |  | ||||||
|             $accessModel = $identity->getAccessToken(); |  | ||||||
|             $account = $identity->getAccount(); |             $account = $identity->getAccount(); | ||||||
|         } else { |  | ||||||
|             $account = $accessModel->account; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         /** @var MinecraftAccessKey|\api\components\OAuth2\Entities\AccessTokenEntity $accessModel */ |  | ||||||
|         if ($accessModel->isExpired()) { |  | ||||||
|             Session::error("User with access_token = '{$accessToken}' failed join by expired access_token."); |  | ||||||
|             throw new ForbiddenOperationException('Expired access_token.'); |  | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         $selectedProfile = $this->selectedProfile; |         $selectedProfile = $this->selectedProfile; | ||||||
| @@ -142,7 +132,9 @@ class JoinForm extends Model { | |||||||
|                 " but access_token issued to account with id = '{$account->uuid}'." |                 " but access_token issued to account with id = '{$account->uuid}'." | ||||||
|             ); |             ); | ||||||
|             throw new ForbiddenOperationException('Wrong selected_profile.'); |             throw new ForbiddenOperationException('Wrong selected_profile.'); | ||||||
|         } elseif (!$isUuid && $account->username !== $selectedProfile) { |         } | ||||||
|  |  | ||||||
|  |         if (!$isUuid && $account->username !== $selectedProfile) { | ||||||
|             Session::error( |             Session::error( | ||||||
|                 "User with access_token = '{$accessToken}' trying to join with identity = '{$selectedProfile}'," . |                 "User with access_token = '{$accessToken}' trying to join with identity = '{$selectedProfile}'," . | ||||||
|                 " but access_token issued to account with username = '{$account->username}'." |                 " but access_token issued to account with username = '{$account->username}'." | ||||||
| @@ -153,10 +145,7 @@ class JoinForm extends Model { | |||||||
|         $this->account = $account; |         $this->account = $account; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     protected function getAccount(): Account { | ||||||
|      * @return Account|null |  | ||||||
|      */ |  | ||||||
|     protected function getAccount() { |  | ||||||
|         return $this->account; |         return $this->account; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -17,24 +17,16 @@ class SessionModel { | |||||||
|         $this->serverId = $serverId; |         $this->serverId = $serverId; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     public static function find(string $username, string $serverId): ?self { | ||||||
|      * @param $username |  | ||||||
|      * @param $serverId |  | ||||||
|      * |  | ||||||
|      * @return static|null |  | ||||||
|      */ |  | ||||||
|     public static function find($username, $serverId) { |  | ||||||
|         $key = static::buildKey($username, $serverId); |         $key = static::buildKey($username, $serverId); | ||||||
|         $result = Yii::$app->redis->executeCommand('GET', [$key]); |         $result = Yii::$app->redis->executeCommand('GET', [$key]); | ||||||
|         if (!$result) { |         if (!$result) { | ||||||
|             /** @noinspection PhpIncompatibleReturnTypeInspection шторм что-то сума сходит, когда видит static */ |  | ||||||
|             return null; |             return null; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         $data = json_decode($result, true); |         $data = json_decode($result, true); | ||||||
|         $model = new static($data['username'], $data['serverId']); |  | ||||||
|  |  | ||||||
|         return $model; |         return new static($data['username'], $data['serverId']); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function save() { |     public function save() { | ||||||
| @@ -51,15 +43,11 @@ class SessionModel { | |||||||
|         return Yii::$app->redis->executeCommand('DEL', [static::buildKey($this->username, $this->serverId)]); |         return Yii::$app->redis->executeCommand('DEL', [static::buildKey($this->username, $this->serverId)]); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     public function getAccount(): ?Account { | ||||||
|      * @return Account|null |  | ||||||
|      * TODO: после перехода на PHP 7.1 установить тип как ?Account |  | ||||||
|      */ |  | ||||||
|     public function getAccount() { |  | ||||||
|         return Account::findOne(['username' => $this->username]); |         return Account::findOne(['username' => $this->username]); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     protected static function buildKey($username, $serverId) : string { |     protected static function buildKey($username, $serverId): string { | ||||||
|         return md5('minecraft:join-server:' . mb_strtolower($username) . ':' . $serverId); |         return md5('minecraft:join-server:' . mb_strtolower($username) . ':' . $serverId); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,31 +1,30 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\modules\session\models\protocols; | namespace api\modules\session\models\protocols; | ||||||
|  |  | ||||||
| use yii\validators\RequiredValidator; |  | ||||||
|  |  | ||||||
| abstract class BaseHasJoined implements HasJoinedInterface { | abstract class BaseHasJoined implements HasJoinedInterface { | ||||||
|  |  | ||||||
|     private $username; |     private $username; | ||||||
|     private $serverId; |     private $serverId; | ||||||
|  |  | ||||||
|     public function __construct(string $username, string $serverId) { |     public function __construct(string $username, string $serverId) { | ||||||
|         $this->username = $username; |         $this->username = trim($username); | ||||||
|         $this->serverId = $serverId; |         $this->serverId = trim($serverId); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getUsername() : string { |     public function getUsername(): string { | ||||||
|         return $this->username; |         return $this->username; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getServerId() : string { |     public function getServerId(): string { | ||||||
|         return $this->serverId; |         return $this->serverId; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function validate() : bool { |     public function validate(): bool { | ||||||
|         $validator = new RequiredValidator(); |         return !$this->isEmpty($this->username) && !$this->isEmpty($this->serverId); | ||||||
|  |     } | ||||||
|  |  | ||||||
|         return $validator->validate($this->username) |     private function isEmpty($value): bool { | ||||||
|             && $validator->validate($this->serverId); |         return $value === null || $value === ''; | ||||||
|     } |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -3,12 +3,8 @@ namespace api\modules\session\models\protocols; | |||||||
|  |  | ||||||
| abstract class BaseJoin implements JoinInterface { | abstract class BaseJoin implements JoinInterface { | ||||||
|  |  | ||||||
|     abstract public function getAccessToken() : string; |     protected function isEmpty($value): bool { | ||||||
|  |         return $value === null || $value === ''; | ||||||
|     abstract public function getSelectedProfile() : string; |     } | ||||||
|  |  | ||||||
|     abstract public function getServerId() : string; |  | ||||||
|  |  | ||||||
|     abstract public function validate() : bool; |  | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -3,10 +3,10 @@ namespace api\modules\session\models\protocols; | |||||||
|  |  | ||||||
| interface HasJoinedInterface { | interface HasJoinedInterface { | ||||||
|  |  | ||||||
|     public function getUsername() : string; |     public function getUsername(): string; | ||||||
|  |  | ||||||
|     public function getServerId() : string; |     public function getServerId(): string; | ||||||
|  |  | ||||||
|     public function validate() : bool; |     public function validate(): bool; | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -3,13 +3,12 @@ namespace api\modules\session\models\protocols; | |||||||
|  |  | ||||||
| interface JoinInterface { | interface JoinInterface { | ||||||
|  |  | ||||||
|     public function getAccessToken() : string; |     public function getAccessToken(): string; | ||||||
|  |  | ||||||
|     // TODO: после перехода на PHP 7.1 сменить тип на ?string и возвращать null, если параметр не передан |     public function getSelectedProfile(): string; | ||||||
|     public function getSelectedProfile() : string; |  | ||||||
|  |  | ||||||
|     public function getServerId() : string; |     public function getServerId(): string; | ||||||
|  |  | ||||||
|     public function validate() : bool; |     public function validate(): bool; | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,8 +1,6 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\modules\session\models\protocols; | namespace api\modules\session\models\protocols; | ||||||
|  |  | ||||||
| use yii\validators\RequiredValidator; |  | ||||||
|  |  | ||||||
| class LegacyJoin extends BaseJoin { | class LegacyJoin extends BaseJoin { | ||||||
|  |  | ||||||
|     private $user; |     private $user; | ||||||
| @@ -13,9 +11,9 @@ class LegacyJoin extends BaseJoin { | |||||||
|     private $uuid; |     private $uuid; | ||||||
|  |  | ||||||
|     public function __construct(string $user, string $sessionId, string $serverId) { |     public function __construct(string $user, string $sessionId, string $serverId) { | ||||||
|         $this->user = $user; |         $this->user = trim($user); | ||||||
|         $this->sessionId = $sessionId; |         $this->sessionId = trim($sessionId); | ||||||
|         $this->serverId = $serverId; |         $this->serverId = trim($serverId); | ||||||
|  |  | ||||||
|         $this->parseSessionId($this->sessionId); |         $this->parseSessionId($this->sessionId); | ||||||
|     } |     } | ||||||
| @@ -24,23 +22,19 @@ class LegacyJoin extends BaseJoin { | |||||||
|         return $this->accessToken; |         return $this->accessToken; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getSelectedProfile() : string { |     public function getSelectedProfile(): string { | ||||||
|         return $this->uuid ?: $this->user; |         return $this->uuid ?: $this->user; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getServerId() : string { |     public function getServerId(): string { | ||||||
|         return $this->serverId; |         return $this->serverId; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * @return bool |      * @return bool | ||||||
|      */ |      */ | ||||||
|     public function validate() : bool { |     public function validate(): bool { | ||||||
|         $validator = new RequiredValidator(); |         return !$this->isEmpty($this->accessToken) && !$this->isEmpty($this->user) && !$this->isEmpty($this->serverId); | ||||||
|  |  | ||||||
|         return $validator->validate($this->accessToken) |  | ||||||
|             && $validator->validate($this->user) |  | ||||||
|             && $validator->validate($this->serverId); |  | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
| @@ -50,7 +44,7 @@ class LegacyJoin extends BaseJoin { | |||||||
|      * Бьём по ':' для учёта авторизации в современных лаунчерах и входе на более старую |      * Бьём по ':' для учёта авторизации в современных лаунчерах и входе на более старую | ||||||
|      * версию игры. Там sessionId передаётся как "token:{accessToken}:{uuid}", так что это нужно обработать |      * версию игры. Там sessionId передаётся как "token:{accessToken}:{uuid}", так что это нужно обработать | ||||||
|      */ |      */ | ||||||
|     protected function parseSessionId(string $sessionId) { |     private function parseSessionId(string $sessionId) { | ||||||
|         $parts = explode(':', $sessionId); |         $parts = explode(':', $sessionId); | ||||||
|         if (count($parts) === 3) { |         if (count($parts) === 3) { | ||||||
|             $this->accessToken = $parts[1]; |             $this->accessToken = $parts[1]; | ||||||
|   | |||||||
| @@ -1,8 +1,6 @@ | |||||||
| <?php | <?php | ||||||
| namespace api\modules\session\models\protocols; | namespace api\modules\session\models\protocols; | ||||||
|  |  | ||||||
| use yii\validators\RequiredValidator; |  | ||||||
|  |  | ||||||
| class ModernJoin extends BaseJoin { | class ModernJoin extends BaseJoin { | ||||||
|  |  | ||||||
|     private $accessToken; |     private $accessToken; | ||||||
| @@ -10,29 +8,25 @@ class ModernJoin extends BaseJoin { | |||||||
|     private $serverId; |     private $serverId; | ||||||
|  |  | ||||||
|     public function __construct(string $accessToken, string $selectedProfile, string $serverId) { |     public function __construct(string $accessToken, string $selectedProfile, string $serverId) { | ||||||
|         $this->accessToken = $accessToken; |         $this->accessToken = trim($accessToken); | ||||||
|         $this->selectedProfile = $selectedProfile; |         $this->selectedProfile = trim($selectedProfile); | ||||||
|         $this->serverId = $serverId; |         $this->serverId = trim($serverId); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getAccessToken() : string { |     public function getAccessToken(): string { | ||||||
|         return $this->accessToken; |         return $this->accessToken; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getSelectedProfile() : string { |     public function getSelectedProfile(): string { | ||||||
|         return $this->selectedProfile; |         return $this->selectedProfile; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getServerId() : string { |     public function getServerId(): string { | ||||||
|         return $this->serverId; |         return $this->serverId; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function validate() : bool { |     public function validate(): bool { | ||||||
|         $validator = new RequiredValidator(); |         return !$this->isEmpty($this->accessToken) && !$this->isEmpty($this->selectedProfile) && !$this->isEmpty($this->serverId); | ||||||
|  |  | ||||||
|         return $validator->validate($this->accessToken) |  | ||||||
|             && $validator->validate($this->selectedProfile) |  | ||||||
|             && $validator->validate($this->serverId); |  | ||||||
|     } |     } | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -7,29 +7,18 @@ trait AccountFinder { | |||||||
|  |  | ||||||
|     private $account; |     private $account; | ||||||
|  |  | ||||||
|     public abstract function getLogin(); |     public abstract function getLogin(): string; | ||||||
|  |  | ||||||
|     /** |     public function getAccount(): ?Account { | ||||||
|      * @return Account|null |  | ||||||
|      */ |  | ||||||
|     public function getAccount() { |  | ||||||
|         if ($this->account === null) { |         if ($this->account === null) { | ||||||
|             $className = $this->getAccountClassName(); |             $this->account = Account::findOne([$this->getLoginAttribute() => $this->getLogin()]); | ||||||
|             $this->account = $className::findOne([$this->getLoginAttribute() => $this->getLogin()]); |  | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         return $this->account; |         return $this->account; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getLoginAttribute() { |     public function getLoginAttribute(): string { | ||||||
|         return strpos($this->getLogin(), '@') ? 'email' : 'username'; |         return strpos($this->getLogin(), '@') ? 'email' : 'username'; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * @return Account|string |  | ||||||
|      */ |  | ||||||
|     protected function getAccountClassName() { |  | ||||||
|         return Account::class; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -3,7 +3,6 @@ namespace api\validators; | |||||||
|  |  | ||||||
| use common\helpers\Error as E; | use common\helpers\Error as E; | ||||||
| use common\models\Account; | use common\models\Account; | ||||||
| use Yii; |  | ||||||
| use yii\base\InvalidConfigException; | use yii\base\InvalidConfigException; | ||||||
| use yii\validators\Validator; | use yii\validators\Validator; | ||||||
|  |  | ||||||
| @@ -21,10 +20,6 @@ class PasswordRequiredValidator extends Validator { | |||||||
|  |  | ||||||
|     public function init() { |     public function init() { | ||||||
|         parent::init(); |         parent::init(); | ||||||
|         if ($this->account === null) { |  | ||||||
|             $this->account = Yii::$app->user->identity; |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         if (!$this->account instanceof Account) { |         if (!$this->account instanceof Account) { | ||||||
|             throw new InvalidConfigException('account should be instance of ' . Account::class); |             throw new InvalidConfigException('account should be instance of ' . Account::class); | ||||||
|         } |         } | ||||||
|   | |||||||
| @@ -32,7 +32,6 @@ abstract class BaseApplication extends yii\base\Application { | |||||||
|  * Include only Web application related components here |  * Include only Web application related components here | ||||||
|  * |  * | ||||||
|  * @property \api\components\User\Component      $user User component. |  * @property \api\components\User\Component      $user User component. | ||||||
|  * @property \api\components\ApiUser\Component   $apiUser Api User component. |  | ||||||
|  * @property \api\components\ReCaptcha\Component $reCaptcha |  * @property \api\components\ReCaptcha\Component $reCaptcha | ||||||
|  * |  * | ||||||
|  * @method \api\components\User\Component getUser() |  * @method \api\components\User\Component getUser() | ||||||
|   | |||||||
| @@ -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 { | class Key { | ||||||
|  |  | ||||||
|     protected $key; |     private $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; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     public function __construct(...$key) { |     public function __construct(...$key) { | ||||||
|         if (empty($key)) { |         if (empty($key)) { | ||||||
| @@ -55,7 +16,43 @@ class Key { | |||||||
|         $this->key = $this->buildKey($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 = []; |         $keyParts = []; | ||||||
|         foreach($parts as $part) { |         foreach($parts as $part) { | ||||||
|             $keyParts[] = str_replace('_', ':', $part); |             $keyParts[] = str_replace('_', ':', $part); | ||||||
|   | |||||||
| @@ -6,34 +6,34 @@ use IteratorAggregate; | |||||||
|  |  | ||||||
| class Set extends Key implements IteratorAggregate { | class Set extends Key implements IteratorAggregate { | ||||||
|  |  | ||||||
|     public function add($value) { |     public function add($value): self { | ||||||
|         $this->getRedis()->sadd($this->key, $value); |         $this->getRedis()->sadd($this->getKey(), $value); | ||||||
|         return $this; |         return $this; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function remove($value) { |     public function remove($value): self { | ||||||
|         $this->getRedis()->srem($this->key, $value); |         $this->getRedis()->srem($this->getKey(), $value); | ||||||
|         return $this; |         return $this; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function members() { |     public function members(): array { | ||||||
|         return $this->getRedis()->smembers($this->key); |         return $this->getRedis()->smembers($this->getKey()); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getValue() { |     public function getValue(): array { | ||||||
|         return $this->members(); |         return $this->members(); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function exists(string $value = null) : bool { |     public function exists(string $value = null): bool { | ||||||
|         if ($value === null) { |         if ($value === null) { | ||||||
|             return parent::exists(); |             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) { |     public function diff(array $sets): array { | ||||||
|         return $this->getRedis()->sdiff([$this->key, implode(' ', $sets)]); |         return $this->getRedis()->sdiff([$this->getKey(), implode(' ', $sets)]); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|   | |||||||
| @@ -1,7 +1,7 @@ | |||||||
| <?php | <?php | ||||||
| return [ | return [ | ||||||
|     'version' => '1.1.18-dev', |     'version' => '1.1.18-dev', | ||||||
|     'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', |     'vendorPath' => dirname(__DIR__, 2) . '/vendor', | ||||||
|     'components' => [ |     'components' => [ | ||||||
|         'cache' => [ |         'cache' => [ | ||||||
|             'class' => common\components\Redis\Cache::class, |             'class' => common\components\Redis\Cache::class, | ||||||
| @@ -72,6 +72,11 @@ return [ | |||||||
|         'oauth' => [ |         'oauth' => [ | ||||||
|             'class' => api\components\OAuth2\Component::class, |             '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' => [ |     'container' => [ | ||||||
|         'definitions' => [ |         'definitions' => [ | ||||||
|   | |||||||
| @@ -51,27 +51,18 @@ class Account extends ActiveRecord { | |||||||
|     const PASS_HASH_STRATEGY_OLD_ELY = 0; |     const PASS_HASH_STRATEGY_OLD_ELY = 0; | ||||||
|     const PASS_HASH_STRATEGY_YII2 = 1; |     const PASS_HASH_STRATEGY_YII2 = 1; | ||||||
|  |  | ||||||
|     public static function tableName() { |     public static function tableName(): string { | ||||||
|         return '{{%accounts}}'; |         return '{{%accounts}}'; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function behaviors() { |     public function behaviors(): array { | ||||||
|         return [ |         return [ | ||||||
|             TimestampBehavior::class, |             TimestampBehavior::class, | ||||||
|         ]; |         ]; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     public function validatePassword(string $password, int $passwordHashStrategy = null): bool { | ||||||
|      * Validates password |         if ($passwordHashStrategy === null) { | ||||||
|      * |  | ||||||
|      * @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) { |  | ||||||
|             $passwordHashStrategy = $this->password_hash_strategy; |             $passwordHashStrategy = $this->password_hash_strategy; | ||||||
|         } |         } | ||||||
|  |  | ||||||
| @@ -88,17 +79,13 @@ class Account extends ActiveRecord { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     public function setPassword(string $password): void { | ||||||
|      * @param string $password |  | ||||||
|      * @throws InvalidConfigException |  | ||||||
|      */ |  | ||||||
|     public function setPassword($password) { |  | ||||||
|         $this->password_hash_strategy = self::PASS_HASH_STRATEGY_YII2; |         $this->password_hash_strategy = self::PASS_HASH_STRATEGY_YII2; | ||||||
|         $this->password_hash = Yii::$app->security->generatePasswordHash($password); |         $this->password_hash = Yii::$app->security->generatePasswordHash($password); | ||||||
|         $this->password_changed_at = time(); |         $this->password_changed_at = time(); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getEmailActivations() { |     public function getEmailActivations(): ActiveQuery { | ||||||
|         return $this->hasMany(EmailActivation::class, ['account_id' => 'id']); |         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']); |         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']); |         return $this->hasMany(UsernameHistory::class, ['account_id' => 'id']); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getSessions() { |     public function getSessions(): ActiveQuery { | ||||||
|         return $this->hasMany(AccountSession::class, ['account_id' => 'id']); |         return $this->hasMany(AccountSession::class, ['account_id' => 'id']); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     public function getMinecraftAccessKeys() { |     public function getMinecraftAccessKeys(): ActiveQuery { | ||||||
|         return $this->hasMany(MinecraftAccessKey::class, ['account_id' => 'id']); |         return $this->hasMany(MinecraftAccessKey::class, ['account_id' => 'id']); | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -123,7 +110,7 @@ class Account extends ActiveRecord { | |||||||
|      * |      * | ||||||
|      * @return bool |      * @return bool | ||||||
|      */ |      */ | ||||||
|     public function hasMojangUsernameCollision() : bool { |     public function hasMojangUsernameCollision(): bool { | ||||||
|         return MojangUsername::find() |         return MojangUsername::find() | ||||||
|             ->andWhere(['username' => $this->username]) |             ->andWhere(['username' => $this->username]) | ||||||
|             ->exists(); |             ->exists(); | ||||||
| @@ -136,7 +123,7 @@ class Account extends ActiveRecord { | |||||||
|      * |      * | ||||||
|      * @return string |      * @return string | ||||||
|      */ |      */ | ||||||
|     public function getProfileLink() : string { |     public function getProfileLink(): string { | ||||||
|         return 'http://ely.by/u' . $this->id; |         return 'http://ely.by/u' . $this->id; | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -148,15 +135,15 @@ class Account extends ActiveRecord { | |||||||
|      * |      * | ||||||
|      * @return bool |      * @return bool | ||||||
|      */ |      */ | ||||||
|     public function isAgreedWithActualRules() : bool { |     public function isAgreedWithActualRules(): bool { | ||||||
|         return $this->rules_agreement_version === LATEST_RULES_VERSION; |         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); |         $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); |         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; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
| } |  | ||||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user