Translate all code comments from Russian to English [skip ci]

This commit is contained in:
ErickSkrauch
2019-07-15 01:59:56 +03:00
parent 31069562b3
commit 3dbf29d34c
64 changed files with 264 additions and 286 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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