-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathManager.php
More file actions
785 lines (667 loc) · 20.4 KB
/
Manager.php
File metadata and controls
785 lines (667 loc) · 20.4 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
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
<?php namespace October\Rain\Auth;
use Cookie;
use Session;
use Request;
use Illuminate\Contracts\Auth\Authenticatable;
/**
* Authentication manager
*/
class Manager implements \Illuminate\Contracts\Auth\StatefulGuard
{
use \October\Rain\Support\Traits\Singleton;
/**
* @var Models\User The currently logged in user
*/
protected $user;
/**
* @var array In memory throttle cache [md5($userId.$ipAddress) => $this->throttleModel]
*/
protected $throttle = [];
/**
* @var string User Model Class
*/
protected $userModel = Models\User::class;
/**
* @var string User Group Model Class
*/
protected $groupModel = Models\Group::class;
/**
* @var string Throttle Model Class
*/
protected $throttleModel = Models\Throttle::class;
/**
* @var bool Flag to enable login throttling
*/
protected $useThrottle = true;
/**
* @var bool Internal flag to toggle using the session for the current authentication request
*/
protected $useSession = true;
/**
* @var bool Flag to require users to be activated to login
*/
protected $requireActivation = true;
/**
* @var string Key to store the auth session data in
*/
protected $sessionKey = 'october_auth';
/**
* @var bool Indicates if the user was authenticated via a recaller cookie.
*/
protected $viaRemember = false;
/**
* @var string The IP address of this request
*/
public $ipAddress = '0.0.0.0';
/**
* Initializes the singleton
*/
protected function init()
{
$this->ipAddress = Request::ip();
}
//
// User
//
/**
* Creates a new instance of the user model
*
* @return Models\User
*/
public function createUserModel()
{
$class = '\\'.ltrim($this->userModel, '\\');
return new $class();
}
/**
* Prepares a query derived from the user model.
*
* @return \October\Rain\Database\Builder $query
*/
protected function createUserModelQuery()
{
$model = $this->createUserModel();
$query = $model->newQuery();
$this->extendUserQuery($query);
return $query;
}
/**
* Extend the query used for finding the user.
* @param \October\Rain\Database\Builder $query
* @return void
*/
public function extendUserQuery($query)
{
}
/**
* Registers a user with the provided credentials with optional flags
* for activating the newly created user and automatically logging them in
*
* @param array $credentials
* @param bool $activate
* @param bool $autoLogin
* @return Models\User
*/
public function register(array $credentials, $activate = false, $autoLogin = true)
{
$user = $this->createUserModel();
$user->fill($credentials);
$user->save();
if ($activate) {
$user->attemptActivation($user->getActivationCode());
}
// Prevents revalidation of the password field
// on subsequent saves to this model object
$user->password = null;
if ($autoLogin) {
$this->user = $user;
}
return $user;
}
/**
* Sets the user
*/
public function setUser(Authenticatable $user)
{
$this->user = $user;
}
/**
* Returns the current user, if any.
*
* @return mixed (Models\User || null)
*/
public function getUser()
{
if (is_null($this->user)) {
$this->check();
}
return $this->user;
}
/**
* Finds a user by the login value.
*
* @param string $id
* @return mixed (Models\User || null)
*/
public function findUserById($id)
{
$query = $this->createUserModelQuery();
$user = $query->find($id);
return $this->validateUserModel($user) ? $user : null;
}
/**
* Finds a user by the login value.
*
* @param string $login
* @return mixed (Models\User || null)
*/
public function findUserByLogin($login)
{
$model = $this->createUserModel();
$query = $this->createUserModelQuery();
$user = $query->where($model->getLoginName(), $login)->first();
return $this->validateUserModel($user) ? $user : null;
}
/**
* Finds a user by the given credentials.
*
* @param array $credentials The credentials to find a user by
* @throws AuthException If the credentials are invalid
* @return Models\User The requested user
*/
public function findUserByCredentials(array $credentials)
{
$model = $this->createUserModel();
$loginName = $model->getLoginName();
if (!array_key_exists($loginName, $credentials)) {
throw new AuthException(sprintf('Login attribute "%s" was not provided.', $loginName));
}
$query = $this->createUserModelQuery();
$hashableAttributes = $model->getHashableAttributes();
$hashedCredentials = [];
/*
* Build query from given credentials
*/
foreach ($credentials as $credential => $value) {
// All excepted the hashed attributes
if (in_array($credential, $hashableAttributes)) {
$hashedCredentials = array_merge($hashedCredentials, [$credential => $value]);
}
else {
$query = $query->where($credential, '=', $value);
}
}
$user = $query->first();
if (!$this->validateUserModel($user)) {
throw new AuthException('A user was not found with the given credentials.');
}
/*
* Check the hashed credentials match
*/
foreach ($hashedCredentials as $credential => $value) {
if (!$user->checkHashValue($credential, $value)) {
// Incorrect password
if ($credential == 'password') {
throw new AuthException(sprintf(
'A user was found to match all plain text credentials however hashed credential "%s" did not match.',
$credential
));
}
// User not found
throw new AuthException('A user was not found with the given credentials.');
}
}
return $user;
}
/**
* Perform additional checks on the user model.
*
* @param $user
* @return boolean
*/
protected function validateUserModel($user)
{
return $user instanceof $this->userModel;
}
//
// Throttle
//
/**
* Creates an instance of the throttle model
*
* @return Models\Throttle
*/
public function createThrottleModel()
{
$class = '\\'.ltrim($this->throttleModel, '\\');
return new $class();
}
/**
* Find a throttle record by login and ip address
*
* @param string $loginName
* @param string $ipAddress
* @return Models\Throttle
*/
public function findThrottleByLogin($loginName, $ipAddress)
{
$user = $this->findUserByLogin($loginName);
if (!$user) {
throw new AuthException("A user was not found with the given credentials.");
}
$userId = $user->getKey();
return $this->findThrottleByUserId($userId, $ipAddress);
}
/**
* Find a throttle record by user id and ip address
*
* @param integer $userId
* @param string $ipAddress
* @return Models\Throttle
*/
public function findThrottleByUserId($userId, $ipAddress = null)
{
$cacheKey = md5($userId.$ipAddress);
if (isset($this->throttle[$cacheKey])) {
return $this->throttle[$cacheKey];
}
$model = $this->createThrottleModel();
$query = $model->where('user_id', '=', $userId);
if ($ipAddress) {
$query->where(function ($query) use ($ipAddress) {
$query->where('ip_address', '=', $ipAddress);
$query->orWhere('ip_address', '=', null);
});
}
if (!$throttle = $query->first()) {
$throttle = $this->createThrottleModel();
$throttle->user_id = $userId;
if ($ipAddress) {
$throttle->ip_address = $ipAddress;
}
$throttle->save();
}
return $this->throttle[$cacheKey] = $throttle;
}
//
// Business Logic
//
/**
* Attempt to authenticate a user using the given credentials.
*
* @param array $credentials The user login details
* @param bool $remember Store a non-expire cookie for the user
* @throws AuthException If authentication fails
* @return Models\User The successfully logged in user
*/
public function attempt(array $credentials = [], $remember = false)
{
return !!$this->authenticate($credentials, $remember);
}
/**
* Validate a user's credentials.
*
* @param array $credentials
* @return bool
*/
public function validate(array $credentials = [])
{
return !!$this->validateInternal($credentials);
}
/**
* Validate a user's credentials, method used internally.
*
* @param array $credentials
* @return User
*/
protected function validateInternal(array $credentials = [])
{
/*
* Default to the login name field or fallback to a hard-coded 'login' value
*/
$loginName = $this->createUserModel()->getLoginName();
$loginCredentialKey = isset($credentials[$loginName]) ? $loginName : 'login';
if (empty($credentials[$loginCredentialKey])) {
throw new AuthException(sprintf('The "%s" attribute is required.', $loginCredentialKey));
}
if (empty($credentials['password'])) {
throw new AuthException('The password attribute is required.');
}
/*
* If the fallback 'login' was provided and did not match the necessary
* login name, swap it over
*/
if ($loginCredentialKey !== $loginName) {
$credentials[$loginName] = $credentials[$loginCredentialKey];
unset($credentials[$loginCredentialKey]);
}
/*
* If throttling is enabled, check they are not locked out first and foremost.
*/
if ($this->useThrottle) {
$throttle = $this->findThrottleByLogin($credentials[$loginName], $this->ipAddress);
$throttle->check();
}
/*
* Look up the user by authentication credentials.
*/
try {
$user = $this->findUserByCredentials($credentials);
}
catch (AuthException $ex) {
if ($this->useThrottle) {
$throttle->addLoginAttempt();
}
throw $ex;
}
if ($this->useThrottle) {
$throttle->clearLoginAttempts();
}
return $user;
}
/**
* Attempts to authenticate the given user according to the passed credentials.
*
* @param array $credentials The user login details
* @param bool $remember Store a non-expire cookie for the user
*/
public function authenticate(array $credentials, $remember = true)
{
$user = $this->validateInternal($credentials);
$user->clearResetPassword();
$this->login($user, $remember);
return $this->user;
}
/**
* Check to see if the user is logged in and activated, and hasn't been banned or suspended.
*
* @return bool
*/
public function check()
{
if (is_null($this->user)) {
/*
* Check session first, follow by cookie
*/
if ($sessionArray = Session::get($this->sessionKey)) {
$userArray = $sessionArray;
}
elseif ($cookieArray = Cookie::get($this->sessionKey)) {
$this->viaRemember = true;
/*
* Shift gracefully to unserialized cookies
* @todo Remove if statement below if year >= 2021 or build >= 475
*/
if (is_array($cookieArray)) {
$userArray = $cookieArray;
}
else {
$userArray = @json_decode($cookieArray, true);
}
}
else {
return false;
}
/*
* Check supplied session/cookie is an array (user id, persist code)
*/
if (!is_array($userArray) || count($userArray) !== 2) {
return false;
}
list($id, $persistCode) = $userArray;
/*
* Look up user
*/
if (!$user = $this->findUserById($id)) {
return false;
}
/*
* Confirm the persistence code is valid, otherwise reject
*/
if (!$user->checkPersistCode($persistCode)) {
return false;
}
/*
* Pass
*/
$this->user = $user;
}
/*
* Check cached user is activated
*/
if (!($user = $this->getUser()) || ($this->requireActivation && !$user->is_activated)) {
return false;
}
/*
* Throttle check
*/
if ($this->useThrottle) {
$throttle = $this->findThrottleByUserId($user->getKey(), $this->ipAddress);
if ($throttle->is_banned || $throttle->checkSuspended()) {
$this->logout();
return false;
}
}
return true;
}
/**
* Determine if the current user is a guest.
*
* @return bool
*/
public function guest()
{
return false;
}
/**
* Get the currently authenticated user.
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
return $this->getUser();
}
/**
* Get the ID for the currently authenticated user.
*
* @return int|null
*/
public function id()
{
if ($user = $this->getUser()) {
return $user->getAuthIdentifier();
}
return null;
}
/**
* Log a user into the application without sessions or cookies.
*
* @param array $credentials
* @return bool
*/
public function once(array $credentials = [])
{
$this->useSession = false;
$user = $this->authenticate($credentials);
$this->useSession = true;
return !!$user;
}
/**
* Log the given user ID into the application without sessions or cookies.
*
* @param mixed $id
* @return \Illuminate\Contracts\Auth\Authenticatable|false
*/
public function onceUsingId($id)
{
if (!is_null($user = $this->findUserById($id))) {
$this->setUser($user);
return $user;
}
return false;
}
/**
* Logs in the given user and sets properties
* in the session.
* @throws AuthException If the user is not activated and $this->requireActivation = true
*/
public function login(Authenticatable $user, $remember = true)
{
/*
* Fire the 'beforeLogin' event
*/
$user->beforeLogin();
/*
* Activation is required, user not activated
*/
if ($this->requireActivation && !$user->is_activated) {
$login = $user->getLogin();
throw new AuthException(sprintf(
'Cannot login user "%s" as they are not activated.',
$login
));
}
$this->user = $user;
/*
* Create session/cookie data to persist the session
*/
if ($this->useSession) {
$toPersist = [$user->getKey(), $user->getPersistCode()];
Session::put($this->sessionKey, $toPersist);
if ($remember) {
Cookie::queue(Cookie::forever($this->sessionKey, json_encode($toPersist)));
}
}
/*
* Fire the 'afterLogin' event
*/
$user->afterLogin();
}
/**
* Log the given user ID into the application.
*
* @param mixed $id
* @param bool $remember
* @return \Illuminate\Contracts\Auth\Authenticatable
*/
public function loginUsingId($id, $remember = false)
{
if (!is_null($user = $this->findUserById($id))) {
$this->login($user, $remember);
return $user;
}
return false;
}
/**
* Determine if the user was authenticated via "remember me" cookie.
*
* @return bool
*/
public function viaRemember()
{
return $this->viaRemember;
}
/**
* Logs the current user out.
*/
public function logout()
{
// Initialize the current auth session before trying to remove it
if (is_null($this->user) && !$this->check()) {
return;
}
if ($this->isImpersonator()) {
$this->user = $this->getImpersonator();
$this->stopImpersonate();
return;
}
if ($this->user) {
$this->user->setRememberToken(null);
$this->user->forceSave();
}
$this->user = null;
Session::flush();
Cookie::queue(Cookie::forget($this->sessionKey));
}
//
// Impersonation
//
/**
* Impersonates the given user and sets properties
* in the session but not the cookie.
*/
public function impersonate($user)
{
$oldSession = Session::get($this->sessionKey);
$oldUser = !empty($oldSession[0]) ? $this->findUserById($oldSession[0]) : false;
/**
* @event model.auth.beforeImpersonate
* Called after the model is booted
*
* Example usage:
*
* $model->bindEvent('model.auth.beforeImpersonate', function (\October\Rain\Database\Model|false $oldUser) use (\October\Rain\Database\Model $model) {
* \Log::info($oldUser->full_name . ' is now impersonating ' . $model->full_name);
* });
*
*/
$user->fireEvent('model.auth.beforeImpersonate', [$oldUser]);
$this->login($user, false);
if (!$this->isImpersonator()) {
Session::put($this->sessionKey.'_impersonate', $oldSession);
}
}
/**
* Stop the current session being impersonated and
* authenticate as the impersonator again
*/
public function stopImpersonate()
{
$currentSession = Session::get($this->sessionKey);
$currentUser = !empty($currentSession[0]) ? $this->findUserById($currentSession[0]) : false;
$oldSession = Session::pull($this->sessionKey.'_impersonate');
$oldUser = !empty($oldSession[0]) ? $this->findUserById($oldSession[0]) : false;
if ($currentUser) {
/**
* @event model.auth.afterImpersonate
* Called after the model is booted
*
* Example usage:
*
* $model->bindEvent('model.auth.afterImpersonate', function (\October\Rain\Database\Model|false $oldUser) use (\October\Rain\Database\Model $model) {
* \Log::info($oldUser->full_name . ' has stopped impersonating ' . $model->full_name);
* });
*
*/
$currentUser->fireEvent('model.auth.afterImpersonate', [$oldUser]);
}
Session::put($this->sessionKey, $oldSession);
}
/**
* Check to see if the current session is being impersonated
*
* @return bool
*/
public function isImpersonator()
{
return !empty(Session::has($this->sessionKey.'_impersonate'));
}
/**
* Get the original user doing the impersonation
*
* @return mixed Returns the User model for the impersonator if able, false if not
*/
public function getImpersonator()
{
$impersonateArray = Session::get($this->sessionKey.'_impersonate');
/*
* Check supplied session/cookie is an array (user id, persist code)
*/
if (!is_array($impersonateArray) || count($impersonateArray) !== 2) {
return false;
}
$id = $impersonateArray[0];
return $this->createUserModel()->find($id);
}
}