mirror of
https://github.com/elyby/accounts.git
synced 2025-05-31 14:11:46 +05:30
Translate all code comments from Russian to English [skip ci]
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace api\aop\annotations;
|
||||
|
||||
use Doctrine\Common\Annotations\Annotation;
|
||||
@@ -12,7 +14,7 @@ class CollectModelMetrics {
|
||||
|
||||
/**
|
||||
* @Required()
|
||||
* @var string задаёт префикс для отправки метрик. Задаётся без ведущей и без завершающей точки.
|
||||
* @var string sets the prefix for collected metrics. Should be specified without trailing dots
|
||||
*/
|
||||
public $prefix = '';
|
||||
|
||||
|
@@ -196,7 +196,7 @@ class AuthCodeGrant extends AbstractGrant {
|
||||
$this->server->getTokenType()->setParam('access_token', $accessToken->getId());
|
||||
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
|
||||
|
||||
// Выдаём refresh_token, если запрошен offline_access
|
||||
// Set refresh_token param only in case when offline_access requested
|
||||
if (isset($accessToken->getScopes()[ScopeStorage::OFFLINE_ACCESS])) {
|
||||
/** @var RefreshTokenGrant $refreshTokenGrant */
|
||||
$refreshTokenGrant = $this->server->getGrantType('refresh_token');
|
||||
@@ -222,8 +222,9 @@ class AuthCodeGrant extends AbstractGrant {
|
||||
}
|
||||
|
||||
/**
|
||||
* По стандарту OAuth2 scopes должны разделяться пробелом, а не запятой. Косяк.
|
||||
* Так что оборачиваем функцию разбора скоупов, заменяя запятые на пробелы.
|
||||
* In the earlier versions of Accounts Ely.by backend we had a comma-separated scopes
|
||||
* list, while by OAuth2 standard it they should be separated by a space. Shit happens :)
|
||||
* So override scopes validation function to reformat passed value.
|
||||
*
|
||||
* @param string $scopeParam
|
||||
* @param BaseClientEntity $client
|
||||
|
@@ -69,8 +69,9 @@ class ClientCredentialsGrant extends AbstractGrant {
|
||||
}
|
||||
|
||||
/**
|
||||
* По стандарту OAuth2 scopes должны разделяться пробелом, а не запятой. Косяк.
|
||||
* Так что оборачиваем функцию разбора скоупов, заменяя запятые на пробелы.
|
||||
* In the earlier versions of Accounts Ely.by backend we had a comma-separated scopes
|
||||
* list, while by OAuth2 standard it they should be separated by a space. Shit happens :)
|
||||
* So override scopes validation function to reformat passed value.
|
||||
*
|
||||
* @param string $scopeParam
|
||||
* @param BaseClientEntity $client
|
||||
|
@@ -48,8 +48,9 @@ class RefreshTokenGrant extends AbstractGrant {
|
||||
}
|
||||
|
||||
/**
|
||||
* По стандарту OAuth2 scopes должны разделяться пробелом, а не запятой. Косяк.
|
||||
* Так что оборачиваем функцию разбора скоупов, заменяя запятые на пробелы.
|
||||
* In the earlier versions of Accounts Ely.by backend we had a comma-separated scopes
|
||||
* list, while by OAuth2 standard it they should be separated by a space. Shit happens :)
|
||||
* So override scopes validation function to reformat passed value.
|
||||
*
|
||||
* @param string $scopeParam
|
||||
* @param BaseClientEntity $client
|
||||
@@ -62,9 +63,9 @@ class RefreshTokenGrant extends AbstractGrant {
|
||||
}
|
||||
|
||||
/**
|
||||
* Метод таки пришлось переписать по той причине, что нынче мы храним access_token в redis с expire значением,
|
||||
* так что он может банально несуществовать на тот момент, когда к нему через refresh_token попытаются обратиться.
|
||||
* Поэтому мы расширили логику RefreshTokenEntity и она теперь знает о сессии, в рамках которой была создана
|
||||
* The method has been overridden because we stores access_tokens in Redis with expire value,
|
||||
* so they might not exists at the moment, when it will be requested via refresh_token.
|
||||
* That's why we extends RefreshTokenEntity to give it knowledge about related session.
|
||||
*
|
||||
* @inheritdoc
|
||||
* @throws \League\OAuth2\Server\Exception\OAuthException
|
||||
|
@@ -27,16 +27,12 @@ class ClientStorage extends AbstractStorage implements ClientInterface {
|
||||
return null;
|
||||
}
|
||||
|
||||
// TODO: нужно учитывать тип приложения
|
||||
/*
|
||||
* Для приложений типа "настольный" redirect_uri необязателем - он должен быть по умолчанию равен
|
||||
* статичному редиректу на страницу сайта
|
||||
* А для приложений типа "сайт" редирект должен быть всегда.
|
||||
* Короче это нужно учесть
|
||||
*/
|
||||
// TODO: should check application type
|
||||
// For "desktop" app type redirect_uri is not required and should be by default set
|
||||
// to the static redirect, but for "site" it's required always.
|
||||
if ($redirectUri !== null) {
|
||||
if (in_array($redirectUri, [self::REDIRECT_STATIC_PAGE, self::REDIRECT_STATIC_PAGE_WITH_CODE], true)) {
|
||||
// Тут, наверное, нужно проверить тип приложения
|
||||
// I think we should check the type of application here
|
||||
} else {
|
||||
if (!StringHelper::startsWith($redirectUri, $model->redirect_uri, false)) {
|
||||
return null;
|
||||
|
@@ -39,8 +39,8 @@ class ScopeStorage extends AbstractStorage implements ScopeInterface {
|
||||
|
||||
/**
|
||||
* @param string $scope
|
||||
* @param string $grantType передаётся, если запрос поступает из grant. В этом случае нужно отфильтровать
|
||||
* только те права, которые можно получить на этом grant.
|
||||
* @param string $grantType is passed on if called from the grant.
|
||||
* In this case, you only need to filter out the rights that you can get on this grant.
|
||||
* @param string $clientId
|
||||
*
|
||||
* @return ScopeEntity|null
|
||||
|
@@ -52,7 +52,7 @@ class SessionStorage extends AbstractStorage implements SessionInterface {
|
||||
->andWhere([
|
||||
'client_id' => $clientId,
|
||||
'owner_type' => $ownerType,
|
||||
'owner_id' => (string)$ownerId, // Переводим в строку, чтобы работали индексы, т.к. поле varchar
|
||||
'owner_id' => (string)$ownerId, // Casts as a string to make the indexes work, because the varchar field
|
||||
])->scalar();
|
||||
|
||||
if ($sessionId === false) {
|
||||
|
@@ -1,15 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace api\components\OAuth2\Utils;
|
||||
|
||||
class Scopes {
|
||||
|
||||
/**
|
||||
* По стандарту OAuth2 scopes должны разделяться пробелом, а не запятой. Косяк.
|
||||
* Так что оборачиваем функцию разбора скоупов, заменяя запятые на пробелы.
|
||||
* Заодно учитываем возможность передать скоупы в виде массива.
|
||||
* In the earlier versions of Accounts Ely.by backend we had a comma-separated scopes
|
||||
* list, while by OAuth2 standard it they should be separated by a space. Shit happens :)
|
||||
* So override scopes validation function to reformat passed value.
|
||||
*
|
||||
* @param string|array $scopes
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function format($scopes): string {
|
||||
@@ -21,7 +22,6 @@ class Scopes {
|
||||
return implode(' ', $scopes);
|
||||
}
|
||||
|
||||
/** @noinspection PhpIncompatibleReturnTypeInspection */
|
||||
return str_replace(',', ' ', $scopes);
|
||||
}
|
||||
|
||||
|
@@ -92,8 +92,8 @@ class Component extends YiiUserComponent {
|
||||
$token->addClaim(new Claim\JwtId($session->id));
|
||||
} else {
|
||||
$session = null;
|
||||
// Если мы не сохраняем сессию, то токен должен жить подольше,
|
||||
// чтобы не прогорала сессия во время работы с аккаунтом
|
||||
// If we don't remember a session, the token should live longer
|
||||
// so that the session doesn't end while working with the account
|
||||
$token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout))));
|
||||
}
|
||||
|
||||
@@ -125,8 +125,8 @@ class Component extends YiiUserComponent {
|
||||
|
||||
/**
|
||||
* @param string $jwtString
|
||||
* @return Token распаршенный токен
|
||||
* @throws VerificationException если один из Claims не пройдёт проверку
|
||||
* @return Token
|
||||
* @throws VerificationException in case when some Claim not pass the validation
|
||||
*/
|
||||
public function parseToken(string $jwtString): Token {
|
||||
$token = &self::$parsedTokensCache[$jwtString];
|
||||
@@ -149,13 +149,13 @@ class Component extends YiiUserComponent {
|
||||
}
|
||||
|
||||
/**
|
||||
* Метод находит AccountSession модель, относительно которой был выдан текущий JWT токен.
|
||||
* В случае, если на пути поиска встретится ошибка, будет возвращено значение null. Возможные кейсы:
|
||||
* - Юзер не авторизован
|
||||
* - Почему-то нет заголовка с токеном
|
||||
* - Во время проверки токена возникла ошибка, что привело к исключению
|
||||
* - В токене не найдено ключа сессии. Такое возможно, если юзер выбрал "не запоминать меня"
|
||||
* или просто старые токены, без поддержки сохранения используемой сессии
|
||||
* The method searches AccountSession model, which one has been used to create current JWT token.
|
||||
* null will be returned in case when any of the following situations occurred:
|
||||
* - The user isn't authorized
|
||||
* - There is no header with a token
|
||||
* - Token validation isn't passed and some exception has been thrown
|
||||
* - No session key found in the token. This is possible if the user chose not to remember me
|
||||
* or just some old tokens, without the support of saving the used session
|
||||
*
|
||||
* @return AccountSession|null
|
||||
*/
|
||||
|
@@ -17,17 +17,17 @@ interface IdentityInterface extends \yii\web\IdentityInterface {
|
||||
public static function findIdentityByAccessToken($token, $type = null): IdentityInterface;
|
||||
|
||||
/**
|
||||
* Этот метод используется для получения токена, к которому привязаны права.
|
||||
* У нас права привязываются к токенам, так что возвращаем именно его id.
|
||||
* This method is used to obtain a token to which scopes are attached.
|
||||
* Our permissions are attached to tokens itself, so we return its id.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getId(): string;
|
||||
|
||||
/**
|
||||
* Метод возвращает аккаунт, который привязан к текущему токену.
|
||||
* Но не исключено, что токен был выдан и без привязки к аккаунту, так что
|
||||
* следует это учитывать.
|
||||
* The method returns an account that is attached to the current token.
|
||||
* But it's possible that the token was issued without binding to the account,
|
||||
* so you should handle it.
|
||||
*
|
||||
* @return Account|null
|
||||
*/
|
||||
|
@@ -1,11 +1,13 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace api\controllers;
|
||||
|
||||
use Yii;
|
||||
use yii\filters\auth\HttpBearerAuth;
|
||||
|
||||
/**
|
||||
* Поведения:
|
||||
* Behaviors:
|
||||
* @mixin \yii\filters\ContentNegotiator
|
||||
* @mixin \yii\filters\VerbFilter
|
||||
* @mixin \yii\filters\auth\CompositeAuth
|
||||
@@ -14,13 +16,13 @@ class Controller extends \yii\rest\Controller {
|
||||
|
||||
public function behaviors(): array {
|
||||
$parentBehaviors = parent::behaviors();
|
||||
// Добавляем авторизатор для входа по jwt токенам
|
||||
// Add JWT authenticator
|
||||
$parentBehaviors['authenticator'] = [
|
||||
'class' => HttpBearerAuth::class,
|
||||
'user' => Yii::$app->getUser(),
|
||||
];
|
||||
|
||||
// xml и rate limiter нам не понадобятся
|
||||
// XML and rate limiter is not necessary
|
||||
unset(
|
||||
$parentBehaviors['contentNegotiator']['formats']['application/xml'],
|
||||
$parentBehaviors['rateLimiter']
|
||||
|
@@ -1,10 +1,12 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace api\exceptions;
|
||||
|
||||
/**
|
||||
* Исключение можно использовать для тех кейсов, где вроде указанных исход не продполагается,
|
||||
* но теоретически может произойти. Целью является отлавливание таких участков и доработка логики,
|
||||
* если такие ситуации всё же будут иметь место случаться.
|
||||
* The exception can be used for cases where the outcome doesn't seem to be expected,
|
||||
* but can theoretically happen. The goal is to capture these areas and refine the logic
|
||||
* if such situations do occur.
|
||||
*/
|
||||
class ThisShouldNotHappenException extends Exception {
|
||||
|
||||
|
@@ -1,4 +1,6 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace api\filters;
|
||||
|
||||
use Yii;
|
||||
@@ -7,13 +9,13 @@ use yii\base\ActionFilter;
|
||||
class NginxCache extends ActionFilter {
|
||||
|
||||
/**
|
||||
* @var array|callable массив или callback, содержащий пары роут -> сколько кэшировать.
|
||||
* @var array|callable array or callback, contains pairs of route => cache duration.
|
||||
*
|
||||
* Период можно задавать 2-умя путями:
|
||||
* - если значение начинается с префикса @, оно задаёт абсолютное время в unix timestamp,
|
||||
* до которого ответ может быть закэширован.
|
||||
* - в ином случае значение интерпретируется как количество секунд, на которое необходимо
|
||||
* закэшировать ответ
|
||||
* Duration can be set in 2-ways:
|
||||
* - if the value starts with the @ prefix, it sets the absolute time
|
||||
* in unix timestamp that the response can be cached to.
|
||||
* - otherwise, the value is interpreted as the number of seconds
|
||||
* for which the response must be cached
|
||||
*/
|
||||
public $rules;
|
||||
|
||||
|
@@ -116,14 +116,14 @@ class RegistrationForm extends ApiForm {
|
||||
}
|
||||
|
||||
/**
|
||||
* Метод проверяет, можно ли занять указанный при регистрации ник или e-mail. Так случается,
|
||||
* что пользователи вводят неправильный e-mail или ник, после замечают это и пытаются вновь
|
||||
* выпонить регистрацию. Мы не будем им мешать и просто удаляем существующие недозарегистрированные
|
||||
* аккаунты, позволяя им зарегистрироваться.
|
||||
*
|
||||
* @param array $errors массив, где ключ - это поле, а значение - первая ошибка из нашего
|
||||
* стандартного словаря ошибок
|
||||
* The method checks whether the username or E-mail specified during registration
|
||||
* can be occupied. It happens that users enter the wrong E-mail or username,
|
||||
* then notice it and try to re-register. We'll not interfere with them
|
||||
* and simply delete existing not-finished-registration account,
|
||||
* allowing them to take it.
|
||||
*
|
||||
* @param array $errors an array where the key is a field and the value is
|
||||
* the first error from our standard error dictionary
|
||||
* @return bool
|
||||
*/
|
||||
protected function canContinue(array $errors): bool {
|
||||
|
@@ -12,17 +12,16 @@ class BanAccountForm extends AccountActionForm {
|
||||
public const DURATION_FOREVER = -1;
|
||||
|
||||
/**
|
||||
* Нереализованный функционал блокировки аккаунта на определённый период времени.
|
||||
* Сейчас установка этого параметра ничего не даст, аккаунт будет заблокирован навечно,
|
||||
* но, по задумке, здесь можно передать количество секунд, на которое будет
|
||||
* заблокирован аккаунт пользователя.
|
||||
* Unimplemented account blocking functionality for a certain period of time.
|
||||
* Setting this parameter currently will do nothing, the account will be blocked forever,
|
||||
* but the idea is to pass the number of seconds for which the user's account will be blocked.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $duration = self::DURATION_FOREVER;
|
||||
|
||||
/**
|
||||
* Нереализованный функционал указания причины блокировки аккаунта.
|
||||
* Unimplemented functionality to indicate the reason for account blocking.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
|
@@ -15,7 +15,7 @@ class SendEmailVerificationForm extends AccountActionForm {
|
||||
public $password;
|
||||
|
||||
/**
|
||||
* @var null meta-поле, чтобы заставить yii валидировать и публиковать ошибки, связанные с отправленными email
|
||||
* @var null meta-field to force yii to validate and publish errors related to sent emails
|
||||
*/
|
||||
public $email;
|
||||
|
||||
@@ -76,10 +76,10 @@ class SendEmailVerificationForm extends AccountActionForm {
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает E-mail активацию, которая использовалась внутри процесса для перехода на следующий шаг.
|
||||
* Метод предназначен для проверки, не слишком ли часто отправляются письма о смене E-mail.
|
||||
* Проверяем тип подтверждения нового E-mail, поскольку при переходе на этот этап, активация предыдущего
|
||||
* шага удаляется.
|
||||
* Returns the E-mail activation that was used within the process to move on to the next step.
|
||||
* The method is designed to check if the E-mail change messages are sent too often.
|
||||
* Including checking for the confirmation of the new E-mail type, because when you go to this step,
|
||||
* the activation of the previous step is removed.
|
||||
*/
|
||||
public function getEmailActivation(): ?EmailActivation {
|
||||
return $this->getAccount()
|
||||
|
@@ -62,13 +62,14 @@ class TwoFactorAuthInfo extends BaseAccountForm {
|
||||
}
|
||||
|
||||
/**
|
||||
* В используемой либе для рендеринга QR кода нет возможности указать QR code version.
|
||||
* In the used library for rendering QR codes there is no possibility to specify a QR code version.
|
||||
* http://www.qrcode.com/en/about/version.html
|
||||
* По какой-то причине 7 и 8 версии не читаются вовсе, с логотипом или без.
|
||||
* Поэтому нужно иначально привести строку к длинне 9 версии (91), добавляя к концу
|
||||
* строки необходимое количество символов "#". Этот символ используется, т.к. нашим
|
||||
* контентом является ссылка и чтобы не вводить лишние параметры мы помечаем добавочную
|
||||
* часть как хеш часть и все программы для чтения QR кодов продолжают свою работу.
|
||||
*
|
||||
* For some reason, generated versions 7 and 8 are not readable at all, with or without a logo.
|
||||
* Therefore, it is necessary to initially append the string to the length of version 9 (91),
|
||||
* adding to the end of the string the necessary number of characters "#".
|
||||
* This symbol is used because our content is a link and in order not to enter unnecessary parameters
|
||||
* we mark the additional part as a hash part and all application for scanning QR codes continue their work.
|
||||
*
|
||||
* @param string $content
|
||||
* @return string
|
||||
@@ -78,11 +79,11 @@ class TwoFactorAuthInfo extends BaseAccountForm {
|
||||
}
|
||||
|
||||
/**
|
||||
* otp_secret кодируется в Base32, но после кодирования в результурющей строке есть символы,
|
||||
* которые можно перепутать (1 и l, O и 0, и т.д.). Т.к. целевая строка не предназначена для
|
||||
* обратной расшифровки, то мы можем безжалостно их удалить. Итоговая строка составляет 160%
|
||||
* от исходной. Поэтому, генерируя исходные случайные байты, мы должны обеспечить такую длину,
|
||||
* чтобы 160% её было равно запрошенному значению.
|
||||
* otp_secret is encoded in Base32, but after encoding there are characters in the result line
|
||||
* that can be mixed up (1 and l, O and 0, etc.). Since the target string isn't intended for
|
||||
* reverse decryption, we can safely delete them. The resulting string is 160% of the source line.
|
||||
* That's why, when generating the initial random bytes, we should provide such a length that
|
||||
* 160% of it is equal to the requested length.
|
||||
*
|
||||
* @param int $length
|
||||
* @return string
|
||||
@@ -91,6 +92,7 @@ class TwoFactorAuthInfo extends BaseAccountForm {
|
||||
$randomBytesLength = ceil($length / 1.6);
|
||||
$result = '';
|
||||
while (strlen($result) < $length) {
|
||||
/** @noinspection PhpUnhandledExceptionInspection */
|
||||
$encoded = Base32::encodeUpper(random_bytes($randomBytesLength));
|
||||
$encoded = trim($encoded, '=');
|
||||
$encoded = str_replace(['I', 'L', 'O', 'U', '1', '0'], '', $encoded);
|
||||
|
@@ -51,9 +51,8 @@ class Module extends \yii\base\Module implements BootstrapInterface {
|
||||
}
|
||||
|
||||
/**
|
||||
* Поскольку это legacy метод и документации в новой среде для него не будет,
|
||||
* нет смысла выставлять на показ внутренние url, так что ограничиваем доступ
|
||||
* только для заходов по старому домену
|
||||
* Since this is a legacy method and there will be no documentation for it in the new environment,
|
||||
* there is no point in displaying the internal API, so we are limiting access only to logons from the old domain.
|
||||
*
|
||||
* @throws NotFoundHttpException
|
||||
*/
|
||||
|
@@ -42,24 +42,24 @@ class AuthenticationController extends Controller {
|
||||
$model = new models\ValidateForm();
|
||||
$model->load(Yii::$app->request->post());
|
||||
$model->validateToken();
|
||||
// В случае успеха ожидается пустой ответ. В случае ошибки же бросается исключение,
|
||||
// которое обработает ErrorHandler
|
||||
// If successful, an empty answer is expected.
|
||||
// In case of an error, an exception is thrown which will be processed by ErrorHandler
|
||||
}
|
||||
|
||||
public function actionSignout() {
|
||||
$model = new models\SignoutForm();
|
||||
$model->load(Yii::$app->request->post());
|
||||
$model->signout();
|
||||
// В случае успеха ожидается пустой ответ. В случае ошибки же бросается исключение,
|
||||
// которое обработает ErrorHandler
|
||||
// If successful, an empty answer is expected.
|
||||
// In case of an error, an exception is thrown which will be processed by ErrorHandler
|
||||
}
|
||||
|
||||
public function actionInvalidate() {
|
||||
$model = new models\InvalidateForm();
|
||||
$model->load(Yii::$app->request->post());
|
||||
$model->invalidateToken();
|
||||
// В случае успеха ожидается пустой ответ. В случае ошибки же бросается исключение,
|
||||
// которое обработает ErrorHandler
|
||||
// If successful, an empty answer is expected.
|
||||
// In case of an error, an exception is thrown which will be processed by ErrorHandler
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ use yii\web\HttpException;
|
||||
class AuthserverException extends HttpException {
|
||||
|
||||
/**
|
||||
* Рефлексия быстрее, как ни странно:
|
||||
* Reflection is faster, weird as it may seem:
|
||||
* @url https://coderwall.com/p/cpxxxw/php-get-class-name-without-namespace#comment_19313
|
||||
*
|
||||
* @return string
|
||||
|
@@ -33,7 +33,7 @@ class AuthenticateData {
|
||||
];
|
||||
|
||||
if ($includeAvailableProfiles) {
|
||||
// Сами моянги ещё ничего не придумали с этими availableProfiles
|
||||
// The Moiangs themselves haven't come up with anything yet with these availableProfiles
|
||||
$availableProfiles[0] = $result['selectedProfile'];
|
||||
$result['availableProfiles'] = $availableProfiles;
|
||||
}
|
||||
|
@@ -56,7 +56,8 @@ class AuthenticationForm extends ApiForm {
|
||||
Authserver::error("User with login = '{$this->username}' passed wrong password.");
|
||||
}
|
||||
|
||||
// На старом сервере авторизации использовалось поле nickname, а не username, так что сохраняем эту логику
|
||||
// The previous authorization server implementation used the nickname field instead of username,
|
||||
// so we keep such behavior
|
||||
$attribute = $loginForm->getLoginAttribute();
|
||||
if ($attribute === 'username') {
|
||||
$attribute = 'nickname';
|
||||
|
@@ -30,11 +30,12 @@ class SignoutForm extends ApiForm {
|
||||
if (!$loginForm->validate()) {
|
||||
$errors = $loginForm->getFirstErrors();
|
||||
if (isset($errors['login']) && $errors['login'] === E::ACCOUNT_BANNED) {
|
||||
// Считаем, что заблокированный может безболезненно выйти
|
||||
// We believe that a blocked one can get out painlessly
|
||||
return true;
|
||||
}
|
||||
|
||||
// На старом сервере авторизации использовалось поле nickname, а не username, так что сохраняем эту логику
|
||||
// The previous authorization server implementation used the nickname field instead of username,
|
||||
// so we keep such behavior
|
||||
$attribute = $loginForm->getLoginAttribute();
|
||||
if ($attribute === 'username') {
|
||||
$attribute = 'nickname';
|
||||
|
@@ -4,8 +4,8 @@ namespace api\modules\authserver\validators;
|
||||
use api\modules\authserver\exceptions\IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* Максимальная длина clientToken для нашей базы данных составляет 255.
|
||||
* После этого мы не принимаем указанный токен
|
||||
* The maximum length of clientToken for our database is 255.
|
||||
* If the token is longer, we do not accept the passed token at all.
|
||||
*/
|
||||
class ClientTokenValidator extends \yii\validators\RequiredValidator {
|
||||
|
||||
|
@@ -4,8 +4,8 @@ namespace api\modules\authserver\validators;
|
||||
use api\modules\authserver\exceptions\IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* Для данного модуля нам не принципиально, что там за ошибка: если не хватает хотя бы одного
|
||||
* параметра - тут же отправляем исключение и дело с концом
|
||||
* For this module, it is not important for us what the error is: if at least one parameter is missing,
|
||||
* we immediately throw an exception and that's it.
|
||||
*/
|
||||
class RequiredValidator extends \yii\validators\RequiredValidator {
|
||||
|
||||
|
@@ -26,10 +26,10 @@ class ApiController extends Controller {
|
||||
->andWhere(['<=', 'applied_in', $at])
|
||||
->one();
|
||||
|
||||
// Запрос выше находит просто последний случай использования, не учитывая то, что ник
|
||||
// мог быть сменён с тех пор. Поэтому дополнительно проводим проверку, чтобы ник находился
|
||||
// в каком-либо периоде (т.е. существовала последующая запись) или последний использовавший
|
||||
// ник пользователь не сменил его на нечто иное
|
||||
// The query above simply finds the latest case of usage, without taking into account the fact
|
||||
// that the nickname may have been changed since then. Therefore, we additionally check
|
||||
// that the nickname is in some period (i.e. there is a subsequent entry) or that the last user
|
||||
// who used the nickname has not changed it to something else
|
||||
$account = null;
|
||||
if ($record !== null) {
|
||||
if ($record->account->username === $record->username || $record->findNext($at) !== null) {
|
||||
@@ -76,8 +76,8 @@ class ApiController extends Controller {
|
||||
];
|
||||
}
|
||||
|
||||
// У первого элемента не должно быть времени, когда он был применён
|
||||
// Хотя мы в принципе эту инфу знаем. А вот Mojang, вероятно, нет
|
||||
// The first element shouldn't have time when it was applied.
|
||||
// Although we know this information in fact. But Mojang probably doesn't.
|
||||
unset($data[0]['changedToAt']);
|
||||
|
||||
return $data;
|
||||
|
@@ -32,10 +32,10 @@ class OauthProcess {
|
||||
}
|
||||
|
||||
/**
|
||||
* Запрос, который должен проверить переданные параметры oAuth авторизации
|
||||
* и сформировать ответ для нашего приложения на фронте
|
||||
* A request that should check the passed OAuth2 authorization params and build a response
|
||||
* for our frontend application.
|
||||
*
|
||||
* Входными данными является стандартный список GET параметров по стандарту oAuth:
|
||||
* The input data is the standard GET parameters list according to the OAuth2 standard:
|
||||
* $_GET = [
|
||||
* client_id,
|
||||
* redirect_uri,
|
||||
@@ -44,7 +44,7 @@ class OauthProcess {
|
||||
* state,
|
||||
* ];
|
||||
*
|
||||
* Кроме того можно передать значения description для переопределения описания приложения.
|
||||
* In addition, you can pass the description value to override the application's description.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
@@ -67,10 +67,10 @@ class OauthProcess {
|
||||
}
|
||||
|
||||
/**
|
||||
* Метод выполняется генерацию авторизационного кода (authorization_code) и формирование
|
||||
* ссылки для дальнейшнешл редиректа пользователя назад на сайт клиента
|
||||
* This method generates authorization_code and a link
|
||||
* for the user's further redirect to the client's site.
|
||||
*
|
||||
* Входными данными является всё те же параметры, что были необходимы для валидации:
|
||||
* The input data are the same parameters that were necessary for validation request:
|
||||
* $_GET = [
|
||||
* client_id,
|
||||
* redirect_uri,
|
||||
@@ -79,9 +79,9 @@ class OauthProcess {
|
||||
* state,
|
||||
* ];
|
||||
*
|
||||
* А также поле accept, которое показывает, что пользователь нажал на кнопку "Принять".
|
||||
* Если поле присутствует, то оно будет интерпретироваться как любое приводимое к false значение.
|
||||
* В ином случае, значение будет интерпретировано, как положительный исход.
|
||||
* Also, the accept field, which shows that the user has clicked on the "Accept" button.
|
||||
* If the field is present, it will be interpreted as any value resulting in false positives.
|
||||
* Otherwise, the value will be interpreted as "true".
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
@@ -125,9 +125,9 @@ class OauthProcess {
|
||||
}
|
||||
|
||||
/**
|
||||
* Метод выполняется сервером приложения, которому был выдан auth_token или refresh_token.
|
||||
* The method is executed by the application server to which auth_token or refresh_token was given.
|
||||
*
|
||||
* Входными данными является стандартный список POST параметров по стандарту oAuth:
|
||||
* Input data is a standard list of POST parameters according to the OAuth2 standard:
|
||||
* $_POST = [
|
||||
* client_id,
|
||||
* client_secret,
|
||||
@@ -135,7 +135,7 @@ class OauthProcess {
|
||||
* code,
|
||||
* grant_type,
|
||||
* ]
|
||||
* для запроса grant_type = authentication_code.
|
||||
* for request with grant_type = authentication_code:
|
||||
* $_POST = [
|
||||
* client_id,
|
||||
* client_secret,
|
||||
@@ -170,8 +170,8 @@ class OauthProcess {
|
||||
}
|
||||
|
||||
/**
|
||||
* Метод проверяет, может ли текущий пользователь быть автоматически авторизован
|
||||
* для указанного клиента без запроса доступа к необходимому списку прав
|
||||
* The method checks whether the current user can be automatically authorized for the specified client
|
||||
* without requesting access to the necessary list of scopes
|
||||
*
|
||||
* @param Account $account
|
||||
* @param OauthClient $client
|
||||
@@ -206,7 +206,7 @@ class OauthProcess {
|
||||
private function buildSuccessResponse(array $queryParams, OauthClient $client, array $scopes): array {
|
||||
return [
|
||||
'success' => true,
|
||||
// Возвращаем только те ключи, которые имеют реальное отношение к oAuth параметрам
|
||||
// We return only those keys which are related to the OAuth2 standard parameters
|
||||
'oAuth' => array_intersect_key($queryParams, array_flip([
|
||||
'client_id',
|
||||
'redirect_uri',
|
||||
|
@@ -7,7 +7,7 @@ use yii\web\HttpException;
|
||||
class SessionServerException extends HttpException {
|
||||
|
||||
/**
|
||||
* Рефлексия быстрее, как ни странно:
|
||||
* Reflection is faster, weird as it may seem:
|
||||
* @url https://coderwall.com/p/cpxxxw/php-get-class-name-without-namespace#comment_19313
|
||||
*
|
||||
* @return string
|
||||
|
@@ -41,11 +41,10 @@ class LegacyJoin extends BaseJoin {
|
||||
}
|
||||
|
||||
/**
|
||||
* Метод проводит инициализацию значений полей для соотвествия общим канонам
|
||||
* именования в проекте
|
||||
* The method initializes field values to meet the general naming conventions in the project
|
||||
*
|
||||
* Бьём по ':' для учёта авторизации в современных лаунчерах и входе на более старую
|
||||
* версию игры. Там sessionId передаётся как "token:{accessToken}:{uuid}", так что это нужно обработать
|
||||
* Split by ':' to take into account authorization in modern launchers and login to an legacy version of the game.
|
||||
* The sessionId is passed on as "token:{accessToken}:{uuid}", so it needs to be processed
|
||||
*/
|
||||
private function parseSessionId(string $sessionId) {
|
||||
$parts = explode(':', $sessionId);
|
||||
|
@@ -4,8 +4,8 @@ namespace api\modules\session\validators;
|
||||
use api\modules\session\exceptions\IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* Для данного модуля нам не принципиально, что там за ошибка: если не хватает хотя бы одного
|
||||
* параметра - тут же отправляем исключение и дело с концом
|
||||
* For this module, it is not important for us what the error is: if at least one parameter is missing,
|
||||
* we immediately throw an exception and that's it.
|
||||
*/
|
||||
class RequiredValidator extends \yii\validators\RequiredValidator {
|
||||
|
||||
|
@@ -6,16 +6,15 @@ use yii\web\JsonParser;
|
||||
use yii\web\RequestParserInterface;
|
||||
|
||||
/**
|
||||
* Т.к. Yii2 не предоставляет возможности сделать fallback для неспаршенного
|
||||
* request, нужно полностью реимплементировать логику парсинга запроса.
|
||||
* Since Yii2 doesn't provide an opportunity to make a fallback for an unparsed request,
|
||||
* the query parsing logic must be fully reimplemented.
|
||||
*
|
||||
* Код взят из \yii\web\Request::getBodyParams() и вывернут таким образом,
|
||||
* чтобы по нисходящей пытаться спарсить запрос:
|
||||
* - сначала проверяем, если PHP справился сам, то возвращаем его значение
|
||||
* - дальше пробуем спарсить JSON, который закодирован в теле
|
||||
* - если не вышло, то предположим, что это PUT, DELETE или иной другой запрос,
|
||||
* который PHP автоматически не осиливает спарсить, так что пытаемся его спарсить
|
||||
* самостоятельно
|
||||
* The code is taken from \yii\web\Request::getBodyParams() and reworked in such a way
|
||||
* that it tries to parse the request by the next steps:
|
||||
* - first check if PHP has managed to do it by itself, then we return its value;
|
||||
* - then we try to parse JSON, which is encoded in the body;
|
||||
* - if it doesn't work out, let's assume it's a PUT, DELETE or other request
|
||||
* that PHP doesn't automatically overpower to parse, so we try to parse it ourselves.
|
||||
*/
|
||||
class RequestParser implements RequestParserInterface {
|
||||
|
||||
|
@@ -80,7 +80,7 @@ class GetCest {
|
||||
}
|
||||
|
||||
public function testGetInfoWithExpiredToken(FunctionalTester $I) {
|
||||
// Устанавливаем заведомо истёкший токен
|
||||
// We're setting up a known expired token
|
||||
$I->amBearerAuthenticated(
|
||||
'eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0NjQ2Mjc1NDUsImV4cCI6MTQ2NDYzMTE0NSwic3ViIjoiZWx5fDEiLCJlbHktc' .
|
||||
'2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIifQ.v1u8V5wk2RkWmnZtH3jZvM3zO1Gpgbp2DQFfLfy8jHY'
|
||||
|
@@ -55,7 +55,7 @@ class ValidateCest {
|
||||
public function expiredAccessToken(AuthserverSteps $I) {
|
||||
$I->wantTo('get error on expired accessToken');
|
||||
$this->route->validate([
|
||||
// Заведомо истёкший токен из дампа
|
||||
// Knowingly expired token from the dump
|
||||
'accessToken' => '6042634a-a1e2-4aed-866c-c661fe4e63e2',
|
||||
]);
|
||||
$I->canSeeResponseCodeIs(401);
|
||||
|
@@ -59,7 +59,7 @@ class ClientCredentialsCest {
|
||||
}
|
||||
|
||||
public function testIssueTokenWithPublicScopes(OauthSteps $I) {
|
||||
// TODO: у нас пока нет публичных скоупов, поэтому тест прогоняется с пустым набором
|
||||
// TODO: we don't have any public scopes yet for this grant, so the test runs with an empty set
|
||||
$this->route->issueToken($this->buildParams(
|
||||
'ely',
|
||||
'ZuM1vGchJz-9_UZ5HC3H3Z9Hg5PzdbkM',
|
||||
|
@@ -19,7 +19,7 @@ class TestCase extends Unit {
|
||||
}
|
||||
|
||||
/**
|
||||
* Список фикстур, что будут загружены перед тестом, но после зачистки базы данных
|
||||
* A list of fixtures that will be loaded before the test, but after the database is cleaned up
|
||||
*
|
||||
* @url http://codeception.com/docs/modules/Yii2#fixtures
|
||||
*
|
||||
|
@@ -6,13 +6,13 @@ use common\models\EmailActivation;
|
||||
use yii\validators\Validator;
|
||||
|
||||
/**
|
||||
* Валидатор для проверки полученного от пользователя кода активации.
|
||||
* В случае успешной валидации подменяет значение поля на актуальную модель
|
||||
* Validator to check the activation code received from the user.
|
||||
* In case of success it replaces the field value with the corresponding model.
|
||||
*/
|
||||
class EmailActivationKeyValidator extends Validator {
|
||||
|
||||
/**
|
||||
* @var int тип ключа. Если не указан, то валидирует по всем ключам.
|
||||
* @var int the type of key. If not specified, it validates over all keys.
|
||||
*/
|
||||
public $type;
|
||||
|
||||
|
@@ -17,17 +17,16 @@ class TotpValidator extends Validator {
|
||||
public $account;
|
||||
|
||||
/**
|
||||
* @var int|null Задаёт окно, в промежуток которого будет проверяться код.
|
||||
* Позволяет избежать ситуации, когда пользователь ввёл код в последнюю секунду
|
||||
* его существования и пока шёл запрос, тот протух.
|
||||
* Значение задаётся в +- периодах, а не секундах.
|
||||
* @var int|null Specifies the window in the interval of which the code will be checked.
|
||||
* Allows you to avoid the situation when the user entered the code in the last second of its existence
|
||||
* and while the request was being sent, it has changed. The value is set in +- periods, not seconds.
|
||||
*/
|
||||
public $window;
|
||||
|
||||
/**
|
||||
* @var int|callable|null Позволяет задать точное время, относительно которого будет
|
||||
* выполняться проверка. Это может быть собственно время или функция, возвращающая значение.
|
||||
* Если не задано, то будет использовано текущее время.
|
||||
* @var int|callable|null Allows you to set the exact time against which the validation will be performed.
|
||||
* It may be the unix time or a function returning a unix time.
|
||||
* If not specified, the current time will be used.
|
||||
*/
|
||||
public $timestamp;
|
||||
|
||||
|
Reference in New Issue
Block a user