-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathUser.php
More file actions
449 lines (403 loc) · 13.3 KB
/
Copy pathUser.php
File metadata and controls
449 lines (403 loc) · 13.3 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
<?php
/*
* This file is part of the 2amigos/yii2-usuario project.
*
* (c) 2amigOS! <http://2amigos.us/>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Da\User\Model;
use Da\User\Dictionary\UserSourceType;
use Da\User\Helper\SecurityHelper;
use Da\User\Query\UserQuery;
use Da\User\Service\InitLdapUserService;
use Da\User\Traits\ContainerAwareTrait;
use Da\User\Traits\ModuleAwareTrait;
use lhs\Yii2SaveRelationsBehavior\SaveRelationsBehavior;
use yetopen\usuarioLdap\UsuarioLdapComponent;
use Yii;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\web\Application;
use yii\web\IdentityInterface;
/**
* User ActiveRecord model.
*
* @property bool $isAdmin
* @property bool $isBlocked
* @property bool $isConfirmed whether user account has been confirmed or not
* @property bool $gdpr_deleted whether user requested deletion of his account
* @property bool $gdpr_consent whether user has consent personal data processing
*
* Database fields:
* @property int $id
* @property string $username
* @property string $email
* @property string $unconfirmed_email
* @property string $password_hash
* @property string $auth_key
* @property string $auth_tf_key
* @property int $auth_tf_enabled
* @property string $auth_tf_type
* @property string $auth_tf_mobile_phone
* @property string $registration_ip
* @property int $confirmed_at
* @property int $blocked_at
* @property int $flags
* @property int $created_at
* @property int $updated_at
* @property int $last_login_at
* @property int $gdpr_consent_date date of agreement of data processing
* @property string $last_login_ip
* @property int $password_changed_at
* @property int $password_age
* @property int $ldap_uid
* Defined relations:
* @property SocialNetworkAccount[] $socialNetworkAccounts
* @property Profile $profile
*/
class User extends ActiveRecord implements IdentityInterface
{
use ModuleAwareTrait;
use ContainerAwareTrait;
// following constants are used on secured email changing process
public const OLD_EMAIL_CONFIRMED = 0b01;
public const NEW_EMAIL_CONFIRMED = 0b10;
// ldap error
public const LDAP_INVALID_USER = -1;
/**
* @var string Plain password. Used for model validation
*/
public $password;
/**
* @var string Stores LDAP uid of the user during creation.
*/
public $ldapUid;
/**
* @var array connected account list
*/
protected $connectedAccounts;
/**
* @var \Adldap\Models\User|null
*/
protected $ldapUser;
/**
* {@inheritdoc}
*
* @throws InvalidParamException
* @throws InvalidConfigException
* @throws Exception
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* {@inheritdoc}
*/
public function fields()
{
$fields = parent::fields();
unset($fields['auth_key'], $fields['password_hash']);
return $fields;
}
/**
* {@inheritdoc}
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
/**
* @return UserQuery
*/
public static function find()
{
return new UserQuery(static::class);
}
/**
* {@inheritdoc}
*
* @throws NotSupportedException
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('Method "' . __CLASS__ . '::' . __METHOD__ . '" is not implemented.');
}
/**
* {@inheritdoc}
*/
public function beforeValidate()
{
if ($this->module->searchUsersInLdap && $this->source == UserSourceType::LDAP && $this->isNewRecord) {
if ($this->ldapUid == self::LDAP_INVALID_USER) {
$this->addError('ldapUid', Yii::t('usuario', 'Invalid LDAP user'));
return false;
}
/** @var UsuarioLdapComponent $ldapComponent */
$ldapComponent = Yii::$app->usuarioLdap;
$this->ldapUser = $ldapComponent->findLdapUser($this->ldapUid);
if ($this->ldapUser !== null) {
$this->make(InitLdapUserService::class, [$this, $this->module->LDAPUserAttributes, $this->ldapUser])->run();
}
}
return parent::beforeValidate();
}
/**
* {@inheritdoc}
*/
public function beforeSave($insert)
{
/** @var SecurityHelper $security */
$security = $this->make(SecurityHelper::class);
if ($insert) {
$this->setAttribute('auth_key', $security->generateRandomString());
if (Yii::$app instanceof Application) {
$this->setAttribute('registration_ip', $this->module->disableIpLogging ? '127.0.0.1' : Yii::$app->request->getUserIP());
}
}
if (!empty($this->password)) {
$this->setAttribute(
'password_hash',
$security->generatePasswordHash($this->password, $this->getModule()->blowfishCost)
);
$this->password_changed_at = time();
}
return parent::beforeSave($insert);
}
/**
* @inheritdoc
*
* @throws InvalidConfigException
*/
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
if ($insert && $this->profile === null) {
$profile = $this->make(Profile::class);
if ($this->ldapUser !== null) {
$this->make(InitLdapUserService::class, [$profile, $this->module->LDAPProfileAttributes, $this->ldapUser])->run();
}
$profile->link('user', $this);
}
}
/**
* {@inheritdoc}
*/
public function behaviors()
{
$behaviors = [
TimestampBehavior::class,
];
if ($this->module->enableGdprCompliance) {
$behaviors['GDPR'] = [
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'gdpr_consent_date',
'updatedAtAttribute' => false
];
}
$behaviors['saveRelations'] = [
'class' => SaveRelationsBehavior::class,
'relations' => [
'profile' => ['cascadeDelete' => true]
]
];
return $behaviors;
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'username' => Yii::t('usuario', 'Username'),
'email' => Yii::t('usuario', 'Email'),
'registration_ip' => Yii::t('usuario', 'Registration IP'),
'unconfirmed_email' => Yii::t('usuario', 'New email'),
'password' => Yii::t('usuario', 'Password'),
'created_at' => Yii::t('usuario', 'Registration time'),
'confirmed_at' => Yii::t('usuario', 'Confirmation time'),
'last_login_at' => Yii::t('usuario', 'Last login time'),
'last_login_ip' => Yii::t('usuario', 'Last login IP'),
'password_changed_at' => Yii::t('usuario', 'Last password change'),
'password_age' => Yii::t('usuario', 'Password age'),
'ldapUid' => Yii::t('usuario', 'Search'),
];
}
/**
* {@inheritdoc}
*/
public function scenarios()
{
return ArrayHelper::merge(
parent::scenarios(),
[
'register' => ['username', 'email', 'password'],
'connect' => ['username', 'email'],
'create' => ['username', 'email', 'password'],
'update' => ['username', 'email', 'password'],
'settings' => ['username', 'email', 'password'],
]
);
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
// username rules
'usernameRequired' => ['username', 'required', 'on' => ['register', 'create', 'connect', 'update']],
'usernameMatch' => ['username', 'match', 'pattern' => '/^[-a-zA-Z0-9_\.@\+]+$/'],
'usernameLength' => ['username', 'string', 'min' => 3, 'max' => 255],
'usernameTrim' => ['username', 'trim'],
'usernameUnique' => [
'username',
'unique',
'message' => Yii::t('usuario', 'This username has already been taken'),
],
// email rules
'emailRequired' => ['email', 'required', 'on' => ['register', 'connect', 'create', 'update']],
'emailPattern' => ['email', 'email'],
'emailLength' => ['email', 'string', 'max' => 255],
'emailUnique' => [
'email',
'unique',
'message' => Yii::t('usuario', 'This email address has already been taken'),
],
'emailTrim' => ['email', 'trim', 'skipOnEmpty' => true],
// password rules
'passwordTrim' => ['password', 'trim'],
'passwordRequired' => ['password', 'required', 'on' => ['register']],
'passwordLength' => ['password', 'string', 'min' => 6, 'max' => 72, 'on' => ['register', 'create']],
// two factor auth rules
'twoFactorSecretTrim' => ['auth_tf_key', 'trim'],
'twoFactorSecretLength' => ['auth_tf_key', 'string', 'max' => 16],
'twoFactorEnabledNumber' => ['auth_tf_enabled', 'boolean'],
'twoFactorTypeLength' => ['auth_tf_type', 'string', 'max' => 20],
'twoFactorMobilePhoneLength' => ['auth_tf_mobile_phone', 'string', 'max' => 20],
// ldapUid rules
'ldapUid' => ['ldapUid', 'string'],
'ldapUidRequired' => ['ldapUid', 'required', 'on' => $this->module->searchUsersInLdap],
];
}
/**
* {@inheritdoc}
*/
public function validateAuthKey($authKey)
{
return $this->getAttribute('auth_key') === $authKey;
}
/**
* {@inheritdoc}
*/
public function getId()
{
return $this->getAttribute('id');
}
/**
* {@inheritdoc}
*/
public function getAuthKey()
{
return $this->getAttribute('auth_key');
}
/**
* @return bool whether is blocked or not
*/
public function getIsBlocked()
{
return $this->blocked_at !== null;
}
/**
* @throws InvalidConfigException
* @return bool whether the user is an admin or not
*/
public function getIsAdmin()
{
return $this->getAuth()->isAdmin($this->username);
}
/**
* Returns whether user account has been confirmed or not.
* @return bool whether user account has been confirmed or not
*/
public function getIsConfirmed()
{
return $this->confirmed_at !== null;
}
/**
* Checks whether a user has a specific role.
*
* @param string $role
*
* @return bool
*/
public function hasRole($role)
{
return $this->getAuth()->hasRole($this->id, $role);
}
/**
* @throws InvalidConfigException
* @throws InvalidParamException
* @return \yii\db\ActiveQuery
*/
public function getProfile()
{
return $this->hasOne($this->getClassMap()->get(Profile::class), ['user_id' => 'id']);
}
/**
* @throws \Exception
* @return SocialNetworkAccount[] social connected accounts [ 'providerName' => socialAccountModel ]
*
*/
public function getSocialNetworkAccounts()
{
if (null === $this->connectedAccounts) {
/** @var SocialNetworkAccount[] $accounts */
$accounts = $this->hasMany(
$this->getClassMap()
->get(SocialNetworkAccount::class),
['user_id' => 'id']
)
->all();
foreach ($accounts as $account) {
$this->connectedAccounts[$account->provider] = $account;
}
}
return $this->connectedAccounts;
}
/**
* Returns password age in days
* @return integer
*/
public function getPassword_age()
{
if (is_null($this->password_changed_at)) {
return $this->getModule()->maxPasswordAge;
}
$d = new \DateTime("@{$this->password_changed_at}");
return $d->diff(new \DateTime(), true)->format("%a");
}
/**
* Returns authentication two factor type enabled for the user
* @return integer
*/
public function getAuthTfType()
{
return $this->getAttribute('auth_tf_type');
}
/**
* Returns the mobile phone number used for sms authentication two factor for the user
* @return string
*/
public function getAuthTfMobilePhone()
{
return $this->getAttribute('auth_tf_mobile_phone');
}
}