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:
@@ -7,7 +7,7 @@ use yii\helpers\ArrayHelper;
|
||||
class DataBehavior extends Behavior {
|
||||
|
||||
/**
|
||||
* @var string имя атрибута, к которому будет применяться поведение
|
||||
* @var string attribute name to which this behavior will be applied
|
||||
*/
|
||||
public $attribute = '_data';
|
||||
|
||||
@@ -31,8 +31,8 @@ class DataBehavior extends Behavior {
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws \yii\base\ErrorException Yii2 подхватит Notice от неправильной десериализаци и превратит его
|
||||
* в свой Exception, благодаря чему программа сможем продолжить нормально работать (вернее ловить Exception)
|
||||
* @throws \yii\base\ErrorException Yii2 will catch Notice from the wrong deserialization and turn it
|
||||
* into its own Exception, so that the program can continue to work normally (you still should catch an Exception)
|
||||
*/
|
||||
private function getData() {
|
||||
$data = $this->owner->{$this->attribute};
|
||||
|
@@ -9,23 +9,23 @@ use yii\base\Behavior;
|
||||
class EmailActivationExpirationBehavior extends Behavior {
|
||||
|
||||
/**
|
||||
* @var int количество секунд, прежде чем можно будет повторить отправку кода
|
||||
* @var int the number of seconds before the code can be sent again
|
||||
* @see EmailActivation::canRepeat()
|
||||
*/
|
||||
public $repeatTimeout;
|
||||
|
||||
/**
|
||||
* @var int количество секунд, прежде чем это подтверждение истечёт
|
||||
* @var int the number of seconds before this activation expires
|
||||
* @see EmailActivation::isExpired()
|
||||
*/
|
||||
public $expirationTimeout;
|
||||
|
||||
/**
|
||||
* Можно ли повторить отправку письма текущего типа?
|
||||
* Для проверки используется значение EmailActivation::$repeatTimeout и интерпретируется как:
|
||||
* - <0 запретит повторную отправку этого кода
|
||||
* - =0 позволит отправлять сообщения в любой момент
|
||||
* - >0 будет проверять, сколько секунд прошло с момента создания модели
|
||||
* Is it allowed to resend a message of the current type?
|
||||
* The value of EmailActivation::$repeatTimeout is used for checking as follows:
|
||||
* - <0 will forbid you to resend this activation
|
||||
* - =0 allows you to send messages at any time
|
||||
* - >0 will check how many seconds have passed since the model was created
|
||||
*
|
||||
* @see EmailActivation::compareTime()
|
||||
* @return bool
|
||||
@@ -35,11 +35,11 @@ class EmailActivationExpirationBehavior extends Behavior {
|
||||
}
|
||||
|
||||
/**
|
||||
* Истёк ли срок кода?
|
||||
* Для проверки используется значение EmailActivation::$expirationTimeout и интерпретируется как:
|
||||
* - <0 означает, что код никогда не истечёт
|
||||
* - =0 всегда будет говорить, что код истёк
|
||||
* - >0 будет проверять, сколько секунд прошло с момента создания модели
|
||||
* Did the code expire?
|
||||
* The value of EmailActivation::$expirationTimeout is used for checking as follows:
|
||||
* - <0 means the code will never expire
|
||||
* - =0 will always say that the code has expired
|
||||
* - >0 will check how many seconds have passed since the model was created
|
||||
*
|
||||
* @see EmailActivation::compareTime()
|
||||
* @return bool
|
||||
@@ -48,25 +48,15 @@ class EmailActivationExpirationBehavior extends Behavior {
|
||||
return $this->compareTime($this->expirationTimeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Вычисляет, во сколько можно будет выполнить повторную отправку кода
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function canRepeatIn(): int {
|
||||
return $this->calculateTime($this->repeatTimeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Вычисляет, во сколько код истечёт
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function expireIn(): int {
|
||||
return $this->calculateTime($this->expirationTimeout);
|
||||
}
|
||||
|
||||
protected function compareTime(int $value): bool {
|
||||
private function compareTime(int $value): bool {
|
||||
if ($value < 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -78,7 +68,7 @@ class EmailActivationExpirationBehavior extends Behavior {
|
||||
return time() > $this->calculateTime($value);
|
||||
}
|
||||
|
||||
protected function calculateTime(int $value): int {
|
||||
private function calculateTime(int $value): int {
|
||||
return $this->owner->created_at + $value;
|
||||
}
|
||||
|
||||
|
@@ -11,10 +11,11 @@ use yii\db\ActiveRecord;
|
||||
class PrimaryKeyValueBehavior extends Behavior {
|
||||
|
||||
/**
|
||||
* @var callable Функция, что будет вызвана для генерации ключа.
|
||||
* Должна возвращать случайное значение, подходящее для логики модели. Функция будет вызываться
|
||||
* в цикле do-while с целью избежания дубликатов строк по первичному ключу, так что если функция
|
||||
* станет возвращать статичное значение, то программа зациклится и что-нибудь здохнет. Не делайте так.
|
||||
* @var callable The function that will be called to generate the key.
|
||||
* Must return a random value suitable for model logic.
|
||||
* The function will be called in the do-while loop to avoid duplicate strings by the primary key,
|
||||
* so if the function returns a static value, the program will loop forever and something will die.
|
||||
* Don't do so.
|
||||
*/
|
||||
public $value;
|
||||
|
||||
@@ -60,7 +61,6 @@ class PrimaryKeyValueBehavior extends Behavior {
|
||||
throw new InvalidConfigException('Current behavior don\'t support models with more then one primary key.');
|
||||
}
|
||||
|
||||
/** @noinspection PhpIncompatibleReturnTypeInspection да как бы оно всё нормально, но шторм мне не верит */
|
||||
return $primaryKeys[0];
|
||||
}
|
||||
|
||||
|
@@ -2,8 +2,9 @@
|
||||
namespace common\components;
|
||||
|
||||
/**
|
||||
* Этот класс был использован для изначальной генерации паролей на Ely.by и сейчас должен быть планомерно выпилен
|
||||
* с проекта с целью заменить этот алгоритм каким-нибудь посерьёзнее.
|
||||
* This class was used for the first generation of passwords on the Ely.by
|
||||
* and should now be systematically cut from the project in order to replace this algorithm
|
||||
* with a more secure one.
|
||||
*/
|
||||
class UserPass {
|
||||
|
||||
|
@@ -24,31 +24,31 @@ class ConfigLoader {
|
||||
require __DIR__ . '/config.php',
|
||||
];
|
||||
|
||||
// Общие окружение-зависимые настройки
|
||||
// Common env-dependent configuration
|
||||
$path = __DIR__ . '/config-' . YII_ENV . '.php';
|
||||
if (file_exists($path)) {
|
||||
$toMerge[] = require $path;
|
||||
}
|
||||
|
||||
// Общие локальные настройки
|
||||
// Common local configuration
|
||||
$path = __DIR__ . '/config-local.php';
|
||||
if (file_exists($path)) {
|
||||
$toMerge[] = require $path;
|
||||
}
|
||||
|
||||
// Настройки конкретного приложения
|
||||
// App-related base configuration
|
||||
$path = self::ROOT_PATH . '/' . $this->application . '/config/config.php';
|
||||
if (file_exists($path)) {
|
||||
$toMerge[] = require $path;
|
||||
}
|
||||
|
||||
// Настройки конкретного приложения для действующего окружения
|
||||
// App-related env-dependent configuration
|
||||
$path = self::ROOT_PATH . '/' . $this->application . '/config/config-' . YII_ENV . '.php';
|
||||
if (file_exists($path)) {
|
||||
$toMerge[] = require $path;
|
||||
}
|
||||
|
||||
// Локальные настройки конкретного приложения
|
||||
// App-related local configuration
|
||||
$path = self::ROOT_PATH . '/' . $this->application . '/config/config-local.php';
|
||||
if (file_exists($path)) {
|
||||
$toMerge[] = require $path;
|
||||
|
@@ -24,12 +24,6 @@ class StringHelper {
|
||||
return $mask . mb_substr($email, $usernameLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет на то, что переданная строка является валидным UUID
|
||||
*
|
||||
* @param string $uuid
|
||||
* @return bool
|
||||
*/
|
||||
public static function isUuid(string $uuid): bool {
|
||||
try {
|
||||
Uuid::fromString($uuid);
|
||||
|
@@ -13,7 +13,7 @@ use yii\db\ActiveRecord;
|
||||
use const common\LATEST_RULES_VERSION;
|
||||
|
||||
/**
|
||||
* Поля модели:
|
||||
* Fields:
|
||||
* @property integer $id
|
||||
* @property string $uuid
|
||||
* @property string $username
|
||||
@@ -30,11 +30,11 @@ use const common\LATEST_RULES_VERSION;
|
||||
* @property integer $updated_at
|
||||
* @property integer $password_changed_at
|
||||
*
|
||||
* Геттеры-сеттеры:
|
||||
* @property string $password пароль пользователя (только для записи)
|
||||
* @property string $profileLink ссылка на профиль на Ely без поддержки static url (только для записи)
|
||||
* Getters-setters:
|
||||
* @property-write string $password plain user's password
|
||||
* @property-read string $profileLink link to the user's Ely.by profile
|
||||
*
|
||||
* Отношения:
|
||||
* Relations:
|
||||
* @property EmailActivation[] $emailActivations
|
||||
* @property OauthSession[] $oauthSessions
|
||||
* @property OauthClient[] $oauthClients
|
||||
@@ -42,7 +42,7 @@ use const common\LATEST_RULES_VERSION;
|
||||
* @property AccountSession[] $sessions
|
||||
* @property MinecraftAccessKey[] $minecraftAccessKeys
|
||||
*
|
||||
* Поведения:
|
||||
* Behaviors:
|
||||
* @mixin TimestampBehavior
|
||||
*/
|
||||
class Account extends ActiveRecord {
|
||||
@@ -113,11 +113,6 @@ class Account extends ActiveRecord {
|
||||
return $this->hasMany(MinecraftAccessKey::class, ['account_id' => 'id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выполняет проверку, принадлежит ли этому нику аккаунт у Mojang
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasMojangUsernameCollision(): bool {
|
||||
return MojangUsername::find()
|
||||
->andWhere(['username' => $this->username])
|
||||
@@ -125,9 +120,8 @@ class Account extends ActiveRecord {
|
||||
}
|
||||
|
||||
/**
|
||||
* Т.к. у нас нет инфы по static_url пользователя, то пока генерируем самый простой вариант
|
||||
* с ссылкой на профиль по id. На Ely он всё равно редиректнется на static, а мы так или
|
||||
* иначе обеспечим отдачу этой инфы.
|
||||
* Since we don't have info about the user's static_url, we still generate the simplest
|
||||
* version with a link to the profile by it's id. On Ely.by, it will be redirected to static url.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
@@ -136,10 +130,10 @@ class Account extends ActiveRecord {
|
||||
}
|
||||
|
||||
/**
|
||||
* При создании структуры БД все аккаунты получают null значение в это поле, однако оно
|
||||
* обязательно для заполнения. Все мигрировавшие с Ely аккаунты будут иметь null значение,
|
||||
* а актуальной версией будет 1 версия правил сайта (т.к. раньше их просто не было). Ну а
|
||||
* дальше уже будем инкрементить.
|
||||
* Initially, the table of users we got from the main site, where there were no rules.
|
||||
* All existing users at the time of migration received an empty value in this field.
|
||||
* They will have to confirm their agreement with the rules at the first login.
|
||||
* All new users automatically agree with the current version of the rules.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
|
@@ -7,7 +7,7 @@ use yii\db\ActiveQuery;
|
||||
use yii\db\ActiveRecord;
|
||||
|
||||
/**
|
||||
* Поля модели:
|
||||
* Fields:
|
||||
* @property integer $id
|
||||
* @property integer $account_id
|
||||
* @property string $refresh_token
|
||||
@@ -15,10 +15,10 @@ use yii\db\ActiveRecord;
|
||||
* @property integer $created_at
|
||||
* @property integer $last_refreshed_at
|
||||
*
|
||||
* Отношения:
|
||||
* Relations:
|
||||
* @property Account $account
|
||||
*
|
||||
* Поведения:
|
||||
* Behaviors:
|
||||
* @mixin TimestampBehavior
|
||||
*/
|
||||
class AccountSession extends ActiveRecord {
|
||||
|
@@ -11,17 +11,17 @@ use yii\db\ActiveRecord;
|
||||
use yii\helpers\ArrayHelper;
|
||||
|
||||
/**
|
||||
* Поля модели:
|
||||
* Fields:
|
||||
* @property string $key
|
||||
* @property integer $account_id
|
||||
* @property integer $type
|
||||
* @property string $_data
|
||||
* @property integer $created_at
|
||||
*
|
||||
* Отношения:
|
||||
* Relations:
|
||||
* @property Account $account
|
||||
*
|
||||
* Поведения:
|
||||
* Behaviors:
|
||||
* @mixin TimestampBehavior
|
||||
* @mixin EmailActivationExpirationBehavior
|
||||
* @mixin DataBehavior
|
||||
|
@@ -8,22 +8,21 @@ use yii\db\ActiveQuery;
|
||||
use yii\db\ActiveRecord;
|
||||
|
||||
/**
|
||||
* Это временный класс, куда мигрирует вся логика ныне существующего authserver.ely.by.
|
||||
* Поскольку там допускался вход по логину и паролю, а формат хранения выданных токенов был
|
||||
* иным, то на период, пока мы окончательно не мигрируем, нужно сохранить старую логику
|
||||
* и структуру под неё.
|
||||
* This is a temporary class where all the logic of the authserver.ely.by service.
|
||||
* Since the login and password were allowed there, and the format of storage of the issued tokens was different,
|
||||
* we need to keep the legacy logic and structure under it for the period until we finally migrate.
|
||||
*
|
||||
* Поля модели:
|
||||
* Fields:
|
||||
* @property string $access_token
|
||||
* @property string $client_token
|
||||
* @property integer $account_id
|
||||
* @property integer $created_at
|
||||
* @property integer $updated_at
|
||||
*
|
||||
* Отношения:
|
||||
* Relations:
|
||||
* @property Account $account
|
||||
*
|
||||
* Поведения:
|
||||
* Behaviors:
|
||||
* @mixin TimestampBehavior
|
||||
* @mixin PrimaryKeyValueBehavior
|
||||
*/
|
||||
|
@@ -5,12 +5,12 @@ use yii\behaviors\TimestampBehavior;
|
||||
use yii\db\ActiveRecord;
|
||||
|
||||
/**
|
||||
* Поля модели:
|
||||
* Fields:
|
||||
* @property string $username
|
||||
* @property string $uuid
|
||||
* @property integer $last_pulled_at
|
||||
*
|
||||
* Поведения:
|
||||
* Behaviors:
|
||||
* @mixin TimestampBehavior
|
||||
*/
|
||||
class MojangUsername extends ActiveRecord {
|
||||
|
@@ -7,7 +7,7 @@ use yii\db\ActiveQuery;
|
||||
use yii\db\ActiveRecord;
|
||||
|
||||
/**
|
||||
* Поля модели:
|
||||
* Fields:
|
||||
* @property string $id
|
||||
* @property string $secret
|
||||
* @property string $type
|
||||
@@ -21,7 +21,7 @@ use yii\db\ActiveRecord;
|
||||
* @property bool $is_deleted
|
||||
* @property integer $created_at
|
||||
*
|
||||
* Отношения:
|
||||
* Behaviors:
|
||||
* @property Account|null $account
|
||||
* @property OauthSession[] $sessions
|
||||
*/
|
||||
|
@@ -4,19 +4,19 @@ namespace common\models;
|
||||
final class OauthOwnerType {
|
||||
|
||||
/**
|
||||
* Используется для сессий, принадлежащих непосредственно пользователям account.ely.by,
|
||||
* выполнивших парольную авторизацию и использующих web интерфейс
|
||||
* Used for sessions belonging directly to account.ely.by users
|
||||
* who have performed password authentication and are using the web interface
|
||||
*/
|
||||
public const ACCOUNT = 'accounts';
|
||||
|
||||
/**
|
||||
* Используется когда пользователь по протоколу oAuth2 authorization_code
|
||||
* разрешает приложению получить доступ и выполнять действия от своего имени
|
||||
* Used when a user uses OAuth2 authorization_code protocol to allow an application
|
||||
* to access and perform actions on its own behalf
|
||||
*/
|
||||
public const USER = 'user';
|
||||
|
||||
/**
|
||||
* Используется для авторизованных по протоколу oAuth2 client_credentials
|
||||
* Used for clients authorized via OAuth2 client_credentials protocol
|
||||
*/
|
||||
public const CLIENT = 'client';
|
||||
|
||||
|
@@ -9,15 +9,15 @@ use yii\db\ActiveQuery;
|
||||
use yii\db\ActiveRecord;
|
||||
|
||||
/**
|
||||
* Поля:
|
||||
* Fields:
|
||||
* @property integer $id
|
||||
* @property string $owner_type содержит одну из констант OauthOwnerType
|
||||
* @property string $owner_type contains one of the OauthOwnerType constants
|
||||
* @property string|null $owner_id
|
||||
* @property string $client_id
|
||||
* @property string $client_redirect_uri
|
||||
* @property integer $created_at
|
||||
*
|
||||
* Отношения
|
||||
* Relations:
|
||||
* @property OauthClient $client
|
||||
* @property Account $account
|
||||
* @property Set $scopes
|
||||
|
@@ -5,16 +5,16 @@ use yii\behaviors\TimestampBehavior;
|
||||
use yii\db\ActiveRecord;
|
||||
|
||||
/**
|
||||
* Поля модели:
|
||||
* Fields:
|
||||
* @property integer $id
|
||||
* @property string $username
|
||||
* @property integer $account_id
|
||||
* @property integer $applied_in
|
||||
*
|
||||
* Отношения:
|
||||
* Relations:
|
||||
* @property Account $account
|
||||
*
|
||||
* Поведения:
|
||||
* Behaviors:
|
||||
* @mixin TimestampBehavior
|
||||
*/
|
||||
class UsernameHistory extends ActiveRecord {
|
||||
|
@@ -5,7 +5,7 @@ use common\models\EmailActivation;
|
||||
use yii\helpers\ArrayHelper;
|
||||
|
||||
/**
|
||||
* Поведения:
|
||||
* Behaviors:
|
||||
* @mixin NewEmailConfirmationBehavior
|
||||
*/
|
||||
class NewEmailConfirmation extends EmailActivation {
|
||||
|
@@ -7,12 +7,11 @@ use yii\rbac\PhpManager;
|
||||
class Manager extends PhpManager {
|
||||
|
||||
/**
|
||||
* В нашем приложении права выдаются не пользователям, а токенам, так что ожидаем
|
||||
* здесь $accessToken и извлекаем из него все присвоенные права.
|
||||
* In our application the permissions are given not to users but to tokens,
|
||||
* so we receive $accessToken here and extract all the assigned scopes from it.
|
||||
*
|
||||
* По каким-то причинам, в Yii механизм рекурсивной проверки прав требует, чтобы
|
||||
* массив с правами был проиндексирован по ключам этих самых прав, так что в
|
||||
* конце выворачиваем массив наизнанку.
|
||||
* In Yii2, the mechanism of recursive permissions checking requires that the array with permissions
|
||||
* is indexed by the keys of these rights, so at the end we turn the array inside out.
|
||||
*
|
||||
* @param string $accessToken
|
||||
* @return string[]
|
||||
|
@@ -10,15 +10,15 @@ class AccountOwner extends Rule {
|
||||
public $name = 'account_owner';
|
||||
|
||||
/**
|
||||
* В нашем приложении права выдаются не пользователям, а токенам, так что ожидаем
|
||||
* здесь $accessToken, по которому дальше восстанавливаем аккаунт, если это возможно.
|
||||
* In our application the permissions are given not to users but to tokens,
|
||||
* so we receive $accessToken here and extract all the assigned scopes from it.
|
||||
*
|
||||
* @param string|int $accessToken
|
||||
* @param \yii\rbac\Item $item
|
||||
* @param array $params параметр accountId нужно передать обязательно как id аккаунта,
|
||||
* к которому выполняется запрос
|
||||
* параметр optionalRules позволяет отключить обязательность
|
||||
* принятия последней версии правил
|
||||
* @param array $params the "accountId" parameter must be passed as the id of the account
|
||||
* to which the request is made
|
||||
* the "optionalRules" parameter allows you to disable the mandatory acceptance
|
||||
* of the latest version of the rules
|
||||
*
|
||||
* @return bool a value indicating whether the rule permits the auth item it is associated with.
|
||||
*/
|
||||
|
@@ -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
|
||||
*
|
||||
|
@@ -13,8 +13,8 @@ use yii\validators\Validator;
|
||||
class EmailValidator extends Validator {
|
||||
|
||||
/**
|
||||
* @var \Closure функция должна возвращать id аккаунта, относительно которого проводится
|
||||
* текущая валидация. Позволяет пропустить проверку email для текущего аккаунта.
|
||||
* @var \Closure the function must return the account id for which the current validation is being performed.
|
||||
* Allows you to skip the email check for the current account.
|
||||
*/
|
||||
public $accountCallback;
|
||||
|
||||
|
@@ -4,9 +4,6 @@ namespace common\validators;
|
||||
use common\helpers\Error as E;
|
||||
use yii\validators\StringValidator;
|
||||
|
||||
/**
|
||||
* Класс должен реализовывать в себе все критерии валидации пароля пользователя
|
||||
*/
|
||||
class PasswordValidator extends StringValidator {
|
||||
|
||||
public $min = 8;
|
||||
|
@@ -12,8 +12,8 @@ use yii\validators\Validator;
|
||||
class UsernameValidator extends Validator {
|
||||
|
||||
/**
|
||||
* @var \Closure функция должна возвращать id аккаунта, относительно которого проводится
|
||||
* текущая валидация. Позволяет пропустить проверку ника для текущего аккаунта.
|
||||
* @var \Closure the function must return the account id for which the current validation is being performed.
|
||||
* Allows you to skip the username check for the current account.
|
||||
*/
|
||||
public $accountCallback;
|
||||
|
||||
|
Reference in New Issue
Block a user