User::findByEmailConfirmToken()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 3
c 1
b 0
f 1
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace modules\users\models;
4
5
use Yii;
6
use yii\helpers\Html;
7
use yii\helpers\ArrayHelper;
8
use modules\users\models\query\UserQuery;
9
use modules\users\Module;
10
11
/**
12
 * Class User
13
 * @package modules\users\models
14
 *
15
 * This is the model class extends IdentityUser.
16
 *
17
 * @property int $id ID
18
 * @property string $username Username
19
 * @property string $auth_key Authorization Key
20
 * @property string $password_hash Hash Password
21
 * @property string $password_reset_token Password Token
22
 * @property string $email_confirm_token Email Confirm Token
23
 * @property string $email Email
24
 * @property int|string $status Status
25
 * @property int $last_visit Last Visit
26
 * @property int $created_at Created
27
 * @property int $updated_at Updated
28
 * @property string $first_name First Name
29
 * @property string $last_name Last Name
30
 * @property string statusLabelName Status name in label
31
 * @property array statusesArray Array statuses
32
 * @property string statusName Name status
33
 * @property string $role User Role Name
34
 * @property string $password
35
 */
36
class User extends IdentityUser
37
{
38
    /**
39
     * @return mixed|null
40
     * @throws \Exception
41
     */
42
    public function getStatusName()
43
    {
44
        return ArrayHelper::getValue(self::getStatusesArray(), $this->status);
45
    }
46
47
    /**
48
     * Return <span class="label label-success">Active</span>
49
     *
50
     * @return string
51
     * @throws \Exception
52
     */
53
    public function getStatusLabelName()
54
    {
55
        $name = ArrayHelper::getValue(self::getLabelsArray(), $this->status);
56
        return Html::tag('span', $this->getStatusName(), ['class' => 'label label-' . $name]);
57
    }
58
59
    /**
60
     * @return array
61
     */
62
    public static function getLabelsArray()
63
    {
64
        return [
65
            self::STATUS_BLOCKED => 'default',
66
            self::STATUS_ACTIVE => 'success',
67
            self::STATUS_WAIT => 'warning',
68
            self::STATUS_DELETED => 'danger',
69
        ];
70
    }
71
72
    /**
73
     * @inheritdoc
74
     * @return array
75
     */
76
    public function attributeLabels()
77
    {
78
        return ArrayHelper::merge(parent::attributeLabels(), [
79
            'role' => Module::t('module', 'Role'),
80
        ]);
81
    }
82
83
    /**
84
     * @return object|\yii\db\ActiveQuery
85
     * @throws \yii\base\InvalidConfigException
86
     */
87
    public static function find()
88
    {
89
        return Yii::createObject(UserQuery::class, [get_called_class()]);
90
    }
91
92
    /**
93
     * Finds user by email
94
     *
95
     * @param string $email
96
     * @return static|null
97
     */
98
    public static function findByUsernameEmail($email)
99
    {
100
        return static::findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]);
101
    }
102
103
    /**
104
     * Finds user by username or email
105
     *
106
     * @param $string
107
     * @return array|\yii\db\ActiveRecord|null
108
     * @throws \yii\base\InvalidConfigException
109
     */
110
    public static function findByUsernameOrEmail($string)
111
    {
112
        return static::find()
113
            ->where(['or', ['username' => $string], ['email' => $string]])
114
            ->andWhere(['status' => self::STATUS_ACTIVE])
115
            ->one();
116
    }
117
118
    /**
119
     * Generates password hash from password and sets it to the model
120
     *
121
     * @param string $password
122
     * @throws \yii\base\Exception
123
     */
124
    public function setPassword($password)
125
    {
126
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
127
    }
128
129
    /**
130
     * Generates new password reset token
131
     */
132
    public function generatePasswordResetToken()
133
    {
134
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
135
    }
136
137
    /**
138
     * Removes password reset token
139
     */
140
    public function removePasswordResetToken()
141
    {
142
        $this->password_reset_token = null;
143
    }
144
145
    /**
146
     * Removes email confirmation token
147
     */
148
    public function removeEmailConfirmToken()
149
    {
150
        $this->email_confirm_token = null;
151
    }
152
153
    /**
154
     * Finds user by password reset token
155
     *
156
     * @param mixed $token password reset token
157
     * @return static|null
158
     */
159
    public static function findByPasswordResetToken($token)
160
    {
161
        if (!static::isPasswordResetTokenValid($token)) {
162
            return null;
163
        }
164
        return static::findOne([
165
            'password_reset_token' => $token,
166
            'status' => self::STATUS_ACTIVE,
167
        ]);
168
    }
169
170
    /**
171
     * @param mixed $email_confirm_token
172
     * @return bool|null|static
173
     */
174
    public static function findByEmailConfirmToken($email_confirm_token)
175
    {
176
        return static::findOne([
177
            'email_confirm_token' => $email_confirm_token,
178
            'status' => self::STATUS_WAIT
179
        ]);
180
    }
181
182
    /**
183
     * Finds user by username
184
     *
185
     * @param string $username
186
     * @return static|null|yii\db\ActiveRecord
187
     */
188
    public static function findByUsername($username)
189
    {
190
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
191
    }
192
193
    /**
194
     * Generates "remember me" authentication key
195
     */
196
    public function generateAuthKey()
197
    {
198
        $this->auth_key = Yii::$app->security->generateRandomString();
199
    }
200
201
    /**
202
     * Generates email confirmation token
203
     */
204
    public function generateEmailConfirmToken()
205
    {
206
        $this->email_confirm_token = Yii::$app->security->generateRandomString();
207
    }
208
209
    /**
210
     * Validates password
211
     *
212
     * @param string $password password to validate
213
     * @return bool if password provided is valid for current user
214
     */
215
    public function validatePassword($password)
216
    {
217
        return Yii::$app->security->validatePassword($password, $this->password_hash);
218
    }
219
220
    /**
221
     * User role
222
     * @throws \Exception
223
     */
224
    public function getRole()
225
    {
226
        return ($role = $this->getUserRoleValue($this->id)) ?
227
            Yii::t('app', $role->description) : Yii::t('app', 'Not assigned');
228
    }
229
230
    /**
231
     * @param string|int $user_id
232
     * @return mixed|null
233
     * @throws \Exception
234
     */
235
    protected function getUserRoleValue($user_id)
236
    {
237
        $authManager = Yii::$app->authManager;
238
        if ($role = $authManager->getRolesByUser($user_id)) {
239
            return ArrayHelper::getValue($role, function ($role) {
240
                foreach ($role as $key => $value) {
241
                    return $value;
242
                }
243
                return null;
244
            });
245
        }
246
        return null;
247
    }
248
249
    /**
250
     * @param string|integer $id
251
     * @return bool
252
     */
253
    public function isSuperAdmin($id = '')
254
    {
255
        $id = $id ? $id : $this->id;
256
        $authManager = Yii::$app->authManager;
257
        $roles = $authManager->getRolesByUser($id);
258
        foreach ($roles as $role) {
259
            if ($role->name == \modules\rbac\models\Role::ROLE_SUPER_ADMIN) {
260
                return true;
261
            }
262
        }
263
        return false;
264
    }
265
266
    /**
267
     * @return bool
268
     */
269
    public function isDeleted()
270
    {
271
        return $this->status === self::STATUS_DELETED;
272
    }
273
274
    /**
275
     * Finds out if password reset token is valid
276
     *
277
     * @param mixed $token password reset token
278
     * @return boolean
279
     */
280
    public static function isPasswordResetTokenValid($token)
281
    {
282
        if (empty($token)) {
283
            return false;
284
        }
285
        $expire = Yii::$app->params['users.passwordResetTokenExpire'];
286
        $parts = explode('_', $token);
287
        $timestamp = (int)end($parts);
288
        return $timestamp + $expire >= time();
289
    }
290
291
    /**
292
     * Set Status
293
     * @return int|string
294
     */
295
    public function setStatus()
296
    {
297
        switch ($this->status) {
298
            case self::STATUS_ACTIVE:
299
                $this->status = self::STATUS_BLOCKED;
300
                break;
301
            case self::STATUS_DELETED:
302
                $this->status = self::STATUS_WAIT;
303
                break;
304
            default:
305
                $this->status = self::STATUS_ACTIVE;
306
        }
307
        return $this->status;
308
    }
309
310
    /**
311
     * Actions before delete
312
     *
313
     * @return bool
314
     */
315
    public function beforeDelete()
316
    {
317
        if (parent::beforeDelete()) {
318
            // Отвязываем от ролей
319
            $authManager = Yii::$app->getAuthManager();
320
            if ($authManager->getRolesByUser($this->id)) {
321
                $authManager->revokeAll($this->id);
322
            }
323
            return true;
324
        }
325
        return false;
326
    }
327
}
328