Passed
Push — master ( 40d7bb...2ec62b )
by Alexey
02:41
created

IdentityUser::setPassword()   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 1
1
<?php
2
3
namespace modules\users\models;
4
5
use Yii;
6
use yii\helpers\Html;
7
use yii\behaviors\TimestampBehavior;
8
use yii2tech\ar\softdelete\SoftDeleteBehavior;
9
use yii\db\ActiveRecord;
10
use yii\web\IdentityInterface;
11
use modules\users\traits\ModuleTrait;
12
use modules\users\Module;
13
14
/**
15
 * Class IdentityUser
16
 * @package modules\users\models
17
 *
18
 * This is the model class for table "{{%user}}".
19
 *
20
 * @property int $id ID
21
 * @property string $username Username
22
 * @property string $auth_key Authorization Key
23
 * @property string $password_hash Hash Password
24
 * @property string $password_reset_token Password Token
25
 * @property string $email_confirm_token Email Confirm Token
26
 * @property string $email Email
27
 * @property int|string $status Status
28
 * @property int $last_visit Last Visit
29
 * @property int $created_at Created
30
 * @property int $updated_at Updated
31
 * @property string $first_name First Name
32
 * @property string $last_name Last Name
33
 */
34
class IdentityUser extends ActiveRecord implements IdentityInterface
35
{
36
    use ModuleTrait;
37
38
    // Status
39
    const STATUS_BLOCKED = 0;
40
    const STATUS_ACTIVE = 1;
41
    const STATUS_WAIT = 2;
42
    const STATUS_DELETED = 3;
43
44
    // Type of registration
45
    const TYPE_REGISTRATION_SYSTEM = 0;
46
47
    /**
48
     * @inheritdoc
49
     * @return string
50
     */
51
    public static function tableName()
52
    {
53
        return '{{%user}}';
54
    }
55
56
    /**
57
     * @inheritdoc
58
     * @return array
59
     */
60
    public function behaviors()
61
    {
62
        return [
63
            'timestamp' => [
64
                'class' => TimestampBehavior::class,
65
            ],
66
            'softDeleteBehavior' => [
67
                'class' => SoftDeleteBehavior::class,
68
                'softDeleteAttributeValues' => [
69
                    'status' => self::STATUS_DELETED,
70
                ],
71
            ],
72
        ];
73
    }
74
75
    /**
76
     * @inheritdoc
77
     * @return array
78
     */
79
    public function rules()
80
    {
81
        return [
82
            ['username', 'required'],
83
            ['username', 'match', 'pattern' => '#^[\w_-]+$#i'],
84
            ['username', 'unique', 'targetClass' => self::class, 'message' => Module::t('module', 'This username is already taken.')],
85
            ['username', 'string', 'min' => 2, 'max' => 255],
86
87
            ['email', 'required'],
88
            ['email', 'email'],
89
            ['email', 'unique', 'targetClass' => self::class, 'message' => Module::t('module', 'This email is already taken.')],
90
            ['email', 'string', 'max' => 255],
91
92
            [['first_name', 'last_name'], 'string', 'max' => 45],
93
            [['registration_type'], 'safe'],
94
        ];
95
    }
96
97
    /**
98
     * @inheritdoc
99
     * @return array
100
     */
101
    public function attributeLabels()
102
    {
103
        return [
104
            'id' => 'ID',
105
            'created_at' => Module::t('module', 'Created'),
106
            'updated_at' => Module::t('module', 'Updated'),
107
            'last_visit' => Module::t('module', 'Last Visit'),
108
            'username' => Module::t('module', 'Username'),
109
            'email' => Module::t('module', 'Email'),
110
            'auth_key' => Module::t('module', 'Auth Key'),
111
            'status' => Module::t('module', 'Status'),
112
            'first_name' => Module::t('module', 'First Name'),
113
            'last_name' => Module::t('module', 'Last Name'),
114
            'registration_type' => Module::t('module', 'Registration Type'),
115
        ];
116
    }
117
118
    /**
119
     * @inheritdoc
120
     * @param int|string $id
121
     * @return IdentityInterface
122
     */
123
    public static function findIdentity($id)
124
    {
125
        /** @var IdentityInterface $result */
126
        $result = static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
127
        return $result;
128
    }
129
130
    /**
131
     * @inheritdoc
132
     * @param mixed $token
133
     * @param mixed $type
134
     * @return IdentityInterface
135
     */
136
    public static function findIdentityByAccessToken($token, $type = null)
137
    {
138
        /** @var IdentityInterface $result */
139
        $result = static::findOne(['auth_key' => $token, 'status' => self::STATUS_ACTIVE]);
140
        return $result;
141
    }
142
143
    /**
144
     * @return integer
145
     */
146
    public function getId()
147
    {
148
        return $this->id;
149
    }
150
151
    /**
152
     * @return string current user auth key
153
     */
154
    public function getAuthKey()
155
    {
156
        return $this->auth_key;
157
    }
158
159
    /**
160
     * @param string|mixed $authKey
161
     * @return bool if auth key is valid for current user
162
     */
163
    public function validateAuthKey($authKey)
164
    {
165
        return $this->getAuthKey() === $authKey;
166
    }
167
168
    /**
169
     * Finds user by username
170
     *
171
     * @param string $username
172
     * @return static|null|ActiveRecord
173
     */
174
    public static function findByUsername($username)
175
    {
176
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
177
    }
178
179
    /**
180
     * Finds user by email
181
     *
182
     * @param string $email
183
     * @return array|null|ActiveRecord
184
     */
185
    public static function findByUsernameEmail($email)
186
    {
187
        return static::findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]);
188
    }
189
190
    /**
191
     * Finds user by username or email
192
     *
193
     * @param string $string
194
     * @return array|null|ActiveRecord
195
     */
196
    public static function findByUsernameOrEmail($string)
197
    {
198
        return static::find()
199
            ->where(['or', ['username' => $string], ['email' => $string]])
200
            ->andWhere(['status' => self::STATUS_ACTIVE])
201
            ->one();
202
    }
203
204
    /**
205
     * Finds user by password reset token
206
     *
207
     * @param mixed $token password reset token
208
     * @return static|null
209
     */
210
    public static function findByPasswordResetToken($token)
211
    {
212
        if (!static::isPasswordResetTokenValid($token)) {
213
            return null;
214
        }
215
        return static::findOne([
216
            'password_reset_token' => $token,
217
            'status' => self::STATUS_ACTIVE,
218
        ]);
219
    }
220
221
    /**
222
     * Finds out if password reset token is valid
223
     *
224
     * @param mixed $token password reset token
225
     * @return boolean
226
     */
227
    public static function isPasswordResetTokenValid($token)
228
    {
229
        if (empty($token)) {
230
            return false;
231
        }
232
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
233
        $parts = explode('_', $token);
234
        $timestamp = (int)end($parts);
235
        return $timestamp + $expire >= time();
236
    }
237
238
    /**
239
     * Validates password
240
     *
241
     * @param string $password password to validate
242
     * @return bool if password provided is valid for current user
243
     */
244
    public function validatePassword($password)
245
    {
246
        return Yii::$app->security->validatePassword($password, $this->password_hash);
247
    }
248
249
    /**
250
     * Generates password hash from password and sets it to the model
251
     *
252
     * @param string $password
253
     * @throws \yii\base\Exception
254
     */
255
    public function setPassword($password)
256
    {
257
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
258
    }
259
260
    /**
261
     * Generates "remember me" authentication key
262
     */
263
    public function generateAuthKey()
264
    {
265
        $this->auth_key = Yii::$app->security->generateRandomString();
266
    }
267
268
    /**
269
     * Generates new password reset token
270
     */
271
    public function generatePasswordResetToken()
272
    {
273
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
274
    }
275
276
    /**
277
     * Removes password reset token
278
     */
279
    public function removePasswordResetToken()
280
    {
281
        $this->password_reset_token = null;
282
    }
283
284
    /**
285
     * @param mixed $email_confirm_token
286
     * @return bool|null|static
287
     */
288
    public static function findByEmailConfirmToken($email_confirm_token)
289
    {
290
        return static::findOne([
291
            'email_confirm_token' => $email_confirm_token,
292
            'status' => self::STATUS_WAIT
293
        ]);
294
    }
295
296
    /**
297
     * Generates email confirmation token
298
     */
299
    public function generateEmailConfirmToken()
300
    {
301
        $this->email_confirm_token = Yii::$app->security->generateRandomString();
302
    }
303
304
    /**
305
     * Removes email confirmation token
306
     */
307
    public function removeEmailConfirmToken()
308
    {
309
        $this->email_confirm_token = null;
310
    }
311
312
    /**
313
     * @return string
314
     */
315
    public function getUserFullName()
316
    {
317
        $fullName = Module::t('module', 'Guest');
318
        if (!Yii::$app->user->isGuest) {
319
            $fullName = $this->first_name . ' ' . $this->last_name;
320
            $fullName = ($fullName != ' ') ? $fullName : $this->username;
321
        }
322
        return Html::encode(trim($fullName));
323
    }
324
}
325