Passed
Push — master ( fefe57...032773 )
by Alexey
02:27
created

User::generateAuthKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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 int|string $registration_type Type Registration
31
 * @property string statusLabelName Status name in label
32
 * @property array statusesArray Array statuses
33
 * @property string statusName Name status
34
 * @property int|string registrationType Type registered
35
 * @property string $role User Role Name
36
 */
37
class User extends IdentityUser
38
{
39
    public $role;
40
41
    /**
42
     * @return mixed
43
     */
44
    public function getStatusName()
45
    {
46
        return ArrayHelper::getValue(self::getStatusesArray(), $this->status);
47
    }
48
49
    /**
50
     * Return <span class="label label-success">Active</span>
51
     * @return string
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
     * @return object|\yii\db\ActiveQuery
84
     * @throws \yii\base\InvalidConfigException
85
     */
86
    public static function find()
87
    {
88
        return Yii::createObject(UserQuery::class, [get_called_class()]);
89
    }
90
91
    /**
92
     * Finds user by email
93
     *
94
     * @param string $email
95
     * @return static|null
96
     */
97
    public static function findByUsernameEmail($email)
98
    {
99
        return static::findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]);
100
    }
101
102
    /**
103
     * Finds user by username or email
104
     *
105
     * @param string $string
106
     * @return static|null
107
     * @throws \yii\base\InvalidConfigException
108
     */
109
    public static function findByUsernameOrEmail($string)
110
    {
111
        return static::find()
112
            ->where(['or', ['username' => $string], ['email' => $string]])
113
            ->andWhere(['status' => self::STATUS_ACTIVE])
114
            ->one();
115
    }
116
117
    /**
118
     * Generates password hash from password and sets it to the model
119
     *
120
     * @param string $password
121
     * @throws \yii\base\Exception
122
     */
123
    public function setPassword($password)
124
    {
125
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
126
    }
127
128
    /**
129
     * Generates new password reset token
130
     */
131
    public function generatePasswordResetToken()
132
    {
133
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
134
    }
135
136
    /**
137
     * Removes password reset token
138
     */
139
    public function removePasswordResetToken()
140
    {
141
        $this->password_reset_token = null;
142
    }
143
144
    /**
145
     * Removes email confirmation token
146
     */
147
    public function removeEmailConfirmToken()
148
    {
149
        $this->email_confirm_token = null;
150
    }
151
152
    /**
153
     * Finds user by password reset token
154
     *
155
     * @param mixed $token password reset token
156
     * @return static|null
157
     */
158
    public static function findByPasswordResetToken($token)
159
    {
160
        if (!static::isPasswordResetTokenValid($token)) {
161
            return null;
162
        }
163
        return static::findOne([
164
            'password_reset_token' => $token,
165
            'status' => self::STATUS_ACTIVE,
166
        ]);
167
    }
168
169
    /**
170
     * @param mixed $email_confirm_token
171
     * @return bool|null|static
172
     */
173
    public static function findByEmailConfirmToken($email_confirm_token)
174
    {
175
        return static::findOne([
176
            'email_confirm_token' => $email_confirm_token,
177
            'status' => self::STATUS_WAIT
178
        ]);
179
    }
180
181
    /**
182
     * Finds user by username
183
     *
184
     * @param string $username
185
     * @return static|null|yii\db\ActiveRecord
186
     */
187
    public static function findByUsername($username)
188
    {
189
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
190
    }
191
192
    /**
193
     * Generates "remember me" authentication key
194
     */
195
    public function generateAuthKey()
196
    {
197
        $this->auth_key = Yii::$app->security->generateRandomString();
198
    }
199
200
    /**
201
     * Generates email confirmation token
202
     */
203
    public function generateEmailConfirmToken()
204
    {
205
        $this->email_confirm_token = Yii::$app->security->generateRandomString();
206
    }
207
208
    /**
209
     * Validates password
210
     *
211
     * @param string $password password to validate
212
     * @return bool if password provided is valid for current user
213
     */
214
    public function validatePassword($password)
215
    {
216
        return Yii::$app->security->validatePassword($password, $this->password_hash);
217
    }
218
219
    /**
220
     * Type of registration
221
     * How the user is created
222
     * If the system registration type is registered by itself,
223
     * if it is created from the admin area,
224
     * then the login type that created the account
225
     *
226
     * @return mixed|string
227
     */
228
    public function getRegistrationType()
229
    {
230
        if ($this->registration_type > 0) {
231
            if (($model = User::findOne($this->registration_type)) !== null) {
232
                return $model->username;
233
            }
234
        }
235
        return $this->getRegistrationTypeName();
236
    }
237
238
    /**
239
     * Returns the registration type string
240
     * @return mixed
241
     */
242
    public function getRegistrationTypeName()
243
    {
244
        return ArrayHelper::getValue(self::getRegistrationTypesArray(), $this->registration_type);
245
    }
246
247
    /**
248
     * Returns an array of log types
249
     * @return array
250
     */
251
    public static function getRegistrationTypesArray()
252
    {
253
        return [
254
            self::TYPE_REGISTRATION_SYSTEM => Module::t('module', 'System'),
255
        ];
256
    }
257
258
    /**
259
     * @param string|integer $id
260
     * @return bool
261
     */
262
    public function isSuperAdmin($id = '')
263
    {
264
        $id = $id ? $id : $this->id;
265
        $authManager = Yii::$app->authManager;
266
        $roles = $authManager->getRolesByUser($id);
267
        foreach ($roles as $role) {
268
            if ($role->name == \modules\rbac\models\Role::ROLE_SUPER_ADMIN)
269
                return true;
270
        }
271
        return false;
272
    }
273
274
    /**
275
     * @return bool
276
     */
277
    public function isDeleted()
278
    {
279
        return $this->status === self::STATUS_DELETED;
280
    }
281
282
    /**
283
     * Finds out if password reset token is valid
284
     *
285
     * @param mixed $token password reset token
286
     * @return boolean
287
     */
288
    public static function isPasswordResetTokenValid($token)
289
    {
290
        if (empty($token)) {
291
            return false;
292
        }
293
        $expire = Yii::$app->params['users.passwordResetTokenExpire'];
294
        $parts = explode('_', $token);
295
        $timestamp = (int)end($parts);
296
        return $timestamp + $expire >= time();
297
    }
298
299
    /**
300
     * Set Status
301
     * @return int|string
302
     */
303
    public function setStatus()
304
    {
305
        switch ($this->status) {
306
            case self::STATUS_ACTIVE:
307
                $this->status = self::STATUS_BLOCKED;
308
                break;
309
            case self::STATUS_DELETED:
310
                $this->status = self::STATUS_WAIT;
311
                break;
312
            default:
313
                $this->status = self::STATUS_ACTIVE;
314
        }
315
        return $this->status;
316
    }
317
}
318