Completed
Push — master ( 83f80c...dcb858 )
by Alexey
03:54
created

User::getRole()   A

Complexity

Conditions 2
Paths 2

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