You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

381 lines
10 KiB

7 years ago
<?php
7 years ago
namespace core\entities\user;
use core\entities\Session;
use core\events\EventTrait;
3 years ago
use DomainException;
7 years ago
use lhs\Yii2SaveRelationsBehavior\SaveRelationsBehavior;
use core\AggregateRoot;
use core\events\user\UserSignUpConfirmed;
use core\events\user\UserSignUpRequested;
use Yii;
3 years ago
use yii\base\Exception;
7 years ago
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
3 years ago
use yii\web\UploadedFile;
use zertex\avatar_generator\AvatarGenerator;
7 years ago
/**
* User model
*
* @property integer $id
* @property string $username
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property string $email_confirm_token
* @property string $auth_key
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
6 years ago
* @property string $user_pic
* @property string $backend_language
* @property string $frontend_language
* @property string $settings
7 years ago
* @property string $password write-only password
*
* @property Network[] $networks
3 years ago
* @property string $USER [char(32)]
* @property int $CURRENT_CONNECTIONS [bigint]
* @property int $TOTAL_CONNECTIONS [bigint]
7 years ago
*/
class User extends ActiveRecord implements AggregateRoot
{
use EventTrait;
const STATUS_WAIT = 0;
const STATUS_ACTIVE = 10;
3 years ago
/**
* @param string $username
* @param string $email
* @param string $password
* @return static
* @throws Exception
*/
7 years ago
public static function create(string $username, string $email, string $password): self
{
$user = new User();
7 years ago
$user->username = $username;
$user->email = $email;
7 years ago
$user->setPassword(!empty($password) ? $password : Yii::$app->security->generateRandomString());
$user->created_at = time();
$user->status = self::STATUS_ACTIVE;
$user->auth_key = Yii::$app->security->generateRandomString();
if ($user->user_pic) {
$fileName = md5('avatar-' . $user->user_pic->baseName . time()) . '.' . $user->user_pic->extension;
if ($user->user_pic->saveAs((new AvatarGenerator())->getPath('avatar') . '/' . $fileName)) {
$user->user_pic = $fileName;
}
}
6 years ago
7 years ago
return $user;
}
3 years ago
/**
* @param string $username
* @param string $email
* @param string $password
* @param null $user_pic
* @throws Exception
*/
6 years ago
public function edit(string $username, string $email, string $password, $user_pic = null): void
7 years ago
{
$this->username = $username;
$this->email = $email;
7 years ago
$this->updated_at = time();
6 years ago
if ($user_pic) {
$fileName = md5('avatar-' . $user_pic->baseName . time()) . '.' . $user_pic->extension;
if ($user_pic->saveAs((new AvatarGenerator())->getPath('avatar') . '/' . $fileName)) {
(new AvatarGenerator())->remove('avatar', $this->user_pic);
$this->user_pic = $fileName;
}
}
if ($password) {
$this->setPassword(!empty($password) ? $password : Yii::$app->security->generateRandomString());
$this->generateAuthKey();
Session::deleteAll(['user_id' => $this->id]);
}
7 years ago
}
3 years ago
/**
* @param string $email
* @param string $username
* @param string|null $password
* @param null $user_pic
* @param $language
* @throws Exception
*/
public function editProfile(
string $email,
string $username,
string $password = null,
$user_pic = null,
$language
3 years ago
): void
{
$this->email = $email;
7 years ago
$this->username = $username;
if ($password && !empty($password)) {
$this->setPassword($password);
7 years ago
}
$this->updated_at = time();
$this->backend_language = $language;
3 years ago
/* @var $user_pic UploadedFile */
if ($user_pic) {
$fileName = md5('avatar-' . $user_pic->baseName . time()) . '.' . $user_pic->extension;
$path = Yii::getAlias('@runtime/' . $fileName);
$user_pic->saveAs($path);
$this->user_pic = basename(Yii::$app->avatar->update($username, null, $path));
if (file_exists($path)) {
unlink($path);
}
}
7 years ago
}
3 years ago
/**
* @param string $username
* @param string $email
* @param string $password
* @return static
* @throws Exception
*/
7 years ago
public static function requestSignup(string $username, string $email, string $password): self
{
$user = new User();
7 years ago
$user->username = $username;
$user->email = $email;
7 years ago
$user->setPassword($password);
$user->created_at = time();
$user->status = self::STATUS_WAIT;
7 years ago
$user->email_confirm_token = Yii::$app->security->generateRandomString();
$user->generateAuthKey();
$user->recordEvent(new UserSignUpRequested($user));
7 years ago
return $user;
}
public function confirmSignup(): void
{
if (!$this->isWait()) {
3 years ago
throw new DomainException('User is already active.');
7 years ago
}
$this->status = self::STATUS_ACTIVE;
7 years ago
$this->email_confirm_token = null;
$this->recordEvent(new UserSignUpConfirmed($this));
}
3 years ago
/**
* @param $network
* @param $identity
* @return static
* @throws Exception
*/
7 years ago
public static function signupByNetwork($network, $identity): self
{
$user = new User();
7 years ago
$user->created_at = time();
$user->status = self::STATUS_ACTIVE;
7 years ago
$user->generateAuthKey();
$user->networks = [Network::create($network, $identity)];
7 years ago
return $user;
}
public function attachNetwork($network, $identity): void
{
$networks = $this->networks;
foreach ($networks as $current) {
if ($current->isFor($network, $identity)) {
3 years ago
throw new DomainException('Network is already attached.');
7 years ago
}
}
$networks[] = Network::create($network, $identity);
7 years ago
$this->networks = $networks;
}
3 years ago
/**
* @throws Exception
*/
7 years ago
public function requestPasswordReset(): void
{
if (!empty($this->password_reset_token) && self::isPasswordResetTokenValid($this->password_reset_token)) {
3 years ago
throw new DomainException(Yii::t('auth', 'Password resetting is already requested.'));
7 years ago
}
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
3 years ago
/**
* @param $password
* @throws Exception
*/
7 years ago
public function resetPassword($password): void
{
if (empty($this->password_reset_token)) {
3 years ago
throw new DomainException(Yii::t('auth', 'Password resetting is not requested.'));
7 years ago
}
$this->setPassword($password);
$this->password_reset_token = null;
}
public function isWait(): bool
{
return $this->status === self::STATUS_WAIT;
}
public function isActive(): bool
{
return $this->status === self::STATUS_ACTIVE;
}
public function getNetworks(): ActiveQuery
{
return $this->hasMany(Network::class, ['user_id' => 'id']);
7 years ago
}
/**
* @inheritdoc
*/
3 years ago
public static function tableName(): string
7 years ago
{
return '{{%users}}';
}
/**
* @inheritdoc
*/
3 years ago
public function behaviors(): array
7 years ago
{
return [
TimestampBehavior::class,
7 years ago
[
'class' => SaveRelationsBehavior::class,
7 years ago
'relations' => ['networks'],
],
];
}
public function transactions()
{
return [
self::SCENARIO_DEFAULT => self::OP_ALL,
];
}
/**
* Finds user by username
*
* @param string $username
*
7 years ago
* @return static|null
*/
3 years ago
public static function findByUsername(string $username): ?static
7 years ago
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
*
7 years ago
* @return static|null
*/
3 years ago
public static function findByPasswordResetToken(string $token): ?static
7 years ago
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
7 years ago
]);
}
/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
*
7 years ago
* @return bool
*/
3 years ago
public static function isPasswordResetTokenValid(string $token): bool
7 years ago
{
if (empty($token)) {
return false;
}
$timestamp = (int)substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
7 years ago
return $timestamp + $expire >= time();
}
/**
* Validates password
*
* @param string $password password to validate
*
7 years ago
* @return bool if password provided is valid for current user
*/
3 years ago
public function validatePassword(string $password): bool
7 years ago
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* @param $password
*
3 years ago
* @throws Exception
*/
3 years ago
public function setPassword($password)
7 years ago
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
3 years ago
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
/**
7 years ago
* Generates "remember me" authentication key
3 years ago
* @throws Exception
7 years ago
*/
3 years ago
public function generateAuthKey()
7 years ago
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
public function attributeLabels()
{
return [
'id' => Yii::t('user', 'ID'),
'username' => Yii::t('user', 'Username'),
'email' => Yii::t('user', 'E-mail'),
'status' => Yii::t('user', 'Status'),
'created_at' => Yii::t('user', 'Created At'),
'updated_at' => Yii::t('user', 'Updated At'),
];
7 years ago
}
3 years ago
/**
* Generates new password reset token
* @throws Exception
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
7 years ago
}