Passed
Push — master ( 4b0bfb...40d7bb )
by Alexey
02:39
created

IdentityUser::findByEmailConfirmToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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