/
User.php
662 lines (568 loc) · 17.2 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
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
<?php namespace October\Rain\Auth\Models;
use Str;
use Hash;
use October\Rain\Database\Model;
use InvalidArgumentException;
use Exception;
/**
* User model
*/
class User extends Model implements \Illuminate\Contracts\Auth\Authenticatable
{
use \October\Rain\Database\Traits\Hashable;
use \October\Rain\Database\Traits\Purgeable;
use \October\Rain\Database\Traits\Validation;
/**
* @var string The table associated with the model.
*/
protected $table = 'users';
/**
* @var array Validation rules
*/
public $rules = [
'email' => 'required|between:3,64|email|unique:users',
'password' => 'required:create|between:2,32|confirmed',
'password_confirmation' => 'required_with:password|between:2,32'
];
/**
* @var array Relations
*/
public $belongsToMany = [
'groups' => [Group::class, 'table' => 'users_groups']
];
public $belongsTo = [
'role' => Role::class
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['activated_at', 'last_login'];
/**
* @var array The attributes that should be hidden for arrays.
*/
protected $hidden = ['password', 'reset_password_code', 'activation_code', 'persist_code'];
/**
* @var array The attributes that aren't mass assignable.
*/
protected $guarded = ['is_superuser', 'reset_password_code', 'activation_code', 'persist_code', 'role_id'];
/**
* @var array List of attribute names which should be hashed using the Bcrypt hashing algorithm.
*/
protected $hashable = ['password', 'persist_code'];
/**
* @var array List of attribute names which should not be saved to the database.
*/
protected $purgeable = ['password_confirmation'];
/**
* @var array The array of custom attribute names.
*/
public $attributeNames = [];
/**
* @var array The array of custom error messages.
*/
public $customMessages = [];
/**
* @var array List of attribute names which are json encoded and decoded from the database.
*/
protected $jsonable = ['permissions'];
/**
* Allowed permissions values.
*
* Possible options:
* -1 => Deny (adds to array, but denies regardless of user's group).
* 0 => Remove.
* 1 => Add.
*
* @var array
*/
protected $allowedPermissionsValues = [-1, 0, 1];
/**
* @var string The login attribute.
*/
public static $loginAttribute = 'email';
/**
* @var string The column name of the "remember me" token.
*/
protected $rememberTokenName = 'persist_code';
/**
* @var array The user merged permissions.
*/
protected $mergedPermissions;
/**
* @return string Returns the name for the user's login.
*/
public function getLoginName()
{
return static::$loginAttribute;
}
/**
* @return mixed Returns the user's login.
*/
public function getLogin()
{
return $this->{$this->getLoginName()};
}
/**
* Checks if the user is a super user - has access to everything regardless of permissions.
* @return bool
*/
public function isSuperUser()
{
return (bool) $this->is_superuser;
}
//
// Events
//
public function beforeLogin()
{
}
public function afterLogin()
{
$this->last_login = $this->freshTimestamp();
$this->forceSave();
}
/**
* Delete the user groups
* @return bool
*/
public function afterDelete()
{
if ($this->hasRelation('groups')) {
$this->groups()->detach();
}
}
//
// Persistence (used by Cookies and Sessions)
//
/**
* Gets a code for when the user is persisted to a cookie or session which identifies the user.
* @return string
*/
public function getPersistCode()
{
$this->persist_code = $this->getRandomString();
// Our code got hashed
$persistCode = $this->persist_code;
$this->forceSave();
return $persistCode;
}
/**
* Checks the given persist code.
* @param string $persistCode
* @return bool
*/
public function checkPersistCode($persistCode)
{
if (!$persistCode || !$this->persist_code) {
return false;
}
return $persistCode == $this->persist_code;
}
//
// Activation
//
/**
* Get mutator for giving the activated property.
* @param mixed $activated
* @return bool
*/
public function getIsActivatedAttribute($activated)
{
return (bool) $activated;
}
/**
* Get an activation code for the given user.
* @return string
*/
public function getActivationCode()
{
$this->activation_code = $activationCode = $this->getRandomString();
$this->forceSave();
return $activationCode;
}
/**
* Attempts to activate the given user by checking the activate code. If the user is activated already, an Exception is thrown.
* @param string $activationCode
* @return bool
*/
public function attemptActivation($activationCode)
{
if ($this->is_activated) {
throw new Exception('User is already active!');
}
if ($activationCode === $this->activation_code) {
$this->activation_code = null;
$this->is_activated = true;
$this->activated_at = $this->freshTimestamp();
$this->forceSave();
return true;
}
return false;
}
//
// Password
//
/**
* Checks the password passed matches the user's password.
* @param string $password
* @return bool
*/
public function checkPassword($password)
{
return Hash::check($password, $this->password);
}
/**
* Get a reset password code for the given user.
* @return string
*/
public function getResetPasswordCode()
{
$this->reset_password_code = $resetCode = $this->getRandomString();
$this->forceSave();
return $resetCode;
}
/**
* Checks if the provided user reset password code is valid without actually resetting the password.
* @param string $resetCode
* @return bool
*/
public function checkResetPasswordCode($resetCode)
{
if (!$resetCode || !$this->reset_password_code) {
return false;
}
return ($this->reset_password_code == $resetCode);
}
/**
* Attempts to reset a user's password by matching the reset code generated with the user's.
* @param string $resetCode
* @param string $newPassword
* @return bool
*/
public function attemptResetPassword($resetCode, $newPassword)
{
if ($this->checkResetPasswordCode($resetCode)) {
$this->password = $newPassword;
$this->reset_password_code = null;
return $this->forceSave();
}
return false;
}
/**
* Wipes out the data associated with resetting a password.
* @return void
*/
public function clearResetPassword()
{
if ($this->reset_password_code) {
$this->reset_password_code = null;
$this->forceSave();
}
}
/**
* Protects the password from being reset to null.
*/
public function setPasswordAttribute($value)
{
if ($this->exists && empty($value)) {
unset($this->attributes['password']);
}
else {
$this->attributes['password'] = $value;
// Password has changed, log out all users
$this->attributes['persist_code'] = null;
}
}
//
// Permissions, Groups & Role
//
/**
* Returns an array of groups which the given user belongs to.
* @return array
*/
public function getGroups()
{
return $this->groups;
}
/**
* Returns the role assigned to this user.
* @return October\Rain\Auth\Models\Role
*/
public function getRole()
{
return $this->role;
}
/**
* Adds the user to the given group.
* @param Group $group
* @return bool
*/
public function addGroup($group)
{
if (!$this->inGroup($group)) {
$this->groups()->attach($group);
$this->reloadRelations('groups');
}
return true;
}
/**
* Removes the user from the given group.
* @param Group $group
* @return bool
*/
public function removeGroup($group)
{
if ($this->inGroup($group)) {
$this->groups()->detach($group);
$this->reloadRelations('groups');
}
return true;
}
/**
* See if the user is in the given group.
* @param Group $group
* @return bool
*/
public function inGroup($group)
{
foreach ($this->getGroups() as $_group) {
if ($_group->getKey() == $group->getKey()) {
return true;
}
}
return false;
}
/**
* Returns an array of merged permissions for each group the user is in.
* @return array
*/
public function getMergedPermissions()
{
if (!$this->mergedPermissions) {
$permissions = [];
if (($role = $this->getRole()) && is_array($role->permissions)) {
$permissions = array_merge($permissions, $role->permissions);
}
if (is_array($this->permissions)) {
$permissions = array_merge($permissions, $this->permissions);
}
$this->mergedPermissions = $permissions;
}
return $this->mergedPermissions;
}
/**
* See if a user has access to the passed permission(s).
* Permissions are merged from all groups the user belongs to
* and then are checked against the passed permission(s).
*
* If multiple permissions are passed, the user must
* have access to all permissions passed through, unless the
* "all" flag is set to false.
*
* Super users have access no matter what.
*
* @param string|array $permissions
* @param bool $all
* @return bool
*/
public function hasAccess($permissions, $all = true)
{
if ($this->isSuperUser()) {
return true;
}
return $this->hasPermission($permissions, $all);
}
/**
* See if a user has access to the passed permission(s).
* Permissions are merged from all groups the user belongs to
* and then are checked against the passed permission(s).
*
* If multiple permissions are passed, the user must
* have access to all permissions passed through, unless the
* "all" flag is set to false.
*
* Super users DON'T have access no matter what.
*
* @param string|array $permissions
* @param bool $all
* @return bool
*/
public function hasPermission($permissions, $all = true)
{
$mergedPermissions = $this->getMergedPermissions();
if (!is_array($permissions)) {
$permissions = [$permissions];
}
foreach ($permissions as $permission) {
// We will set a flag now for whether this permission was
// matched at all.
$matched = true;
// Now, let's check if the permission ends in a wildcard "*" symbol.
// If it does, we'll check through all the merged permissions to see
// if a permission exists which matches the wildcard.
if ((strlen($permission) > 1) && ends_with($permission, '*')) {
$matched = false;
foreach ($mergedPermissions as $mergedPermission => $value) {
// Strip the '*' off the end of the permission.
$checkPermission = substr($permission, 0, -1);
// We will make sure that the merged permission does not
// exactly match our permission, but starts with it.
if ($checkPermission != $mergedPermission && starts_with($mergedPermission, $checkPermission) && $value == 1) {
$matched = true;
break;
}
}
}
elseif ((strlen($permission) > 1) && starts_with($permission, '*')) {
$matched = false;
foreach ($mergedPermissions as $mergedPermission => $value) {
// Strip the '*' off the beginning of the permission.
$checkPermission = substr($permission, 1);
// We will make sure that the merged permission does not
// exactly match our permission, but ends with it.
if ($checkPermission != $mergedPermission && ends_with($mergedPermission, $checkPermission) && $value == 1) {
$matched = true;
break;
}
}
}
else {
$matched = false;
foreach ($mergedPermissions as $mergedPermission => $value) {
// This time check if the mergedPermission ends in wildcard "*" symbol.
if ((strlen($mergedPermission) > 1) && ends_with($mergedPermission, '*')) {
$matched = false;
// Strip the '*' off the end of the permission.
$checkMergedPermission = substr($mergedPermission, 0, -1);
// We will make sure that the merged permission does not
// exactly match our permission, but starts with it.
if ($checkMergedPermission != $permission && starts_with($permission, $checkMergedPermission) && $value == 1) {
$matched = true;
break;
}
}
// Otherwise, we'll fallback to standard permissions checking where
// we match that permissions explicitly exist.
elseif ($permission == $mergedPermission && $mergedPermissions[$permission] == 1) {
$matched = true;
break;
}
}
}
// Now, we will check if we have to match all
// permissions or any permission and return
// accordingly.
if ($all === true && $matched === false) {
return false;
}
elseif ($all === false && $matched === true) {
return true;
}
}
return !($all === false);
}
/**
* Returns if the user has access to any of the given permissions.
* @param array $permissions
* @return bool
*/
public function hasAnyAccess(array $permissions)
{
return $this->hasAccess($permissions, false);
}
/**
* Validate any set permissions.
* @param array $permissions
* @return void
*/
public function setPermissionsAttribute($permissions)
{
$permissions = json_decode($permissions, true) ?: [];
foreach ($permissions as $permission => &$value) {
if (!in_array($value = (int) $value, $this->allowedPermissionsValues)) {
throw new InvalidArgumentException(sprintf(
'Invalid value "%s" for permission "%s" given.',
$value,
$permission
));
}
if ($value === 0) {
unset($permissions[$permission]);
}
}
$this->attributes['permissions'] = !empty($permissions) ? json_encode($permissions) : '';
}
//
// User Interface
//
/**
* Get the name of the unique identifier for the user.
* @return string
*/
public function getAuthIdentifierName()
{
return $this->getKeyName();
}
/**
* Get the unique identifier for the user.
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->{$this->getAuthIdentifierName()};
}
/**
* Get the password for the user.
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
/**
* Get the token value for the "remember me" session.
* @return string
*/
public function getRememberToken()
{
return $this->getPersistCode();
}
/**
* Set the token value for the "remember me" session.
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->persist_code = $value;
}
/**
* Get the column name for the "remember me" token.
* @return string
*/
public function getRememberTokenName()
{
return $this->rememberTokenName;
}
//
// Helpers
//
/**
* Generate a random string
* @return string
*/
public function getRandomString($length = 42)
{
return Str::random($length);
}
}