-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuth.php
More file actions
1981 lines (1770 loc) · 80.9 KB
/
Copy pathAuth.php
File metadata and controls
1981 lines (1770 loc) · 80.9 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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Horizom\Auth;
use Delight\Base64\Base64;
use Delight\Cookie\Cookie;
use Delight\Cookie\Session;
use Delight\Db\PdoDatabase;
use Delight\Db\PdoDsn;
use Delight\Db\Throwable\Error;
use Delight\Db\Throwable\IntegrityConstraintViolationException;
use Horizom\Auth\Error\AuthError;
use Horizom\Auth\Error\DatabaseError;
use Horizom\Auth\Error\MissingCallbackError;
use Horizom\Auth\Error\HeadersAlreadySentError;
use Horizom\Auth\Error\EmailOrUsernameRequiredError;
use Horizom\Auth\Exception\TokenExpiredException;
use Horizom\Auth\Exception\AuthException;
use Horizom\Auth\Exception\AttemptCancelledException;
use Horizom\Auth\Exception\NotLoggedInException;
use Horizom\Auth\Exception\ConfirmationRequestNotFound;
use Horizom\Auth\Exception\ResetDisabledException;
use Horizom\Auth\Exception\TooManyRequestsException;
use Horizom\Auth\Exception\EmailNotVerifiedException;
use Horizom\Auth\Exception\AmbiguousUsernameException;
use Horizom\Auth\Exception\InvalidPasswordException;
use Horizom\Auth\Exception\UnknownUsernameException;
use Horizom\Auth\Exception\InvalidEmailException;
use Horizom\Auth\Exception\UserAlreadyExistsException;
use Horizom\Auth\Exception\DuplicateUsernameException;
use Horizom\Auth\Exception\InvalidSelectorTokenPairException;
/**
* Component that provides all features and utilities for secure authentication of individual users
*/
class Auth extends AuthManager
{
const COOKIE_PREFIXES = [Cookie::PREFIX_SECURE, Cookie::PREFIX_HOST];
const COOKIE_CONTENT_SEPARATOR = '~';
/** @var string the user's current IP address */
private $ipAddress;
/** @var bool whether throttling should be enabled (e.g. in production) or disabled (e.g. during development) */
private $throttling;
/** @var int the interval in seconds after which to resynchronize the session data with its authoritative source in the database */
private $sessionResyncInterval;
/** @var string the name of the cookie used for the 'remember me' feature */
private $rememberCookieName;
/**
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection to operate on
* @param string|null $ipAddress (optional) the IP address that should be used instead of the default setting (if any), e.g. when behind a proxy
* @param string|null $dbTablePrefix (optional) the prefix for the names of all database tables used by this component
* @param bool|null $throttling (optional) whether throttling should be enabled (e.g. in production) or disabled (e.g. during development)
* @param int|null $sessionResyncInterval (optional) the interval in seconds after which to resynchronize the session data with its authoritative source in the database
* @param string|null $dbSchema (optional) the schema name for all database tables used by this component
*/
public function __construct($databaseConnection, array $tables = null, $ipAddress = null, $dbTablePrefix = null, $throttling = null, $sessionResyncInterval = null, $dbSchema = null)
{
parent::__construct($databaseConnection, $tables, $dbTablePrefix, $dbSchema);
if ($tables !== null) {
self::$tables = $tables;
}
$this->ipAddress = !empty($ipAddress) ? $ipAddress : (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null);
$this->throttling = isset($throttling) ? (bool) $throttling : true;
$this->sessionResyncInterval = isset($sessionResyncInterval) ? ((int) $sessionResyncInterval) : (60 * 5);
$this->rememberCookieName = self::createRememberCookieName();
$this->initSessionIfNecessary();
$this->enhanceHttpSecurity();
$this->processRememberDirective();
$this->resyncSessionIfNecessary();
}
/** Initializes the session and sets the correct configuration */
private function initSessionIfNecessary()
{
if (\session_status() === \PHP_SESSION_NONE) {
// use cookies to store session IDs
\ini_set('session.use_cookies', 1);
// use cookies only (do not send session IDs in URLs)
\ini_set('session.use_only_cookies', 1);
// do not send session IDs in URLs
\ini_set('session.use_trans_sid', 0);
// start the session (requests a cookie to be written on the client)
@Session::start();
}
}
/** Improves the application's security over HTTP(S) by setting specific headers */
private function enhanceHttpSecurity()
{
// remove exposure of PHP version (at least where possible)
\header_remove('X-Powered-By');
// if the user is signed in
if ($this->isLoggedIn()) {
// prevent clickjacking
\header('X-Frame-Options: sameorigin');
// prevent content sniffing (MIME sniffing)
\header('X-Content-Type-Options: nosniff');
// disable caching of potentially sensitive data
\header('Cache-Control: no-store, no-cache, must-revalidate', true);
\header('Expires: Thu, 19 Nov 1981 00:00:00 GMT', true);
\header('Pragma: no-cache', true);
}
}
/** Checks if there is a "remember me" directive set and handles the automatic login (if appropriate) */
private function processRememberDirective()
{
// if the user is not signed in yet
if (!$this->isLoggedIn()) {
// if there is currently no cookie for the 'remember me' feature
if (!isset($_COOKIE[$this->rememberCookieName])) {
// if an old cookie for that feature from versions v1.x.x to v6.x.x has been found
if (isset($_COOKIE['auth_remember'])) {
// use the value from that old cookie instead
$_COOKIE[$this->rememberCookieName] = $_COOKIE['auth_remember'];
}
}
// if a remember cookie is set
if (isset($_COOKIE[$this->rememberCookieName])) {
// assume the cookie and its contents to be invalid until proven otherwise
$valid = false;
// split the cookie's content into selector and token
$parts = \explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[$this->rememberCookieName], 2);
// if both selector and token were found
if (!empty($parts[0]) && !empty($parts[1])) {
try {
$rememberData = $this->db->selectRow(
'SELECT a.user, a.token, a.expires, b.email, b.username, b.status, b.roles_mask, b.force_logout FROM ' . $this->makeTableName(self::$tables['remembered']) . ' AS a JOIN ' . $this->makeTableName(self::$tables['users']) . ' AS b ON a.user = b.id WHERE a.selector = ?',
[$parts[0]]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
if (!empty($rememberData)) {
if ($rememberData['expires'] >= \time()) {
if (\password_verify($parts[1], $rememberData['token'])) {
// the cookie and its contents have now been proven to be valid
$valid = true;
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], $rememberData['status'], $rememberData['roles_mask'], $rememberData['force_logout'], true);
}
}
}
}
// if the cookie or its contents have been invalid
if (!$valid) {
// mark the cookie as such to prevent any further futile attempts
$this->setRememberCookie('', '', \time() + 60 * 60 * 24 * 365.25);
}
}
}
}
private function resyncSessionIfNecessary()
{
// if the user is signed in
if ($this->isLoggedIn()) {
// the following session field may not have been initialized for sessions that had already existed before the introduction of this feature
if (!isset($_SESSION[self::SESSION_FIELD_LAST_RESYNC])) {
$_SESSION[self::SESSION_FIELD_LAST_RESYNC] = 0;
}
// if it's time for resynchronization
if (($_SESSION[self::SESSION_FIELD_LAST_RESYNC] + $this->sessionResyncInterval) <= \time()) {
// fetch the authoritative data from the database again
try {
$authoritativeData = $this->db->selectRow(
'SELECT email, username, status, roles_mask, force_logout FROM ' . $this->makeTableName(self::$tables['users']) . ' WHERE id = ?',
[$this->getUserId()]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
// if the user's data has been found
if (!empty($authoritativeData)) {
// the following session field may not have been initialized for sessions that had already existed before the introduction of this feature
if (!isset($_SESSION[self::SESSION_FIELD_FORCE_LOGOUT])) {
$_SESSION[self::SESSION_FIELD_FORCE_LOGOUT] = 0;
}
// if the counter that keeps track of forced logouts has been incremented
if ($authoritativeData['force_logout'] > $_SESSION[self::SESSION_FIELD_FORCE_LOGOUT]) {
// the user must be signed out
$this->logOut();
}
// if the counter that keeps track of forced logouts has remained unchanged
else {
// the session data needs to be updated
$_SESSION[self::SESSION_FIELD_EMAIL] = $authoritativeData['email'];
$_SESSION[self::SESSION_FIELD_USERNAME] = $authoritativeData['username'];
$_SESSION[self::SESSION_FIELD_STATUS] = (int) $authoritativeData['status'];
$_SESSION[self::SESSION_FIELD_ROLES] = (int) $authoritativeData['roles_mask'];
// remember that we've just performed the required resynchronization
$_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time();
}
}
// if no data has been found for the user
else {
// their account may have been deleted so they should be signed out
$this->logOut();
}
}
}
}
/**
* Attempts to sign up a user
*
* If you want the user's account to be activated by default, pass `null` as the callback
*
* If you want to make the user verify their email address first, pass an anonymous function as the callback
*
* The callback function must have the following signature:
*
* `function ($selector, $token)`
*
* Both pieces of information must be sent to the user, usually embedded in a link
*
* When the user wants to verify their email address as a next step, both pieces will be required again
*
* @param string $email the email address to register
* @param string $password the password for the new account
* @param string|null $username (optional) the username that will be displayed
* @param callable|null $callback (optional) the function that sends the confirmation email to the user
* @return int the ID of the user that has been created (if any)
* @throws InvalidEmailException if the email address was invalid
* @throws InvalidPasswordException if the password was invalid
* @throws UserAlreadyExistsException if a user with the specified email address already exists
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*
* @see confirmEmail
* @see confirmEmailAndSignIn
*/
public function register($email, $password, $username = null, callable $callback = null)
{
$this->throttle(['enumerateUsers', $this->getIpAddress()], 1, (60 * 60), 75);
$this->throttle(['createNewAccount', $this->getIpAddress()], 1, (60 * 60 * 12), 5, true);
$newUserId = $this->createUserInternal(false, $email, $password, $username, $callback);
$this->throttle(['createNewAccount', $this->getIpAddress()], 1, (60 * 60 * 12), 5, false);
return $newUserId;
}
/**
* Attempts to sign up a user while ensuring that the username is unique
*
* If you want the user's account to be activated by default, pass `null` as the callback
*
* If you want to make the user verify their email address first, pass an anonymous function as the callback
*
* The callback function must have the following signature:
*
* `function ($selector, $token)`
*
* Both pieces of information must be sent to the user, usually embedded in a link
*
* When the user wants to verify their email address as a next step, both pieces will be required again
*
* @param string $email the email address to register
* @param string $password the password for the new account
* @param string|null $username (optional) the username that will be displayed
* @param callable|null $callback (optional) the function that sends the confirmation email to the user
* @return int the ID of the user that has been created (if any)
* @throws InvalidEmailException if the email address was invalid
* @throws InvalidPasswordException if the password was invalid
* @throws UserAlreadyExistsException if a user with the specified email address already exists
* @throws DuplicateUsernameException if the specified username wasn't unique
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*
* @see confirmEmail
* @see confirmEmailAndSignIn
*/
public function registerWithUniqueUsername($email, $password, $username = null, callable $callback = null)
{
$this->throttle(['enumerateUsers', $this->getIpAddress()], 1, (60 * 60), 75);
$this->throttle(['createNewAccount', $this->getIpAddress()], 1, (60 * 60 * 12), 5, true);
$newUserId = $this->createUserInternal(true, $email, $password, $username, $callback);
$this->throttle(['createNewAccount', $this->getIpAddress()], 1, (60 * 60 * 12), 5, false);
return $newUserId;
}
/**
* Attempts to sign in a user with their email address and password
*
* @param string $email the user's email address
* @param string $password the user's password
* @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
* @param callable|null $onBeforeSuccess (optional) a function that receives the user's ID as its single parameter and is executed before successful authentication; must return `true` to proceed or `false` to cancel
* @throws InvalidEmailException if the email address was invalid or could not be found
* @throws InvalidPasswordException if the password was invalid
* @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email
* @throws AttemptCancelledException if the attempt has been cancelled by the supplied callback that is executed before success
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function login($email, $password, $rememberDuration = null, callable $onBeforeSuccess = null)
{
$this->throttle(['attemptToLogin', 'email', $email], 500, (60 * 60 * 24), null, true);
$this->authenticateUserInternal($password, $email, null, $rememberDuration, $onBeforeSuccess);
}
/**
* Attempts to sign in a user with their username and password
*
* When using this method to authenticate users, you should ensure that usernames are unique
*
* Consistently using {@see registerWithUniqueUsername} instead of {@see register} can be helpful
*
* @param string $username the user's username
* @param string $password the user's password
* @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
* @param callable|null $onBeforeSuccess (optional) a function that receives the user's ID as its single parameter and is executed before successful authentication; must return `true` to proceed or `false` to cancel
* @throws UnknownUsernameException if the specified username does not exist
* @throws AmbiguousUsernameException if the specified username is ambiguous, i.e. there are multiple users with that name
* @throws InvalidPasswordException if the password was invalid
* @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email
* @throws AttemptCancelledException if the attempt has been cancelled by the supplied callback that is executed before success
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function loginWithUsername($username, $password, $rememberDuration = null, callable $onBeforeSuccess = null)
{
$this->throttle(['attemptToLogin', 'username', $username], 500, (60 * 60 * 24), null, true);
$this->authenticateUserInternal($password, null, $username, $rememberDuration, $onBeforeSuccess);
}
/**
* Attempts to confirm the currently signed-in user's password again
*
* Whenever you want to confirm the user's identity again, e.g. before
* the user is allowed to perform some "dangerous" action, you should
* use this method to confirm that the user is who they claim to be.
*
* For example, when a user has been remembered by a long-lived cookie
* and thus {@see isRemembered} returns `true`, this means that the
* user has not entered their password for quite some time anymore.
*
* @param string $password the user's password
* @return bool whether the supplied password has been correct
* @throws NotLoggedInException if the user is not currently signed in
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function reconfirmPassword($password)
{
if ($this->isLoggedIn()) {
try {
$password = self::validatePassword($password);
} catch (InvalidPasswordException $e) {
return false;
}
$this->throttle(['reconfirmPassword', $this->getIpAddress()], 3, (60 * 60), 4, true);
try {
$expectedHash = $this->db->selectValue(
'SELECT password FROM ' . $this->makeTableName(self::$tables['users']) . ' WHERE id = ?',
[$this->getUserId()]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
if (!empty($expectedHash)) {
$validated = \password_verify($password, $expectedHash);
if (!$validated) {
$this->throttle(['reconfirmPassword', $this->getIpAddress()], 3, (60 * 60), 4, false);
}
return $validated;
} else {
throw new NotLoggedInException();
}
} else {
throw new NotLoggedInException();
}
}
/**
* Logs the user out
*
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function logOut()
{
// if the user has been signed in
if ($this->isLoggedIn()) {
// retrieve any locally existing remember directive
$rememberDirectiveSelector = $this->getRememberDirectiveSelector();
// if such a remember directive exists
if (isset($rememberDirectiveSelector)) {
// delete the local remember directive
$this->deleteRememberDirectiveForUserById(
$this->getUserId(),
$rememberDirectiveSelector
);
}
// remove all session variables maintained by this library
unset($_SESSION[self::SESSION_FIELD_LOGGED_IN]);
unset($_SESSION[self::SESSION_FIELD_USER_ID]);
unset($_SESSION[self::SESSION_FIELD_EMAIL]);
unset($_SESSION[self::SESSION_FIELD_USERNAME]);
unset($_SESSION[self::SESSION_FIELD_STATUS]);
unset($_SESSION[self::SESSION_FIELD_ROLES]);
unset($_SESSION[self::SESSION_FIELD_REMEMBERED]);
unset($_SESSION[self::SESSION_FIELD_LAST_RESYNC]);
unset($_SESSION[self::SESSION_FIELD_FORCE_LOGOUT]);
}
}
/**
* Logs the user out in all other sessions (except for the current one)
*
* @throws NotLoggedInException if the user is not currently signed in
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function logOutEverywhereElse()
{
if (!$this->isLoggedIn()) {
throw new NotLoggedInException();
}
// determine the expiry date of any locally existing remember directive
$previousRememberDirectiveExpiry = $this->getRememberDirectiveExpiry();
// schedule a forced logout in all sessions
$this->forceLogoutForUserById($this->getUserId());
// the following session field may not have been initialized for sessions that had already existed before the introduction of this feature
if (!isset($_SESSION[self::SESSION_FIELD_FORCE_LOGOUT])) {
$_SESSION[self::SESSION_FIELD_FORCE_LOGOUT] = 0;
}
// ensure that we will simply skip or ignore the next forced logout (which we have just caused) in the current session
$_SESSION[self::SESSION_FIELD_FORCE_LOGOUT]++;
// re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client)
Session::regenerate(true);
// if there had been an existing remember directive previously
if (isset($previousRememberDirectiveExpiry)) {
// restore the directive with the old expiry date but new credentials
$this->createRememberDirective(
$this->getUserId(),
$previousRememberDirectiveExpiry - \time()
);
}
}
/**
* Logs the user out in all sessions
*
* @throws NotLoggedInException if the user is not currently signed in
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function logOutEverywhere()
{
if (!$this->isLoggedIn()) {
throw new NotLoggedInException();
}
// schedule a forced logout in all sessions
$this->forceLogoutForUserById($this->getUserId());
// and immediately apply the logout locally
$this->logOut();
}
/**
* Destroys all session data
*
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function destroySession()
{
// remove all session variables without exception
$_SESSION = [];
// delete the session cookie
$this->deleteSessionCookie();
// let PHP destroy the session
\session_destroy();
}
/**
* Creates a new directive keeping the user logged in ("remember me")
*
* @param int $userId the user ID to keep signed in
* @param int $duration the duration in seconds
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function createRememberDirective($userId, $duration)
{
$selector = self::createRandomString(24);
$token = self::createRandomString(32);
$tokenHashed = \password_hash($token, $this->passwordHashAlgo);
$expires = \time() + ((int) $duration);
try {
$this->db->insert(
$this->makeTableNameComponents(self::$tables['remembered']),
[
'user' => $userId,
'selector' => $selector,
'token' => $tokenHashed,
'expires' => $expires
]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
$this->setRememberCookie($selector, $token, $expires);
}
protected function deleteRememberDirectiveForUserById($userId, $selector = null)
{
parent::deleteRememberDirectiveForUserById($userId, $selector);
$this->setRememberCookie(null, null, \time() - 3600);
}
/**
* Sets or updates the cookie that manages the "remember me" token
*
* @param string|null $selector the selector from the selector/token pair
* @param string|null $token the token from the selector/token pair
* @param int $expires the UNIX time in seconds which the token should expire at
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function setRememberCookie($selector, $token, $expires)
{
$params = \session_get_cookie_params();
if (isset($selector) && isset($token)) {
$content = $selector . self::COOKIE_CONTENT_SEPARATOR . $token;
} else {
$content = '';
}
// save the cookie with the selector and token (requests a cookie to be written on the client)
$cookie = new Cookie($this->rememberCookieName);
$cookie->setValue($content);
$cookie->setExpiryTime($expires);
$cookie->setPath($params['path']);
$cookie->setDomain($params['domain']);
$cookie->setHttpOnly($params['httponly']);
$cookie->setSecureOnly($params['secure']);
$result = $cookie->save();
if ($result === false) {
throw new HeadersAlreadySentError();
}
// if we've been deleting the cookie above
if (!isset($selector) || !isset($token)) {
// attempt to delete a potential old cookie from versions v1.x.x to v6.x.x as well (requests a cookie to be written on the client)
$cookie = new Cookie('auth_remember');
$cookie->setPath((!empty($params['path'])) ? $params['path'] : '/');
$cookie->setDomain($params['domain']);
$cookie->setHttpOnly($params['httponly']);
$cookie->setSecureOnly($params['secure']);
$cookie->delete();
}
}
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered)
{
// update the timestamp of the user's last login
try {
$this->db->update(
$this->makeTableNameComponents(self::$tables['users']),
['last_login' => \time()],
['id' => $userId]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
parent::onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered);
}
/**
* Deletes the session cookie on the client
*
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function deleteSessionCookie()
{
$params = \session_get_cookie_params();
// ask for the session cookie to be deleted (requests a cookie to be written on the client)
$cookie = new Cookie(\session_name());
$cookie->setPath($params['path']);
$cookie->setDomain($params['domain']);
$cookie->setHttpOnly($params['httponly']);
$cookie->setSecureOnly($params['secure']);
$result = $cookie->delete();
if ($result === false) {
throw new HeadersAlreadySentError();
}
}
/**
* Confirms an email address (and activates the account) by supplying the correct selector/token pair
*
* The selector/token pair must have been generated previously by registering a new account
*
* @param string $selector the selector from the selector/token pair
* @param string $token the token from the selector/token pair
* @return string[] an array with the old email address (if any) at index zero and the new email address (which has just been verified) at index one
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
* @throws TokenExpiredException if the token has already expired
* @throws UserAlreadyExistsException if an attempt has been made to change the email address to a (now) occupied address
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function confirmEmail($selector, $token)
{
$this->throttle(['confirmEmail', $this->getIpAddress()], 5, (60 * 60), 10);
$this->throttle(['confirmEmail', 'selector', $selector], 3, (60 * 60), 10);
$this->throttle(['confirmEmail', 'token', $token], 3, (60 * 60), 10);
try {
$confirmationData = $this->db->selectRow(
'SELECT a.id, a.user_id, a.email AS new_email, a.token, a.expires, b.email AS old_email FROM ' . $this->makeTableName(self::$tables['confirmations']) . ' AS a JOIN ' . $this->makeTableName(self::$tables['users']) . ' AS b ON b.id = a.user_id WHERE a.selector = ?',
[$selector]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
if (!empty($confirmationData)) {
if (\password_verify($token, $confirmationData['token'])) {
if ($confirmationData['expires'] >= \time()) {
// invalidate any potential outstanding password reset requests
try {
$this->db->delete(
$this->makeTableNameComponents(self::$tables['resets']),
['user' => $confirmationData['user_id']]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
// mark the email address as verified (and possibly update it to the new address given)
try {
$this->db->update(
$this->makeTableNameComponents(self::$tables['users']),
[
'email' => $confirmationData['new_email'],
'verified' => 1
],
['id' => $confirmationData['user_id']]
);
} catch (IntegrityConstraintViolationException $e) {
throw new UserAlreadyExistsException();
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
// if the user is currently signed in
if ($this->isLoggedIn()) {
// if the user has just confirmed an email address for their own account
if ($this->getUserId() === $confirmationData['user_id']) {
// immediately update the email address in the current session as well
$_SESSION[self::SESSION_FIELD_EMAIL] = $confirmationData['new_email'];
}
}
// consume the token just being used for confirmation
try {
$this->db->delete(
$this->makeTableNameComponents(self::$tables['confirmations']),
['id' => $confirmationData['id']]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
// if the email address has not been changed but simply been verified
if ($confirmationData['old_email'] === $confirmationData['new_email']) {
// the output should not contain any previous email address
$confirmationData['old_email'] = null;
}
return [
$confirmationData['old_email'],
$confirmationData['new_email']
];
} else {
throw new TokenExpiredException();
}
} else {
throw new InvalidSelectorTokenPairException();
}
} else {
throw new InvalidSelectorTokenPairException();
}
}
/**
* Confirms an email address and activates the account by supplying the correct selector/token pair
*
* The selector/token pair must have been generated previously by registering a new account
*
* The user will be automatically signed in if this operation is successful
*
* @param string $selector the selector from the selector/token pair
* @param string $token the token from the selector/token pair
* @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
* @return string[] an array with the old email address (if any) at index zero and the new email address (which has just been verified) at index one
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
* @throws TokenExpiredException if the token has already expired
* @throws UserAlreadyExistsException if an attempt has been made to change the email address to a (now) occupied address
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function confirmEmailAndSignIn($selector, $token, $rememberDuration = null)
{
$emailBeforeAndAfter = $this->confirmEmail($selector, $token);
if (!$this->isLoggedIn()) {
if ($emailBeforeAndAfter[1] !== null) {
$emailBeforeAndAfter[1] = self::validateEmailAddress($emailBeforeAndAfter[1]);
$userData = $this->getUserDataByEmailAddress(
$emailBeforeAndAfter[1],
['id', 'email', 'username', 'status', 'roles_mask', 'force_logout']
);
$this->onLoginSuccessful($userData['id'], $userData['email'], $userData['username'], $userData['status'], $userData['roles_mask'], $userData['force_logout'], true);
if ($rememberDuration !== null) {
$this->createRememberDirective($userData['id'], $rememberDuration);
}
}
}
return $emailBeforeAndAfter;
}
/**
* Changes the currently signed-in user's password while requiring the old password for verification
*
* @param string $oldPassword the old password to verify account ownership
* @param string $newPassword the new password that should be set
* @throws NotLoggedInException if the user is not currently signed in
* @throws InvalidPasswordException if either the old password has been wrong or the desired new one has been invalid
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function changePassword($oldPassword, $newPassword)
{
if ($this->reconfirmPassword($oldPassword)) {
$this->changePasswordWithoutOldPassword($newPassword);
} else {
throw new InvalidPasswordException();
}
}
/**
* Changes the currently signed-in user's password without requiring the old password for verification
*
* @param string $newPassword the new password that should be set
* @throws NotLoggedInException if the user is not currently signed in
* @throws InvalidPasswordException if the desired new password has been invalid
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function changePasswordWithoutOldPassword($newPassword)
{
if ($this->isLoggedIn()) {
$newPassword = self::validatePassword($newPassword);
$this->updatePasswordInternal($this->getUserId(), $newPassword);
try {
$this->logOutEverywhereElse();
} catch (NotLoggedInException $ignored) {
}
} else {
throw new NotLoggedInException();
}
}
/**
* Attempts to change the email address of the currently signed-in user (which requires confirmation)
*
* The callback function must have the following signature:
*
* `function ($selector, $token)`
*
* Both pieces of information must be sent to the user, usually embedded in a link
*
* When the user wants to verify their email address as a next step, both pieces will be required again
*
* @param string $newEmail the desired new email address
* @param callable $callback the function that sends the confirmation email to the user
* @throws InvalidEmailException if the desired new email address is invalid
* @throws UserAlreadyExistsException if a user with the desired new email address already exists
* @throws EmailNotVerifiedException if the current (old) email address has not been verified yet
* @throws NotLoggedInException if the user is not currently signed in
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*
* @see confirmEmail
* @see confirmEmailAndSignIn
*/
public function changeEmail($newEmail, callable $callback)
{
if ($this->isLoggedIn()) {
$newEmail = self::validateEmailAddress($newEmail);
$this->throttle(['enumerateUsers', $this->getIpAddress()], 1, (60 * 60), 75);
try {
$existingUsersWithNewEmail = $this->db->selectValue(
'SELECT COUNT(*) FROM ' . $this->makeTableName(self::$tables['users']) . ' WHERE email = ?',
[$newEmail]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
if ((int) $existingUsersWithNewEmail !== 0) {
throw new UserAlreadyExistsException();
}
try {
$verified = $this->db->selectValue(
'SELECT verified FROM ' . $this->makeTableName(self::$tables['users']) . ' WHERE id = ?',
[$this->getUserId()]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
// ensure that at least the current (old) email address has been verified before proceeding
if ((int) $verified !== 1) {
throw new EmailNotVerifiedException();
}
$this->throttle(['requestEmailChange', 'userId', $this->getUserId()], 1, (60 * 60 * 24));
$this->throttle(['requestEmailChange', $this->getIpAddress()], 1, (60 * 60 * 24), 3);
$this->createConfirmationRequest($this->getUserId(), $newEmail, $callback);
} else {
throw new NotLoggedInException();
}
}
/**
* Attempts to re-send an earlier confirmation request for the user with the specified email address
*
* The callback function must have the following signature:
*
* `function ($selector, $token)`
*
* Both pieces of information must be sent to the user, usually embedded in a link
*
* When the user wants to verify their email address as a next step, both pieces will be required again
*
* @param string $email the email address of the user to re-send the confirmation request for
* @param callable $callback the function that sends the confirmation request to the user
* @throws ConfirmationRequestNotFound if no previous request has been found that could be re-sent
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
*/
public function resendConfirmationForEmail($email, callable $callback)
{
$this->throttle(['enumerateUsers', $this->getIpAddress()], 1, (60 * 60), 75);
$this->resendConfirmationForColumnValue('email', $email, $callback);
}
/**
* Attempts to re-send an earlier confirmation request for the user with the specified ID
*
* The callback function must have the following signature:
*
* `function ($selector, $token)`
*
* Both pieces of information must be sent to the user, usually embedded in a link
*
* When the user wants to verify their email address as a next step, both pieces will be required again
*
* @param int $userId the ID of the user to re-send the confirmation request for
* @param callable $callback the function that sends the confirmation request to the user
* @throws ConfirmationRequestNotFound if no previous request has been found that could be re-sent
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
*/
public function resendConfirmationForUserId($userId, callable $callback)
{
$this->resendConfirmationForColumnValue('user_id', $userId, $callback);
}
/**
* Attempts to re-send an earlier confirmation request
*
* The callback function must have the following signature:
*
* `function ($selector, $token)`
*
* Both pieces of information must be sent to the user, usually embedded in a link
*
* When the user wants to verify their email address as a next step, both pieces will be required again
*
* You must never pass untrusted input to the parameter that takes the column name
*
* @param string $columnName the name of the column to filter by
* @param mixed $columnValue the value to look for in the selected column
* @param callable $callback the function that sends the confirmation request to the user
* @throws ConfirmationRequestNotFound if no previous request has been found that could be re-sent
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function resendConfirmationForColumnValue($columnName, $columnValue, callable $callback)
{
try {
$latestAttempt = $this->db->selectRow(
'SELECT user_id, email FROM ' . $this->makeTableName(self::$tables['confirmations']) . ' WHERE ' . $columnName . ' = ? ORDER BY id DESC LIMIT 1 OFFSET 0',
[$columnValue]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
if ($latestAttempt === null) {
throw new ConfirmationRequestNotFound();
}
$this->throttle(['resendConfirmation', 'userId', $latestAttempt['user_id']], 1, (60 * 60 * 6));
$this->throttle(['resendConfirmation', $this->getIpAddress()], 4, (60 * 60 * 24 * 7), 2);
$this->createConfirmationRequest(
$latestAttempt['user_id'],
$latestAttempt['email'],
$callback
);
}
/**
* Initiates a password reset request for the user with the specified email address
*
* The callback function must have the following signature:
*
* `function ($selector, $token)`
*
* Both pieces of information must be sent to the user, usually embedded in a link
*
* When the user wants to proceed to the second step of the password reset, both pieces will be required again
*
* @param string $email the email address of the user who wants to request the password reset
* @param callable $callback the function that sends the password reset information to the user
* @param int|null $requestExpiresAfter (optional) the interval in seconds after which the request should expire
* @param int|null $maxOpenRequests (optional) the maximum number of unexpired and unused requests per user
* @throws InvalidEmailException if the email address was invalid or could not be found
* @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*
* @see canResetPasswordOrThrow
* @see canResetPassword
* @see resetPassword
* @see resetPasswordAndSignIn
*/
public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null)
{
$email = self::validateEmailAddress($email);
$this->throttle(['enumerateUsers', $this->getIpAddress()], 1, (60 * 60), 75);
if ($requestExpiresAfter === null) {
// use six hours as the default