forked from robregonm/yii2-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUser.php
294 lines (264 loc) · 6.98 KB
/
User.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<?php
namespace auth\models;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\helpers\Security;
use yii\web\IdentityInterface;
/**
* This is the model class for table "User".
*
* @property integer $id
* @property string $username
* @property string $email
* @property string $password_hash
* @property string $password_reset_token
* @property string $auth_key
* @property integer $status
* @property string $last_visit_time
* @property string $create_time
* @property string $update_time
* @property string $delete_time
*
* @property ProfileFieldValue $profileFieldValue
*/
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_INACTIVE = 1;
const STATUS_ACTIVE = 2;
const STATUS_SUSPENDED = 3;
/**
* @var string the raw password. Used to collect password input and isn't saved in database
*/
public $password;
private $_isSuperAdmin = null;
private $statuses = [
self::STATUS_DELETED => 'Deleted',
self::STATUS_INACTIVE => 'Inactive',
self::STATUS_ACTIVE => 'Active',
self::STATUS_SUSPENDED => 'Suspended',
];
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
self::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
self::EVENT_BEFORE_DELETE => 'delete_time',
],
'value' => function () {
return new Expression('CURRENT_TIMESTAMP');
}
],
];
}
public function getStatus($status = null)
{
if ($status === null) {
return $this->statuses[$this->status];
}
return $this->statuses[$status];
}
/**
* Finds an identity by the given ID.
*
* @param string|integer $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
*/
public static function findIdentity($id)
{
return static::find($id);
}
/**
* Finds user by username
*
* @param string $username
* @return null|User
*/
public static function findByUsername($username)
{
return static::find(['username' => $username, 'status' => static::STATUS_ACTIVE]);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int)end($parts);
if ($timestamp + $expire < time()) {
// token expired
return null;
}
return static::find([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* @return int|string current user ID
*/
public function getId()
{
return $this->id;
}
/**
* @return string current user auth key
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @param string $authKey
* @return boolean if auth key is valid for current user
*/
public function validateAuthKey($authKey)
{
return $this->auth_key === $authKey;
}
/**
* @param string $password password to validate
* @return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Security::validatePassword($password, $this->password_hash);
}
/**
* @inheritdoc
*/
public static function tableName()
{
return Yii::$app->getModule('auth')->tableMap['User'];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => static::STATUS_ACTIVE, 'on' => 'signup'],
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['email', 'unique', 'message' => Yii::t('auth.user', 'This username has already been taken.')],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique', 'message' => Yii::t('auth.user', 'This email address has already been taken.')],
['email', 'exist', 'message' => Yii::t('auth.user', 'There is no user with such email.'), 'on' => 'requestPasswordResetToken'],
['password', 'required', 'on' => 'signup'],
['password', 'string', 'min' => 6],
];
}
public function scenarios()
{
return [
'signup' => ['username', 'email', 'password'],
'profile' => ['username', 'email', 'password'],
'resetPassword' => ['password'],
'requestPasswordResetToken' => ['email'],
'login' => ['last_visit_time'],
] + parent::scenarios();
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => Yii::t('auth.user', 'Username'),
'email' => Yii::t('auth.user', 'Email'),
'password' => Yii::t('auth.user', 'Password'),
'password_hash' => Yii::t('auth.user', 'Password Hash'),
'password_reset_token' => Yii::t('auth.user', 'Password Reset Token'),
'auth_key' => Yii::t('auth.user', 'Auth Key'),
'status' => Yii::t('auth.user', 'Status'),
'last_visit_time' => Yii::t('auth.user', 'Last Visit Time'),
'create_time' => Yii::t('auth.user', 'Create Time'),
'update_time' => Yii::t('auth.user', 'Update Time'),
'delete_time' => Yii::t('auth.user', 'Delete Time'),
];
}
/**
* @return \yii\db\ActiveRelation
*/
public function getProfileFieldValue()
{
return $this->hasOne(ProfileFieldValue::className(), ['id' => 'user_id']);
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if (($this->isNewRecord || $this->getScenario() === 'resetPassword') && !empty($this->password)) {
$this->password_hash = Security::generatePasswordHash($this->password);
}
if ($this->isNewRecord) {
$this->auth_key = Security::generateRandomKey();
}
if ($this->getScenario() !== \yii\web\User::EVENT_AFTER_LOGIN) {
$this->setAttribute('update_time', new Expression('CURRENT_TIMESTAMP'));
}
return true;
}
return false;
}
public function delete()
{
$db = static::getDb();
$transaction = $this->isTransactional(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
try {
$result = false;
if ($this->beforeDelete()) {
$this->save(false);
}
if ($transaction !== null) {
if ($result === false) {
$transaction->rollback();
} else {
$transaction->commit();
}
}
} catch (\Exception $e) {
if ($transaction !== null) {
$transaction->rollback();
}
throw $e;
}
return $result;
}
/**
* Returns whether the logged in user is an administrator.
*
* @return boolean the result.
*/
public function getIsSuperAdmin()
{
if ($this->_isSuperAdmin !== null) {
return $this->_isSuperAdmin;
}
$this->_isSuperAdmin = in_array($this->username, Yii::$app->getModule('auth')->superAdmins);
return $this->_isSuperAdmin;
}
public function login($duration = 0)
{
return Yii::$app->user->login($this, $duration);
}
}