/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
common/models/User.php
293 строки
7 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace common\models; use common\behaviors\UniqueHashBehavior; use common\helpers\AuthHelper; use common\helpers\DateHelper; use common\helpers\UserHelper; use common\helpers\UuidHelper; use common\kdf\KModelStatus; use common\models\base\BaseModel; use common\validators\UidValidator; use Yii; use yii\base\Exception; use yii\base\InvalidConfigException; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; use yii\helpers\VarDumper; use yii\web\IdentityInterface; /** * This is the model class for table "user". * * @property string $username * @property string $auth_key * @property string $display_name * @property string $guid * @property string $last_active * @property string $email_id * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2019-2022 */ class User extends BaseModel implements IdentityInterface { // GTP.ADMIN const ADMIN = 2; /** * Время смещения относительно UTC * @var int */ public $offset = 0; /** * {@inheritdoc} */ protected $modelName = 'User'; /** * {@inheritdoc} */ public static function tableName() { return 'user'; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ ['guid', 'default', 'value' => UuidHelper::uuid()], ['rec_status', 'default', 'value' => KModelStatus::PUBLISHED], [['username', 'auth_key'], 'trim'], [['username', 'auth_key', 'rec_status', 'display_name', 'guid'], 'required'], [['auth_key'], 'string', 'max' => 255], [['guid', 'display_name'], 'string', 'max' => 50], [ ['last_active'], 'filter', 'filter' => function ($value) { return DateHelper::parse($value, true); } ], [ 'email_id', 'unique', 'message' => Yii::t('user', 'This Email has already been taken') ], [['guid'], UidValidator::class], [['guid'], 'unique'], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'username' => Yii::t('app', 'Username'), ]); } /** * {@inheritdoc} */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ 'UniqueHashBehavior' => [ 'class' => UniqueHashBehavior::class, 'hashAttribute' => 'auth_key', 'hashLength' => 32, ], ]); } /** * {@inheritdoc} */ public static function findIdentity($id) { return static::findOne(['id' => $id]); } /** * @return User|null */ public static function getCurrentUser() { return self::findIdentity(Yii::$app->user->id); } /** * @return string */ public function getTimeZoneOffset() { return $this->offset; } /** * {@inheritdoc} * @param $token * @param null $type * @return array|\yii\db\ActiveRecord * @throws \Exception */ public static function findIdentityByAccessToken($token, $type = null) { $a = User::getAlias(); return User::find() ->alias($a) ->innerJoin(['uk' => UserKey::tableName()], $a . '.id = uk.user_id') ->andWhere([ $a . '.rec_status' => KModelStatus::PUBLISHED, 'uk.is_published' => 1, 'uk.api_key' => $token, ]) ->one(); } /** * Finds user by username * * @param string $username * @return static|null */ public static function findByUsername($username) { return static::findOne(['username' => $username]); } /** * Проверяем правильность ввода пароля * * @param $password * @return bool */ public function validatePassword($password) { $password_hash = UserHelper::generateHash($password, $this->auth_key); return PasswordHash::find() ->andWhere(['password_hash' => $password_hash]) ->exists(); } /** * Создание пароля * @param $password * @return bool * @throws InvalidConfigException */ public function generatePassword($password) { $password_hash = UserHelper::generateHash($password, $this->auth_key); // сохраняем уникальный ключ доступа для авторизации $ph = PasswordHash::findOrNew([ 'password_hash' => $password_hash ]); if (!$ph->save()) { Yii::debug(VarDumper::dumpAsString($ph->errors)); return false; } return true; } /** * @throws Exception */ public function generateAuthKey() { $this->auth_key = Yii::$app->security->generateRandomString(); } /** * @inheritdoc */ public function getAuthKey() { return $this->getAttribute('auth_key'); } /** * @inheritdoc */ public function validateAuthKey($authKey) { return $this->getAttribute('auth_key') === $authKey; } /** * @inheritdoc */ public function __toString() { return $this->display_name; } /** * @inheritdoc */ public function getTitle() { return $this->display_name; } /** * Проверка доступа * * @param $permissionName * @param array $params * @return bool */ public function can($permissionName, $params = []) { return Yii::$app->user->accessChecker->checkAccess($this->id, $permissionName, $params); } /** * Получить ссылку на вход * * @param $user_id * @return string * @throws InvalidConfigException */ public static function authUrl($user_id) { return AuthHelper::getUrl(['/auth/login'], ['user_id' => $user_id]); } /** * Получить состояние фильтра для пользователя * * @param int $filter_id Идентификатор фильтра * @return mixed|null Результат выбранного фильтра */ public function getFilter($filter_id) { Yii::debug(VarDumper::dumpAsString([ 'filter' => $filter_id ])); return Yii::$app->session->get('filter-' . $filter_id); } /** * @return ActiveQuery */ public function getEmail() { return $this->hasOne(Email::class, ['id' => 'email_id']); } }