Объединены сущности для авторизации посредством JWT токенов и токенов, выданных через oAuth2.

Все действия, связанные с аккаунтами, теперь вызываются через url `/api/v1/accounts/<id>/<action>`.
Добавлена вменяемая система разграничения прав на основе RBAC.
Теперь oAuth2 токены генерируются как случайная строка в 40 символов длинной, а не UUID.
Исправлен баг с неправильным временем жизни токена в ответе успешного запроса аутентификации.
Теперь все unit тесты можно успешно прогнать без наличия интернета.
This commit is contained in:
ErickSkrauch 2017-09-19 20:06:16 +03:00
parent 928b3aa7fc
commit dd2c4bc413
173 changed files with 2719 additions and 2748 deletions

View File

@ -1,8 +0,0 @@
<?php
namespace api\components\ApiUser;
class AccessControl extends \yii\filters\AccessControl {
public $user = 'apiUser';
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -2,9 +2,10 @@
namespace api\components\OAuth2;
use api\components\OAuth2\Storage;
use api\components\OAuth2\Utils\KeyAlgorithm\UuidAlgorithm;
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;
/**
@ -34,11 +35,21 @@ class Component extends BaseComponent {
$authServer->addGrantType(new Grants\ClientCredentialsGrant());
$this->_authServer = $authServer;
SecureKey::setAlgorithm(new UuidAlgorithm());
}
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();
}
}

View File

@ -6,7 +6,7 @@ use api\components\OAuth2\Entities\AuthCodeEntity;
use api\components\OAuth2\Entities\ClientEntity;
use api\components\OAuth2\Entities\RefreshTokenEntity;
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\ClientEntity as BaseClientEntity;
use League\OAuth2\Server\Event\ClientAuthenticationFailedEvent;
@ -178,7 +178,7 @@ class AuthCodeGrant extends AbstractGrant {
// Generate the access token
$accessToken = new AccessTokenEntity($this->server);
$accessToken->setId(SecureKey::generate()); // TODO: generate code based on permissions
$accessToken->setId(SecureKey::generate());
$accessToken->setExpireTime($this->getAccessTokenTTL() + time());
foreach ($authCodeScopes as $authCodeScope) {
@ -194,7 +194,7 @@ class AuthCodeGrant extends AbstractGrant {
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
// Выдаём refresh_token, если запрошен offline_access
if (isset($accessToken->getScopes()[OauthScope::OFFLINE_ACCESS])) {
if (isset($accessToken->getScopes()[ScopeStorage::OFFLINE_ACCESS])) {
/** @var RefreshTokenGrant $refreshTokenGrant */
$refreshTokenGrant = $this->server->getGrantType('refresh_token');
$refreshToken = new RefreshTokenEntity($this->server);
@ -223,12 +223,12 @@ class AuthCodeGrant extends AbstractGrant {
* Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые.
*
* @param string $scopeParam
* @param ClientEntity $client
* @param BaseClientEntity $client
* @param string $redirectUri
*
* @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);
return parent::validateScopes($scopes, $client, $redirectUri);
}

View File

@ -18,14 +18,12 @@ class ClientCredentialsGrant extends AbstractGrant {
* @throws \League\OAuth2\Server\Exception\OAuthException
*/
public function completeFlow(): array {
// Get the required params
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
if ($clientId === null) {
throw new Exception\InvalidRequestException('client_id');
}
$clientSecret = $this->server->getRequest()->request->get('client_secret',
$this->server->getRequest()->getPassword());
$clientSecret = $this->server->getRequest()->request->get('client_secret');
if ($clientSecret === null) {
throw new Exception\InvalidRequestException('client_secret');
}
@ -74,12 +72,12 @@ class ClientCredentialsGrant extends AbstractGrant {
* Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые.
*
* @param string $scopeParam
* @param ClientEntity $client
* @param BaseClientEntity $client
* @param string $redirectUri
*
* @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);
return parent::validateScopes($scopes, $client, $redirectUri);
}

View File

@ -51,12 +51,12 @@ class RefreshTokenGrant extends AbstractGrant {
* Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые.
*
* @param string $scopeParam
* @param ClientEntity $client
* @param BaseClientEntity $client
* @param string $redirectUri
*
* @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);
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
$newAccessToken = new AccessTokenEntity($this->server);
$newAccessToken->setId(SecureKey::generate()); // TODO: generate based on permissions
$newAccessToken->setId(SecureKey::generate());
$newAccessToken->setExpireTime($this->getAccessTokenTTL() + time());
$newAccessToken->setSession($session);

View File

@ -3,46 +3,84 @@ namespace api\components\OAuth2\Storage;
use api\components\OAuth2\Entities\ClientEntity;
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\ScopeInterface;
use yii\base\ErrorException;
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) {
$query = OauthScope::find();
public function get($scope, $grantType = null, $clientId = null): ?ScopeEntity {
$permission = $this->convertToInternalPermission($scope);
if ($grantType === 'authorization_code') {
$query->onlyPublic()->usersScopes();
$permissions = self::AUTHORIZATION_CODE_PERMISSIONS;
} elseif ($grantType === 'client_credentials') {
$query->machineScopes();
$permissions = self::CLIENT_CREDENTIALS_PERMISSIONS;
$isTrusted = false;
if ($clientId !== null) {
/** @var ClientEntity $client */
$client = $this->server->getClientStorage()->get($clientId);
if (!$client instanceof ClientEntity) {
throw new ErrorException('client storage must return instance of ' . ClientEntity::class);
}
Assert::that($client)->isInstanceOf(ClientEntity::class);
$isTrusted = $client->isTrusted();
}
if (!$isTrusted) {
$query->onlyPublic();
if ($isTrusted) {
$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($scope, $scopes, true)) {
if (!in_array($permission, $permissions, true)) {
return null;
}
$entity = new ScopeEntity($this->server);
$entity->setId($scope);
$entity->setId($permission);
return $entity;
}
private function convertToInternalPermission(string $publicScope): string {
return self::PUBLIC_SCOPES_TO_INTERNAL_PERMISSIONS[$publicScope] ?? $publicScope;
}
}

View File

@ -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();
}
}

View 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;
}
}

View File

@ -1,8 +1,10 @@
<?php
namespace api\components\User;
use api\models\AccountIdentity;
use api\exceptions\ThisShouldNotHappenException;
use common\models\Account;
use common\models\AccountSession;
use common\rbac\Roles as R;
use DateInterval;
use DateTime;
use Emarref\Jwt\Algorithm\AlgorithmInterface;
@ -10,34 +12,33 @@ use Emarref\Jwt\Algorithm\Hs256;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Token;
use Emarref\Jwt\Verification\Context as VerificationContext;
use Exception;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidConfigException;
use yii\web\IdentityInterface;
use yii\web\User as YiiUserComponent;
/**
* @property AccountSession|null $activeSession
* @property AccountIdentity|null $identity
* @property IdentityInterface|null $identity
*
* @method AccountIdentity|null loginByAccessToken($token, $type = null)
* @method AccountIdentity|null getIdentity($autoRenew = true)
* @method IdentityInterface|null loginByAccessToken($token, $type = null)
* @method IdentityInterface|null getIdentity($autoRenew = true)
*/
class Component extends YiiUserComponent {
const TERMINATE_MINECRAFT_SESSIONS = 1;
const TERMINATE_SITE_SESSIONS = 2;
const DO_NOT_TERMINATE_CURRENT_SESSION = 4;
const TERMINATE_ALL = self::TERMINATE_MINECRAFT_SESSIONS | self::TERMINATE_SITE_SESSIONS;
const KEEP_MINECRAFT_SESSIONS = 1;
const KEEP_SITE_SESSIONS = 2;
const KEEP_CURRENT_SESSION = 4;
const JWT_SUBJECT_PREFIX = 'ely|';
public $enableSession = false;
public $loginUrl = null;
public $identityClass = AccountIdentity::class;
public $identityClass = Identity::class;
public $secret;
@ -45,6 +46,11 @@ class Component extends YiiUserComponent {
public $sessionTimeout = 'P7D';
/**
* @var Token[]
*/
private static $parsedTokensCache = [];
public function init() {
parent::init();
if (!$this->secret) {
@ -52,72 +58,60 @@ class Component extends YiiUserComponent {
}
}
/**
* @param IdentityInterface $identity
* @param bool $rememberMe
*
* @return LoginResult|bool
* @throws ErrorException
*/
public function login(IdentityInterface $identity, $rememberMe = false) {
if (!$this->beforeLogin($identity, false, $rememberMe)) {
return false;
public function findIdentityByAccessToken(string $accessToken): ?IdentityInterface {
/** @var \api\components\User\IdentityInterface|string $identityClass */
$identityClass = $this->identityClass;
try {
return $identityClass::findIdentityByAccessToken($accessToken);
} catch (Exception $e) {
Yii::error($e);
return null;
}
}
$this->switchIdentity($identity, 0);
$id = $identity->getId();
public function createJwtAuthenticationToken(Account $account, bool $rememberMe): AuthenticationResult {
$ip = Yii::$app->request->userIP;
$token = $this->createToken($identity);
$token = $this->createToken($account);
if ($rememberMe) {
$session = new AccountSession();
$session->account_id = $id;
$session->account_id = $account->id;
$session->setIp($ip);
$session->generateRefreshToken();
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 {
$session = null;
// Если мы не сохраняем сессию, то токен должен жить подольше, чтобы
// не прогорала сессия во время работы с аккаунтом
// Если мы не сохраняем сессию, то токен должен жить подольше,
// чтобы не прогорала сессия во время работы с аккаунтом
$token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout))));
}
$jwt = $this->serializeToken($token);
Yii::info("User '{$id}' logged in from {$ip}.", __METHOD__);
$result = new LoginResult($identity, $jwt, $session);
$this->afterLogin($identity, false, $rememberMe);
return $result;
return new AuthenticationResult($account, $jwt, $session);
}
public function renew(AccountSession $session): RenewResult {
$account = $session->account;
public function renewJwtAuthenticationToken(AccountSession $session): AuthenticationResult {
$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);
$session->last_refreshed_at = time();
if (!$session->save()) {
throw new ErrorException('Cannot update session info');
}
$result = new AuthenticationResult($account, $jwt, $session);
$transaction->commit();
} catch (ErrorException $e) {
$transaction->rollBack();
throw $e;
$session->setIp(Yii::$app->request->userIP);
$session->last_refreshed_at = time();
if (!$session->save()) {
throw new ThisShouldNotHappenException('Cannot update session info');
}
$transaction->commit();
return $result;
}
@ -126,15 +120,22 @@ class Component extends YiiUserComponent {
* @return Token распаршенный токен
* @throws VerificationException если один из Claims не пройдёт проверку
*/
public function parseToken(string $jwtString) : Token {
$hostInfo = Yii::$app->request->hostInfo;
public function parseToken(string $jwtString): Token {
$token = &self::$parsedTokensCache[$jwtString];
if ($token === null) {
$hostInfo = Yii::$app->request->hostInfo;
$jwt = new Jwt();
$token = $jwt->deserialize($jwtString);
$context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm()));
$context->setAudience($hostInfo);
$context->setIssuer($hostInfo);
$jwt->verify($token, $context);
$jwt = new Jwt();
$notVerifiedToken = $jwt->deserialize($jwtString);
$context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm()));
$context->setAudience($hostInfo);
$context->setIssuer($hostInfo);
$context->setSubject(self::JWT_SUBJECT_PREFIX);
$jwt->verify($notVerifiedToken, $context);
$token = $notVerifiedToken;
}
return $token;
}
@ -150,19 +151,23 @@ class Component extends YiiUserComponent {
*
* @return AccountSession|null
*/
public function getActiveSession() {
public function getActiveSession(): ?AccountSession {
if ($this->getIsGuest()) {
return null;
}
$bearer = $this->getBearerToken();
if ($bearer === null) {
return null;
}
try {
$token = $this->parseToken($bearer);
} catch (VerificationException $e) {
return null;
}
$sessionId = $token->getPayload()->findClaimByName(SessionIdClaim::NAME);
$sessionId = $token->getPayload()->findClaimByName(Claim\JwtId::NAME);
if ($sessionId === null) {
return null;
}
@ -170,35 +175,38 @@ class Component extends YiiUserComponent {
return AccountSession::findOne($sessionId->getValue());
}
public function terminateSessions(int $mode = self::TERMINATE_ALL | self::DO_NOT_TERMINATE_CURRENT_SESSION): void {
$identity = $this->getIdentity();
$activeSession = ($mode & self::DO_NOT_TERMINATE_CURRENT_SESSION) ? $this->getActiveSession() : null;
if ($mode & self::TERMINATE_SITE_SESSIONS) {
foreach ($identity->sessions as $session) {
if ($activeSession === null || $activeSession->id !== $session->id) {
public function terminateSessions(Account $account, int $mode = 0): void {
$currentSession = null;
if ($mode & self::KEEP_CURRENT_SESSION) {
$currentSession = $this->getActiveSession();
}
if (!($mode & self::KEEP_SITE_SESSIONS)) {
foreach ($account->sessions as $session) {
if ($currentSession === null || $currentSession->id !== $session->id) {
$session->delete();
}
}
}
if ($mode & self::TERMINATE_MINECRAFT_SESSIONS) {
foreach ($identity->minecraftAccessKeys as $minecraftAccessKey) {
if (!($mode & self::KEEP_MINECRAFT_SESSIONS)) {
foreach ($account->minecraftAccessKeys as $minecraftAccessKey) {
$minecraftAccessKey->delete();
}
}
}
public function getAlgorithm() : AlgorithmInterface {
public function getAlgorithm(): AlgorithmInterface {
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()));
}
protected function createToken(IdentityInterface $identity) : Token {
protected function createToken(Account $account): Token {
$token = new Token();
foreach($this->getClaims($identity) as $claim) {
foreach($this->getClaims($account) as $claim) {
$token->addClaim($claim);
}
@ -206,25 +214,23 @@ class Component extends YiiUserComponent {
}
/**
* @param IdentityInterface $identity
* @param Account $account
* @return Claim\AbstractClaim[]
*/
protected function getClaims(IdentityInterface $identity) {
protected function getClaims(Account $account): array {
$currentTime = new DateTime();
$hostInfo = Yii::$app->request->hostInfo;
return [
new ScopesClaim([R::ACCOUNTS_WEB_USER]),
new Claim\Audience($hostInfo),
new Claim\Issuer($hostInfo),
new Claim\IssuedAt($currentTime),
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() {
$authHeader = Yii::$app->request->getHeaders()->get('Authorization');
if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {

View File

@ -1,20 +1,15 @@
<?php
namespace api\components\ApiUser;
namespace api\components\User;
use api\components\OAuth2\Entities\AccessTokenEntity;
use common\models\Account;
use common\models\OauthClient;
use common\models\OauthSession;
use Yii;
use yii\base\NotSupportedException;
use yii\web\IdentityInterface;
use yii\web\UnauthorizedHttpException;
/**
* @property Account $account
* @property OauthClient $client
* @property OauthSession $session
* @property AccessTokenEntity $accessToken
* @property Account $account
*/
class Identity implements IdentityInterface {
@ -25,44 +20,43 @@ class Identity implements IdentityInterface {
/**
* @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 */
$model = Yii::$app->oauth->getAuthServer()->getAccessTokenStorage()->get($token);
$model = Yii::$app->oauth->getAccessTokenStorage()->get($token);
if ($model === null) {
throw new UnauthorizedHttpException('Incorrect token');
} elseif ($model->isExpired()) {
}
if ($model->isExpired()) {
throw new UnauthorizedHttpException('Token expired');
}
return new static($model);
}
private function __construct(AccessTokenEntity $accessToken) {
$this->_accessToken = $accessToken;
}
public function getAccount(): Account {
public function getAccount(): ?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;
}
/**
* Этот метод используется для получения токена, к которому привязаны права.
* У нас права привязываются к токенам, так что возвращаем именно его id.
* @inheritdoc
* @return string[]
*/
public function getAssignedPermissions(): array {
return array_keys($this->_accessToken->getScopes());
}
public function getId(): string {
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');
}
private function __construct(AccessTokenEntity $accessToken) {
$this->_accessToken = $accessToken;
}
private function getSession(): OauthSession {
return OauthSession::findOne($this->_accessToken->getSessionId());
}
}

View 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;
}

View 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;
}
}

View 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;
}
}

View File

@ -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;
}
}

View File

@ -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(),
];
}
}

View 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;
}
}

View File

@ -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;
}
}

View 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;
}
}
}

View File

@ -15,9 +15,6 @@ return [
'class' => api\components\User\Component::class,
'secret' => getenv('JWT_USER_SECRET'),
],
'apiUser' => [
'class' => api\components\ApiUser\Component::class,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
@ -85,14 +82,9 @@ return [
'class' => api\modules\authserver\Module::class,
'host' => $params['authserverHost'],
],
'session' => [
'class' => api\modules\session\Module::class,
],
'mojang' => [
'class' => api\modules\mojang\Module::class,
],
'internal' => [
'class' => api\modules\internal\Module::class,
],
'session' => api\modules\session\Module::class,
'mojang' => api\modules\mojang\Module::class,
'internal' => api\modules\internal\Module::class,
'accounts' => api\modules\accounts\Module::class,
],
];

View File

@ -3,15 +3,16 @@
* @var array $params
*/
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>',
'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',
'/minecraft/session/join' => 'session/session/join',

View File

@ -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,
];
}
}

View File

@ -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;
}
}

View File

@ -14,7 +14,7 @@ use yii\helpers\ArrayHelper;
class AuthenticationController extends Controller {
public function behaviors() {
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'only' => ['logout'],
@ -139,9 +139,12 @@ class AuthenticationController extends Controller {
];
}
$response = $result->getAsResponse();
unset($response['refresh_token']);
return array_merge([
'success' => true,
], $result->getAsResponse());
], $response);
}
}

View File

@ -12,7 +12,7 @@ use yii\filters\auth\HttpBearerAuth;
*/
class Controller extends \yii\rest\Controller {
public function behaviors() {
public function behaviors(): array {
$parentBehaviors = parent::behaviors();
// Добавляем авторизатор для входа по jwt токенам
$parentBehaviors['authenticator'] = [

View File

@ -7,7 +7,7 @@ use yii\helpers\ArrayHelper;
class FeedbackController extends Controller {
public function behaviors() {
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'optional' => ['index'],

View File

@ -1,14 +1,15 @@
<?php
namespace api\controllers;
use api\components\ApiUser\AccessControl;
use common\models\OauthScope as S;
use api\models\OauthAccountInfo;
use common\rbac\Permissions as P;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
class IdentityInfoController extends ApiController {
class IdentityInfoController extends Controller {
public function behaviors() {
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [
'access' => [
'class' => AccessControl::class,
@ -16,29 +17,22 @@ class IdentityInfoController extends ApiController {
[
'actions' => ['index'],
'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() {
$account = Yii::$app->apiUser->getIdentity()->getAccount();
$response = [
'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;
public function actionIndex(): array {
/** @noinspection NullPointerExceptionInspection */
return (new OauthAccountInfo(Yii::$app->user->getIdentity()->getAccount()))->info();
}
}

View File

@ -1,8 +1,8 @@
<?php
namespace api\controllers;
use api\filters\ActiveUserRule;
use api\models\OauthProcess;
use common\rbac\Permissions as P;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
@ -19,8 +19,14 @@ class OauthController extends Controller {
'only' => ['complete'],
'rules' => [
[
'class' => ActiveUserRule::class,
'allow' => true,
'actions' => ['complete'],
'roles' => [P::COMPLETE_OAUTH_FLOW],
'roleParams' => function() {
return [
'accountId' => Yii::$app->user->identity->getAccount()->id,
];
},
],
],
],

View File

@ -7,7 +7,7 @@ use yii\helpers\ArrayHelper;
class OptionsController extends Controller {
public function behaviors() {
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'except' => ['index'],

View File

@ -11,7 +11,7 @@ use yii\helpers\ArrayHelper;
class SignupController extends Controller {
public function behaviors() {
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'except' => ['index', 'repeat-message', 'confirm'],

View File

@ -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,
];
}
}

View File

@ -6,6 +6,6 @@ namespace api\exceptions;
* но теоретически может произойти. Целью является отлавливание таких участков и доработка логики,
* если такие ситуации всё же будут иметь место случаться.
*/
class ThisShouldNotHaveHappenedException extends Exception {
class ThisShouldNotHappenException extends Exception {
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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');
}
}

View 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;
}
}

View File

@ -83,7 +83,7 @@ class OauthProcess {
try {
$grant = $this->getAuthorizationCodeGrant();
$authParams = $grant->checkAuthorizeParams();
$account = Yii::$app->user->identity;
$account = Yii::$app->user->identity->getAccount();
/** @var \common\models\OauthClient $clientModel */
$clientModel = OauthClient::findOne($authParams->getClient()->getId());

View File

@ -1,9 +1,8 @@
<?php
namespace api\models\authentication;
use api\models\AccountIdentity;
use api\models\base\ApiForm;
use api\models\profile\ChangeUsernameForm;
use api\modules\accounts\models\ChangeUsernameForm;
use api\validators\EmailActivationKeyValidator;
use common\models\Account;
use common\models\EmailActivation;
@ -14,14 +13,14 @@ class ConfirmEmailForm extends ApiForm {
public $key;
public function rules() {
public function rules(): array {
return [
['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION],
];
}
/**
* @return \api\components\User\LoginResult|bool
* @return \api\components\User\AuthenticationResult|bool
* @throws ErrorException
*/
public function confirm() {
@ -48,7 +47,7 @@ class ConfirmEmailForm extends ApiForm {
$transaction->commit();
return Yii::$app->user->login(new AccountIdentity($account->attributes), true);
return Yii::$app->user->createJwtAuthenticationToken($account, true);
}
}

View File

@ -101,7 +101,7 @@ class ForgotPasswordForm extends ApiForm {
return true;
}
public function getLogin() {
public function getLogin(): string {
return $this->login;
}

View File

@ -1,7 +1,6 @@
<?php
namespace api\models\authentication;
use api\models\AccountIdentity;
use api\models\base\ApiForm;
use api\validators\TotpValidator;
use common\helpers\Error as E;
@ -9,9 +8,6 @@ use api\traits\AccountFinder;
use common\models\Account;
use Yii;
/**
* @method AccountIdentity|null getAccount()
*/
class LoginForm extends ApiForm {
use AccountFinder;
@ -86,12 +82,12 @@ class LoginForm extends ApiForm {
}
}
public function getLogin() {
public function getLogin(): string {
return $this->login;
}
/**
* @return \api\components\User\LoginResult|bool
* @return \api\components\User\AuthenticationResult|bool
*/
public function login() {
if (!$this->validate()) {
@ -104,11 +100,7 @@ class LoginForm extends ApiForm {
$account->save();
}
return Yii::$app->user->login($account, $this->rememberMe);
}
protected function getAccountClassName() {
return AccountIdentity::class;
return Yii::$app->user->createJwtAuthenticationToken($account, $this->rememberMe);
}
}

View File

@ -1,7 +1,6 @@
<?php
namespace api\models\authentication;
use api\models\AccountIdentity;
use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator;
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
*/
public function recoverPassword() {
@ -61,7 +60,7 @@ class RecoverPasswordForm extends ApiForm {
$transaction->commit();
return Yii::$app->user->login(new AccountIdentity($account->attributes), false);
return Yii::$app->user->createJwtAuthenticationToken($account, false);
}
}

View File

@ -32,7 +32,7 @@ class RefreshTokenForm extends ApiForm {
}
/**
* @return \api\components\User\RenewResult|bool
* @return \api\components\User\AuthenticationResult|bool
*/
public function renew() {
if (!$this->validate()) {
@ -42,7 +42,7 @@ class RefreshTokenForm extends ApiForm {
/** @var \api\components\User\Component $component */
$component = Yii::$app->user;
return $component->renew($this->getSession());
return $component->renewJwtAuthenticationToken($this->getSession());
}
/**

View 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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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, '#');
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace api\modules\accounts;
use yii\base\Module as BaseModule;
class Module extends BaseModule {
public $id = 'accounts';
}

View 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;
}
}

View 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;
}
}

View 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;
}
}

View 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,
];
}
}

View 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;
}
}

View 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;
}
}

View 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;
}
}

View 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;
}
}

View 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,
];
}
}

View 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;
}
}

View 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;
}
}

View 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;
}
}

View 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;
}
}

View 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;
}
}

View 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;
}

View 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;
}
}

View File

@ -1,7 +1,6 @@
<?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 common\helpers\Amqp;
use common\models\Account;
@ -10,7 +9,7 @@ use PhpAmqpLib\Message\AMQPMessage;
use Yii;
use yii\base\ErrorException;
class BanForm extends ApiForm {
class BanAccountForm extends AccountActionForm {
public const DURATION_FOREVER = -1;
@ -31,11 +30,6 @@ class BanForm extends ApiForm {
*/
public $message = '';
/**
* @var Account
*/
private $account;
public function rules(): array {
return [
[['duration'], 'integer', 'min' => self::DURATION_FOREVER],
@ -44,24 +38,20 @@ class BanForm extends ApiForm {
];
}
public function getAccount(): Account {
return $this->account;
}
public function validateAccountActivity() {
if ($this->account->status === Account::STATUS_BANNED) {
if ($this->getAccount()->status === Account::STATUS_BANNED) {
$this->addError('account', E::ACCOUNT_ALREADY_BANNED);
}
}
public function ban(): bool {
public function performAction(): bool {
if (!$this->validate()) {
return false;
}
$transaction = Yii::$app->db->beginTransaction();
$account = $this->account;
$account = $this->getAccount();
$account->status = Account::STATUS_BANNED;
if (!$account->save()) {
throw new ErrorException('Cannot ban account');
@ -76,7 +66,7 @@ class BanForm extends ApiForm {
public function createTask(): void {
$model = new AccountBanned();
$model->accountId = $this->account->id;
$model->accountId = $this->getAccount()->id;
$model->duration = $this->duration;
$model->message = $this->message;
@ -87,9 +77,4 @@ class BanForm extends ApiForm {
Amqp::sendToEventsExchange('accounts.account-banned', $message);
}
public function __construct(Account $account, array $config = []) {
$this->account = $account;
parent::__construct($config);
}
}

View File

@ -1,39 +1,25 @@
<?php
namespace api\models\profile\ChangeEmail;
namespace api\modules\accounts\models;
use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator;
use common\helpers\Amqp;
use common\models\Account;
use common\models\amqp\EmailChanged;
use common\models\EmailActivation;
use PhpAmqpLib\Message\AMQPMessage;
use Yii;
use yii\base\ErrorException;
class ConfirmNewEmailForm extends ApiForm {
class ChangeEmailForm extends AccountActionForm {
public $key;
/**
* @var Account
*/
private $account;
public function rules() {
public function rules(): array {
return [
['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION],
];
}
/**
* @return Account
*/
public function getAccount(): Account {
return $this->account;
}
public function changeEmail(): bool {
public function performAction(): bool {
if (!$this->validate()) {
return false;
}
@ -58,13 +44,7 @@ class ConfirmNewEmailForm extends ApiForm {
return true;
}
/**
* @param integer $accountId
* @param string $newEmail
* @param string $oldEmail
* @throws \PhpAmqpLib\Exception\AMQPExceptionInterface
*/
public function createTask($accountId, $newEmail, $oldEmail) {
public function createTask(int $accountId, string $newEmail, string $oldEmail): void {
$model = new EmailChanged;
$model->accountId = $accountId;
$model->oldEmail = $oldEmail;
@ -77,9 +57,4 @@ class ConfirmNewEmailForm extends ApiForm {
Amqp::sendToEventsExchange('accounts.email-changed', $message);
}
public function __construct(Account $account, array $config = []) {
$this->account = $account;
parent::__construct($config);
}
}

View 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;
}
}

View File

@ -1,16 +1,15 @@
<?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 common\helpers\Error as E;
use common\models\Account;
use common\validators\PasswordValidator;
use Yii;
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;
class ChangePasswordForm extends ApiForm {
class ChangePasswordForm extends AccountActionForm {
public $newPassword;
@ -20,31 +19,23 @@ class ChangePasswordForm extends ApiForm {
public $password;
/**
* @var \common\models\Account
*/
private $_account;
public function __construct(Account $account, array $config = []) {
$this->_account = $account;
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function rules() {
public function rules(): array {
return ArrayHelper::merge(parent::rules(), [
['newPassword', 'required', 'message' => E::NEW_PASSWORD_REQUIRED],
['newRePassword', 'required', 'message' => E::NEW_RE_PASSWORD_REQUIRED],
['newPassword', PasswordValidator::class],
['newRePassword', 'validatePasswordAndRePasswordMatch'],
['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->newPassword !== $this->newRePassword) {
$this->addError($attribute, E::NEW_RE_PASSWORD_DOES_NOT_MATCH);
@ -52,25 +43,22 @@ class ChangePasswordForm extends ApiForm {
}
}
/**
* @return bool
* @throws ErrorException
*/
public function changePassword() : bool {
public function performAction(): bool {
if (!$this->validate()) {
return false;
}
$transaction = Yii::$app->db->beginTransaction();
$account = $this->_account;
$account = $this->getAccount();
$account->setPassword($this->newPassword);
if ($this->logoutAll) {
Yii::$app->user->terminateSessions();
Yii::$app->user->terminateSessions($account, Component::KEEP_CURRENT_SESSION);
}
if (!$account->save()) {
throw new ErrorException('Cannot save user model');
throw new ThisShouldNotHappenException('Cannot save user model');
}
$transaction->commit();
@ -78,8 +66,4 @@ class ChangePasswordForm extends ApiForm {
return true;
}
protected function getAccount() : Account {
return $this->_account;
}
}

View File

@ -1,76 +1,60 @@
<?php
namespace api\models\profile;
namespace api\modules\accounts\models;
use api\models\base\ApiForm;
use api\exceptions\ThisShouldNotHappenException;
use api\validators\PasswordRequiredValidator;
use common\helpers\Amqp;
use common\models\Account;
use common\models\amqp\UsernameChanged;
use common\models\UsernameHistory;
use common\validators\UsernameValidator;
use Exception;
use PhpAmqpLib\Message\AMQPMessage;
use Yii;
use yii\base\ErrorException;
class ChangeUsernameForm extends ApiForm {
class ChangeUsernameForm extends AccountActionForm {
public $username;
public $password;
/**
* @var Account
*/
private $account;
public function __construct(Account $account, array $config = []) {
parent::__construct($config);
$this->account = $account;
}
public function rules(): array {
return [
['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()) {
return false;
}
$account = $this->account;
$account = $this->getAccount();
if ($this->username === $account->username) {
return true;
}
$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();
$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();
} catch (Exception $e) {
$transaction->rollBack();
throw $e;
$oldNickname = $account->username;
$account->username = $this->username;
if (!$account->save()) {
throw new ThisShouldNotHappenException('Cannot save account model with new username');
}
$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;
}
@ -80,10 +64,11 @@ class ChangeUsernameForm extends ApiForm {
* @param integer $accountId
* @param string $newNickname
* @param string $oldNickname
* @throws \PhpAmqpLib\Exception\AMQPExceptionInterface
*
* @throws \PhpAmqpLib\Exception\AMQPExceptionInterface|\yii\base\Exception
*/
public function createEventTask($accountId, $newNickname, $oldNickname) {
$model = new UsernameChanged;
public function createEventTask($accountId, $newNickname, $oldNickname): void {
$model = new UsernameChanged();
$model->accountId = $accountId;
$model->oldUsername = $oldNickname;
$model->newUsername = $newNickname;

View 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);
}
}
}

View 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);
}
}
}

View File

@ -1,7 +1,6 @@
<?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 common\helpers\Amqp;
use common\models\Account;
@ -10,12 +9,7 @@ use PhpAmqpLib\Message\AMQPMessage;
use Yii;
use yii\base\ErrorException;
class PardonForm extends ApiForm {
/**
* @var Account
*/
private $account;
class PardonAccountForm extends AccountActionForm {
public function rules(): array {
return [
@ -23,24 +17,20 @@ class PardonForm extends ApiForm {
];
}
public function getAccount(): Account {
return $this->account;
}
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);
}
}
public function pardon(): bool {
public function performAction(): bool {
if (!$this->validate()) {
return false;
}
$transaction = Yii::$app->db->beginTransaction();
$account = $this->account;
$account = $this->getAccount();
$account->status = Account::STATUS_ACTIVE;
if (!$account->save()) {
throw new ErrorException('Cannot pardon account');
@ -55,7 +45,7 @@ class PardonForm extends ApiForm {
public function createTask(): void {
$model = new AccountPardoned();
$model->accountId = $this->account->id;
$model->accountId = $this->getAccount()->id;
$message = Amqp::getInstance()->prepareMessage($model, [
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
@ -64,9 +54,4 @@ class PardonForm extends ApiForm {
Amqp::sendToEventsExchange('accounts.account-pardoned', $message);
}
public function __construct(Account $account, array $config = []) {
$this->account = $account;
parent::__construct($config);
}
}

View File

@ -1,43 +1,31 @@
<?php
namespace api\models\profile\ChangeEmail;
namespace api\modules\accounts\models;
use api\exceptions\ThisShouldNotHappenException;
use common\emails\EmailHelper;
use api\models\base\ApiForm;
use api\validators\PasswordRequiredValidator;
use common\helpers\Error as E;
use common\models\Account;
use common\models\confirmations\CurrentEmailConfirmation;
use common\models\EmailActivation;
use Yii;
use yii\base\ErrorException;
use yii\base\Exception;
class InitStateForm extends ApiForm {
public $email;
class SendEmailVerificationForm extends AccountActionForm {
public $password;
private $account;
/**
* @var null meta-поле, чтобы заставить yii валидировать и публиковать ошибки, связанные с отправленными email
*/
public $email;
public function __construct(Account $account, array $config = []) {
$this->account = $account;
$this->email = $account->email;
parent::__construct($config);
}
public function getAccount() : Account {
return $this->account;
}
public function rules() {
public function rules(): array {
return [
['email', 'validateFrequency'],
['password', PasswordRequiredValidator::class, 'account' => $this->account],
['email', 'validateFrequency', 'skipOnEmpty' => false],
['password', PasswordRequiredValidator::class, 'account' => $this->getAccount()],
];
}
public function validateFrequency($attribute) {
public function validateFrequency($attribute): void {
if (!$this->hasErrors()) {
$emailConfirmation = $this->getEmailActivation();
if ($emailConfirmation !== null && !$emailConfirmation->canRepeat()) {
@ -46,46 +34,35 @@ class InitStateForm extends ApiForm {
}
}
public function sendCurrentEmailConfirmation() : bool {
public function performAction(): bool {
if (!$this->validate()) {
return false;
}
$transaction = Yii::$app->db->beginTransaction();
try {
$this->removeOldCode();
$activation = $this->createCode();
EmailHelper::changeEmailConfirmCurrent($activation);
$this->removeOldCode();
$activation = $this->createCode();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
throw $e;
}
EmailHelper::changeEmailConfirmCurrent($activation);
$transaction->commit();
return true;
}
/**
* @return CurrentEmailConfirmation
* @throws ErrorException
*/
public function createCode() : CurrentEmailConfirmation {
public function createCode(): CurrentEmailConfirmation {
$account = $this->getAccount();
$emailActivation = new CurrentEmailConfirmation();
$emailActivation->account_id = $account->id;
if (!$emailActivation->save()) {
throw new ErrorException('Cannot save email activation model');
throw new ThisShouldNotHappenException('Cannot save email activation model');
}
return $emailActivation;
}
/**
* Удаляет старый ключ активации, если он существует
*/
public function removeOldCode() {
public function removeOldCode(): void {
$emailActivation = $this->getEmailActivation();
if ($emailActivation === null) {
return;
@ -99,10 +76,8 @@ class InitStateForm extends ApiForm {
* Метод предназначен для проверки, не слишком ли часто отправляются письма о смене E-mail.
* Проверяем тип подтверждения нового E-mail, поскольку при переходе на этот этап, активация предыдущего
* шага удаляется.
* @return EmailActivation|null
* @throws ErrorException
*/
public function getEmailActivation() {
public function getEmailActivation(): ?EmailActivation {
return $this->getAccount()
->getEmailActivations()
->andWhere([

View File

@ -1,39 +1,28 @@
<?php
namespace api\models\profile\ChangeEmail;
namespace api\modules\accounts\models;
use api\exceptions\ThisShouldNotHappenException;
use common\emails\EmailHelper;
use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator;
use common\models\Account;
use common\models\confirmations\NewEmailConfirmation;
use common\models\EmailActivation;
use common\validators\EmailValidator;
use Yii;
use yii\base\ErrorException;
class NewEmailForm extends ApiForm {
class SendNewEmailVerificationForm extends AccountActionForm {
public $key;
public $email;
/**
* @var Account
*/
private $account;
public function rules() {
public function rules(): array {
return [
['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION],
['email', EmailValidator::class],
];
}
public function getAccount(): Account {
return $this->account;
}
public function sendNewEmailConfirmation(): bool {
public function performAction(): bool {
if (!$this->validate()) {
return false;
}
@ -53,24 +42,15 @@ class NewEmailForm extends ApiForm {
return true;
}
/**
* @return NewEmailConfirmation
* @throws ErrorException
*/
public function createCode() {
public function createCode(): NewEmailConfirmation {
$emailActivation = new NewEmailConfirmation();
$emailActivation->account_id = $this->getAccount()->id;
$emailActivation->newEmail = $this->email;
if (!$emailActivation->save()) {
throw new ErrorException('Cannot save email activation model');
throw new ThisShouldNotHappenException('Cannot save email activation model');
}
return $emailActivation;
}
public function __construct(Account $account, array $config = []) {
$this->account = $account;
parent::__construct($config);
}
}

View 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;
}

View 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, '#');
}
}

View File

@ -7,7 +7,7 @@ use Yii;
class AuthenticationController extends Controller {
public function behaviors() {
public function behaviors(): array {
$behaviors = parent::behaviors();
unset($behaviors['authenticator']);

View File

@ -1,58 +1,42 @@
<?php
namespace api\modules\internal\controllers;
use api\components\ApiUser\AccessControl;
use api\controllers\Controller;
use api\modules\internal\models\BanForm;
use api\modules\internal\models\PardonForm;
use common\models\Account;
use common\models\OauthScope as S;
use Yii;
use common\rbac\Permissions as P;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
class AccountsController extends Controller {
public function behaviors() {
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'user' => Yii::$app->apiUser,
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'actions' => ['ban'],
'allow' => true,
'roles' => [S::ACCOUNT_BLOCK],
],
[
'actions' => ['info'],
'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 [
'ban' => ['POST', 'DELETE'],
'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) {
if ($id !== null) {
$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;
}
}

View File

@ -10,7 +10,7 @@ use yii\web\Response;
class ApiController extends Controller {
public function behaviors() {
public function behaviors(): array {
$behaviors = parent::behaviors();
unset($behaviors['authenticator']);

View File

@ -1,7 +1,7 @@
<?php
namespace api\modules\session\controllers;
use api\controllers\ApiController;
use api\controllers\Controller;
use api\modules\session\exceptions\ForbiddenOperationException;
use api\modules\session\exceptions\IllegalArgumentException;
use api\modules\session\exceptions\SessionServerException;
@ -17,9 +17,9 @@ use Ramsey\Uuid\Uuid;
use Yii;
use yii\web\Response;
class SessionController extends ApiController {
class SessionController extends Controller {
public function behaviors() {
public function behaviors(): array {
$behaviors = parent::behaviors();
unset($behaviors['authenticator']);
$behaviors['rateLimiting'] = [

View File

@ -18,7 +18,7 @@ class HasJoinedForm extends Model {
parent::__construct($config);
}
public function hasJoined() : Account {
public function hasJoined(): Account {
if (!$this->protocol->validate()) {
throw new IllegalArgumentException();
}

View File

@ -7,10 +7,10 @@ use api\modules\session\models\protocols\JoinInterface;
use api\modules\session\Module as Session;
use api\modules\session\validators\RequiredValidator;
use common\helpers\StringHelper;
use common\models\OauthScope as S;
use common\validators\UuidValidator;
use common\rbac\Permissions as P;
use common\models\Account;
use common\models\MinecraftAccessKey;
use Ramsey\Uuid\Uuid;
use Yii;
use yii\base\ErrorException;
use yii\base\Model;
@ -84,16 +84,7 @@ class JoinForm extends Model {
return;
}
if ($attribute === 'selectedProfile' && !StringHelper::isUuid($this->selectedProfile)) {
// Это нормально. Там может быть ник игрока, если это Legacy авторизация
return;
}
$validator = new UuidValidator();
$validator->allowNil = false;
$validator->validateAttribute($this, $attribute);
if ($this->hasErrors($attribute)) {
if ($this->$attribute === Uuid::NIL) {
throw new IllegalArgumentException();
}
}
@ -105,9 +96,17 @@ class JoinForm extends Model {
$accessToken = $this->accessToken;
/** @var MinecraftAccessKey|null $accessModel */
$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 {
$identity = Yii::$app->apiUser->loginByAccessToken($accessToken);
$identity = Yii::$app->user->loginByAccessToken($accessToken);
} catch (UnauthorizedHttpException $e) {
$identity = null;
}
@ -117,21 +116,12 @@ class JoinForm extends Model {
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.");
throw new ForbiddenOperationException('The token does not have required scope.');
}
$accessModel = $identity->getAccessToken();
$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;
@ -142,7 +132,9 @@ class JoinForm extends Model {
" but access_token issued to account with id = '{$account->uuid}'."
);
throw new ForbiddenOperationException('Wrong selected_profile.');
} elseif (!$isUuid && $account->username !== $selectedProfile) {
}
if (!$isUuid && $account->username !== $selectedProfile) {
Session::error(
"User with access_token = '{$accessToken}' trying to join with identity = '{$selectedProfile}'," .
" but access_token issued to account with username = '{$account->username}'."
@ -153,10 +145,7 @@ class JoinForm extends Model {
$this->account = $account;
}
/**
* @return Account|null
*/
protected function getAccount() {
protected function getAccount(): Account {
return $this->account;
}

View File

@ -17,24 +17,16 @@ class SessionModel {
$this->serverId = $serverId;
}
/**
* @param $username
* @param $serverId
*
* @return static|null
*/
public static function find($username, $serverId) {
public static function find(string $username, string $serverId): ?self {
$key = static::buildKey($username, $serverId);
$result = Yii::$app->redis->executeCommand('GET', [$key]);
if (!$result) {
/** @noinspection PhpIncompatibleReturnTypeInspection шторм что-то сума сходит, когда видит static */
return null;
}
$data = json_decode($result, true);
$model = new static($data['username'], $data['serverId']);
return $model;
return new static($data['username'], $data['serverId']);
}
public function save() {
@ -51,15 +43,11 @@ class SessionModel {
return Yii::$app->redis->executeCommand('DEL', [static::buildKey($this->username, $this->serverId)]);
}
/**
* @return Account|null
* TODO: после перехода на PHP 7.1 установить тип как ?Account
*/
public function getAccount() {
public function getAccount(): ?Account {
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);
}

View File

@ -1,31 +1,30 @@
<?php
namespace api\modules\session\models\protocols;
use yii\validators\RequiredValidator;
abstract class BaseHasJoined implements HasJoinedInterface {
private $username;
private $serverId;
public function __construct(string $username, string $serverId) {
$this->username = $username;
$this->serverId = $serverId;
$this->username = trim($username);
$this->serverId = trim($serverId);
}
public function getUsername() : string {
public function getUsername(): string {
return $this->username;
}
public function getServerId() : string {
public function getServerId(): string {
return $this->serverId;
}
public function validate() : bool {
$validator = new RequiredValidator();
public function validate(): bool {
return !$this->isEmpty($this->username) && !$this->isEmpty($this->serverId);
}
return $validator->validate($this->username)
&& $validator->validate($this->serverId);
private function isEmpty($value): bool {
return $value === null || $value === '';
}
}

View File

@ -3,12 +3,8 @@ namespace api\modules\session\models\protocols;
abstract class BaseJoin implements JoinInterface {
abstract public function getAccessToken() : string;
abstract public function getSelectedProfile() : string;
abstract public function getServerId() : string;
abstract public function validate() : bool;
protected function isEmpty($value): bool {
return $value === null || $value === '';
}
}

View File

@ -3,10 +3,10 @@ namespace api\modules\session\models\protocols;
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;
}

View File

@ -3,13 +3,12 @@ namespace api\modules\session\models\protocols;
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;
}

View File

@ -1,8 +1,6 @@
<?php
namespace api\modules\session\models\protocols;
use yii\validators\RequiredValidator;
class LegacyJoin extends BaseJoin {
private $user;
@ -13,9 +11,9 @@ class LegacyJoin extends BaseJoin {
private $uuid;
public function __construct(string $user, string $sessionId, string $serverId) {
$this->user = $user;
$this->sessionId = $sessionId;
$this->serverId = $serverId;
$this->user = trim($user);
$this->sessionId = trim($sessionId);
$this->serverId = trim($serverId);
$this->parseSessionId($this->sessionId);
}
@ -24,23 +22,19 @@ class LegacyJoin extends BaseJoin {
return $this->accessToken;
}
public function getSelectedProfile() : string {
public function getSelectedProfile(): string {
return $this->uuid ?: $this->user;
}
public function getServerId() : string {
public function getServerId(): string {
return $this->serverId;
}
/**
* @return bool
*/
public function validate() : bool {
$validator = new RequiredValidator();
return $validator->validate($this->accessToken)
&& $validator->validate($this->user)
&& $validator->validate($this->serverId);
public function validate(): bool {
return !$this->isEmpty($this->accessToken) && !$this->isEmpty($this->user) && !$this->isEmpty($this->serverId);
}
/**
@ -50,7 +44,7 @@ class LegacyJoin extends BaseJoin {
* Бьём по ':' для учёта авторизации в современных лаунчерах и входе на более старую
* версию игры. Там sessionId передаётся как "token:{accessToken}:{uuid}", так что это нужно обработать
*/
protected function parseSessionId(string $sessionId) {
private function parseSessionId(string $sessionId) {
$parts = explode(':', $sessionId);
if (count($parts) === 3) {
$this->accessToken = $parts[1];

View File

@ -1,8 +1,6 @@
<?php
namespace api\modules\session\models\protocols;
use yii\validators\RequiredValidator;
class ModernJoin extends BaseJoin {
private $accessToken;
@ -10,29 +8,25 @@ class ModernJoin extends BaseJoin {
private $serverId;
public function __construct(string $accessToken, string $selectedProfile, string $serverId) {
$this->accessToken = $accessToken;
$this->selectedProfile = $selectedProfile;
$this->serverId = $serverId;
$this->accessToken = trim($accessToken);
$this->selectedProfile = trim($selectedProfile);
$this->serverId = trim($serverId);
}
public function getAccessToken() : string {
public function getAccessToken(): string {
return $this->accessToken;
}
public function getSelectedProfile() : string {
public function getSelectedProfile(): string {
return $this->selectedProfile;
}
public function getServerId() : string {
public function getServerId(): string {
return $this->serverId;
}
public function validate() : bool {
$validator = new RequiredValidator();
return $validator->validate($this->accessToken)
&& $validator->validate($this->selectedProfile)
&& $validator->validate($this->serverId);
public function validate(): bool {
return !$this->isEmpty($this->accessToken) && !$this->isEmpty($this->selectedProfile) && !$this->isEmpty($this->serverId);
}
}

View File

@ -7,29 +7,18 @@ trait AccountFinder {
private $account;
public abstract function getLogin();
public abstract function getLogin(): string;
/**
* @return Account|null
*/
public function getAccount() {
public function getAccount(): ?Account {
if ($this->account === null) {
$className = $this->getAccountClassName();
$this->account = $className::findOne([$this->getLoginAttribute() => $this->getLogin()]);
$this->account = Account::findOne([$this->getLoginAttribute() => $this->getLogin()]);
}
return $this->account;
}
public function getLoginAttribute() {
public function getLoginAttribute(): string {
return strpos($this->getLogin(), '@') ? 'email' : 'username';
}
/**
* @return Account|string
*/
protected function getAccountClassName() {
return Account::class;
}
}

View File

@ -3,7 +3,6 @@ namespace api\validators;
use common\helpers\Error as E;
use common\models\Account;
use Yii;
use yii\base\InvalidConfigException;
use yii\validators\Validator;
@ -21,10 +20,6 @@ class PasswordRequiredValidator extends Validator {
public function init() {
parent::init();
if ($this->account === null) {
$this->account = Yii::$app->user->identity;
}
if (!$this->account instanceof Account) {
throw new InvalidConfigException('account should be instance of ' . Account::class);
}

View File

@ -32,7 +32,6 @@ abstract class BaseApplication extends yii\base\Application {
* Include only Web application related components here
*
* @property \api\components\User\Component $user User component.
* @property \api\components\ApiUser\Component $apiUser Api User component.
* @property \api\components\ReCaptcha\Component $reCaptcha
*
* @method \api\components\User\Component getUser()

View File

@ -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());
}
}

View File

@ -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');
}
}

View File

@ -6,46 +6,7 @@ use Yii;
class Key {
protected $key;
/**
* @return Connection
*/
public function getRedis() {
return Yii::$app->redis;
}
public function getKey() : string {
return $this->key;
}
public function getValue() {
return $this->getRedis()->get($this->key);
}
public function setValue($value) {
$this->getRedis()->set($this->key, $value);
return $this;
}
public function delete() {
$this->getRedis()->del($this->key);
return $this;
}
public function exists() : bool {
return (bool)$this->getRedis()->exists($this->key);
}
public function expire(int $ttl) {
$this->getRedis()->expire($this->key, $ttl);
return $this;
}
public function expireAt(int $unixTimestamp) {
$this->getRedis()->expireat($this->key, $unixTimestamp);
return $this;
}
private $key;
public function __construct(...$key) {
if (empty($key)) {
@ -55,7 +16,43 @@ class Key {
$this->key = $this->buildKey($key);
}
private function buildKey(array $parts) {
public function getRedis(): Connection {
return Yii::$app->redis;
}
public function getKey(): string {
return $this->key;
}
public function getValue() {
return $this->getRedis()->get($this->key);
}
public function setValue($value): self {
$this->getRedis()->set($this->key, $value);
return $this;
}
public function delete(): self {
$this->getRedis()->del([$this->getKey()]);
return $this;
}
public function exists(): bool {
return (bool)$this->getRedis()->exists($this->key);
}
public function expire(int $ttl): self {
$this->getRedis()->expire($this->key, $ttl);
return $this;
}
public function expireAt(int $unixTimestamp): self {
$this->getRedis()->expireat($this->key, $unixTimestamp);
return $this;
}
private function buildKey(array $parts): string {
$keyParts = [];
foreach($parts as $part) {
$keyParts[] = str_replace('_', ':', $part);

View File

@ -6,34 +6,34 @@ use IteratorAggregate;
class Set extends Key implements IteratorAggregate {
public function add($value) {
$this->getRedis()->sadd($this->key, $value);
public function add($value): self {
$this->getRedis()->sadd($this->getKey(), $value);
return $this;
}
public function remove($value) {
$this->getRedis()->srem($this->key, $value);
public function remove($value): self {
$this->getRedis()->srem($this->getKey(), $value);
return $this;
}
public function members() {
return $this->getRedis()->smembers($this->key);
public function members(): array {
return $this->getRedis()->smembers($this->getKey());
}
public function getValue() {
public function getValue(): array {
return $this->members();
}
public function exists(string $value = null) : bool {
public function exists(string $value = null): bool {
if ($value === null) {
return parent::exists();
} else {
return (bool)$this->getRedis()->sismember($this->key, $value);
}
return (bool)$this->getRedis()->sismember($this->getKey(), $value);
}
public function diff(array $sets) {
return $this->getRedis()->sdiff([$this->key, implode(' ', $sets)]);
public function diff(array $sets): array {
return $this->getRedis()->sdiff([$this->getKey(), implode(' ', $sets)]);
}
/**

View File

@ -1,7 +1,7 @@
<?php
return [
'version' => '1.1.18-dev',
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'vendorPath' => dirname(__DIR__, 2) . '/vendor',
'components' => [
'cache' => [
'class' => common\components\Redis\Cache::class,
@ -72,6 +72,11 @@ return [
'oauth' => [
'class' => api\components\OAuth2\Component::class,
],
'authManager' => [
'class' => common\rbac\Manager::class,
'itemFile' => '@common/rbac/.generated/items.php',
'ruleFile' => '@common/rbac/.generated/rules.php',
],
],
'container' => [
'definitions' => [

View File

@ -51,27 +51,18 @@ class Account extends ActiveRecord {
const PASS_HASH_STRATEGY_OLD_ELY = 0;
const PASS_HASH_STRATEGY_YII2 = 1;
public static function tableName() {
public static function tableName(): string {
return '{{%accounts}}';
}
public function behaviors() {
public function behaviors(): array {
return [
TimestampBehavior::class,
];
}
/**
* Validates password
*
* @param string $password password to validate
* @param integer $passwordHashStrategy
*
* @return bool if password provided is valid for current user
* @throws InvalidConfigException
*/
public function validatePassword($password, $passwordHashStrategy = NULL) : bool {
if ($passwordHashStrategy === NULL) {
public function validatePassword(string $password, int $passwordHashStrategy = null): bool {
if ($passwordHashStrategy === null) {
$passwordHashStrategy = $this->password_hash_strategy;
}
@ -88,17 +79,13 @@ class Account extends ActiveRecord {
}
}
/**
* @param string $password
* @throws InvalidConfigException
*/
public function setPassword($password) {
public function setPassword(string $password): void {
$this->password_hash_strategy = self::PASS_HASH_STRATEGY_YII2;
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
$this->password_changed_at = time();
}
public function getEmailActivations() {
public function getEmailActivations(): ActiveQuery {
return $this->hasMany(EmailActivation::class, ['account_id' => 'id']);
}
@ -106,15 +93,15 @@ class Account extends ActiveRecord {
return $this->hasMany(OauthSession::class, ['owner_id' => 'id'])->andWhere(['owner_type' => 'user']);
}
public function getUsernameHistory() {
public function getUsernameHistory(): ActiveQuery {
return $this->hasMany(UsernameHistory::class, ['account_id' => 'id']);
}
public function getSessions() {
public function getSessions(): ActiveQuery {
return $this->hasMany(AccountSession::class, ['account_id' => 'id']);
}
public function getMinecraftAccessKeys() {
public function getMinecraftAccessKeys(): ActiveQuery {
return $this->hasMany(MinecraftAccessKey::class, ['account_id' => 'id']);
}
@ -123,7 +110,7 @@ class Account extends ActiveRecord {
*
* @return bool
*/
public function hasMojangUsernameCollision() : bool {
public function hasMojangUsernameCollision(): bool {
return MojangUsername::find()
->andWhere(['username' => $this->username])
->exists();
@ -136,7 +123,7 @@ class Account extends ActiveRecord {
*
* @return string
*/
public function getProfileLink() : string {
public function getProfileLink(): string {
return 'http://ely.by/u' . $this->id;
}
@ -148,15 +135,15 @@ class Account extends ActiveRecord {
*
* @return bool
*/
public function isAgreedWithActualRules() : bool {
public function isAgreedWithActualRules(): bool {
return $this->rules_agreement_version === LATEST_RULES_VERSION;
}
public function setRegistrationIp($ip) {
public function setRegistrationIp($ip): void {
$this->registration_ip = $ip === null ? null : inet_pton($ip);
}
public function getRegistrationIp() {
public function getRegistrationIp(): ?string {
return $this->registration_ip === null ? null : inet_ntop($this->registration_ip);
}

View 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';
}

View File

@ -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