/
AbstractUserAuthentication.php
1485 lines (1360 loc) · 54.9 KB
/
AbstractUserAuthentication.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
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 TYPO3\CMS\Core\Authentication;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Crypto\Random;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
use TYPO3\CMS\Core\Database\Query\Restriction\RootLevelRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
use TYPO3\CMS\Core\Exception;
use TYPO3\CMS\Core\Session\Backend\Exception\SessionNotFoundException;
use TYPO3\CMS\Core\Session\Backend\SessionBackendInterface;
use TYPO3\CMS\Core\Session\SessionManager;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
/**
* Authentication of users in TYPO3
*
* This class is used to authenticate a login user.
* The class is used by both the frontend and backend.
* In both cases this class is a parent class to BackendUserAuthentication and FrontendUserAuthentication
*
* See Inside TYPO3 for more information about the API of the class and internal variables.
*/
abstract class AbstractUserAuthentication implements LoggerAwareInterface
{
use LoggerAwareTrait;
/**
* Session/Cookie name
* @var string
*/
public $name = '';
/**
* Table in database with user data
* @var string
*/
public $user_table = '';
/**
* Table in database with user groups
* @var string
*/
public $usergroup_table = '';
/**
* Column for login-name
* @var string
*/
public $username_column = '';
/**
* Column for password
* @var string
*/
public $userident_column = '';
/**
* Column for user-id
* @var string
*/
public $userid_column = '';
/**
* Column for user group information
* @var string
*/
public $usergroup_column = '';
/**
* Column name for last login timestamp
* @var string
*/
public $lastLogin_column = '';
/**
* Enable field columns of user table
* @var array
*/
public $enablecolumns = [
'rootLevel' => '',
// Boolean: If TRUE, 'AND pid=0' will be a part of the query...
'disabled' => '',
'starttime' => '',
'endtime' => '',
'deleted' => '',
];
/**
* @var bool
*/
public $showHiddenRecords = false;
/**
* Form field with login-name
* @var string
*/
public $formfield_uname = '';
/**
* Form field with password
* @var string
*/
public $formfield_uident = '';
/**
* Form field with status: *'login', 'logout'. If empty login is not verified.
* @var string
*/
public $formfield_status = '';
/**
* Session timeout (on the server)
*
* If >0: session-timeout in seconds.
* If <=0: Instant logout after login.
*
* @var int
*/
public $sessionTimeout = 0;
/**
* Name for a field to fetch the server session timeout from.
* If not empty this is a field name from the user table where the timeout can be found.
* @var string
*/
public $auth_timeout_field = '';
/**
* Lifetime for the session-cookie (on the client)
*
* If >0: permanent cookie with given lifetime
* If 0: session-cookie
* Session-cookie means the browser will remove it when the browser is closed.
*
* @var int
*/
public $lifetime = 0;
/**
* GarbageCollection
* Purge all server session data older than $gc_time seconds.
* if $this->sessionTimeout > 0, then the session timeout is used instead.
* @var int
*/
public $gc_time = 86400;
/**
* Probability for garbage collection to be run (in percent)
* @var int
*/
public $gc_probability = 1;
/**
* Decides if the writelog() function is called at login and logout
* @var bool
*/
public $writeStdLog = false;
/**
* Log failed login attempts
* @var bool
*/
public $writeAttemptLog = false;
/**
* Send no-cache headers
* @var bool
*/
public $sendNoCacheHeaders = true;
/**
* The ident-hash is normally 32 characters and should be!
* But if you are making sites for WAP-devices or other low-bandwidth stuff,
* you may shorten the length.
* Never let this value drop below 6!
* A length of 6 would give you more than 16 mio possibilities.
* @var int
*/
public $hash_length = 32;
/**
* If set to 4, the session will be locked to the user's IP address (all four numbers).
* Reducing this to 1-3 means that only the given number of parts of the IP address is used.
* @var int
*/
public $lockIP = 4;
/**
* @var string
*/
public $warningEmail = '';
/**
* Time span (in seconds) within the number of failed logins are collected
* @var int
*/
public $warningPeriod = 3600;
/**
* The maximum accepted number of warnings before an email to $warningEmail is sent
* @var int
*/
public $warningMax = 3;
/**
* If set, the user-record must be stored at the page defined by $checkPid_value
* @var bool
*/
public $checkPid = true;
/**
* The page id the user record must be stored at
* @var int
*/
public $checkPid_value = 0;
/**
* session_id (MD5-hash)
* @var string
* @internal
*/
public $id;
/**
* Indicates if an authentication was started but failed
* @var bool
*/
public $loginFailure = false;
/**
* Will be set to TRUE if the login session is actually written during auth-check.
* @var bool
*/
public $loginSessionStarted = false;
/**
* @var array|null contains user- AND session-data from database (joined tables)
* @internal
*/
public $user;
/**
* Will be set to TRUE if a new session ID was created
* @var bool
*/
public $newSessionID = false;
/**
* Will force the session cookie to be set every time (lifetime must be 0)
* @var bool
*/
public $forceSetCookie = false;
/**
* Will prevent the setting of the session cookie (takes precedence over forceSetCookie)
* @var bool
*/
public $dontSetCookie = false;
/**
* @var bool
*/
protected $cookieWasSetOnCurrentRequest = false;
/**
* Login type, used for services.
* @var string
*/
public $loginType = '';
/**
* "auth" services configuration array from $GLOBALS['TYPO3_CONF_VARS']['SVCONF']['auth']
* @var array
*/
public $svConfig = [];
/**
* @var array
*/
public $uc;
/**
* @var SessionBackendInterface
*/
protected $sessionBackend;
/**
* Holds deserialized data from session records.
* 'Reserved' keys are:
* - 'sys': Reserved for TypoScript standard code.
* @var array
*/
protected $sessionData = [];
/**
* Initialize some important variables
*
* @throws Exception
*/
public function __construct()
{
$this->svConfig = $GLOBALS['TYPO3_CONF_VARS']['SVCONF']['auth'] ?? [];
// If there is a custom session timeout, use this instead of the 1d default gc time.
if ($this->sessionTimeout > 0) {
$this->gc_time = $this->sessionTimeout;
}
// Backend or frontend login - used for auth services
if (empty($this->loginType)) {
throw new Exception('No loginType defined, must be set explicitly by subclass', 1476045345);
}
}
/**
* Starts a user session
* Typical configurations will:
* a) check if session cookie was set and if not, set one,
* b) check if a password/username was sent and if so, try to authenticate the user
* c) Lookup a session attached to a user and check timeout etc.
* d) Garbage collection, setting of no-cache headers.
* If a user is authenticated the database record of the user (array) will be set in the ->user internal variable.
*/
public function start()
{
$this->logger->debug('## Beginning of auth logging.');
$this->newSessionID = false;
// Make certain that NO user is set initially
$this->user = null;
// sessionID is set to ses_id if cookie is present. Otherwise a new session will start
$this->id = $this->getCookie($this->name);
// If new session or client tries to fix session...
if (!$this->isExistingSessionRecord($this->id)) {
$this->id = $this->createSessionId();
$this->newSessionID = true;
}
// Set all possible headers that could ensure that the script is not cached on the client-side
$this->sendHttpHeaders();
// Load user session, check to see if anyone has submitted login-information and if so authenticate
// the user with the session. $this->user[uid] may be used to write log...
$this->checkAuthentication();
// Setting cookies
if (!$this->dontSetCookie) {
$this->setSessionCookie();
}
// Hook for alternative ways of filling the $this->user array (is used by the "timtaw" extension)
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'] ?? [] as $funcName) {
$_params = [
'pObj' => $this,
];
GeneralUtility::callUserFunction($funcName, $_params, $this);
}
// If we're lucky we'll get to clean up old sessions
if (rand() % 100 <= $this->gc_probability) {
$this->gc();
}
}
/**
* Set all possible headers that could ensure that the script
* is not cached on the client-side.
*
* Only do this if $this->sendNoCacheHeaders is set.
*/
protected function sendHttpHeaders()
{
// skip sending the "no-cache" headers if it's a CLI request or the no-cache headers should not be sent.
if (!$this->sendNoCacheHeaders || Environment::isCli()) {
return;
}
$httpHeaders = $this->getHttpHeaders();
foreach ($httpHeaders as $httpHeaderName => $value) {
header($httpHeaderName . ': ' . $value);
}
}
/**
* Get the http headers to be sent if an authenticated user is available, in order to disallow
* browsers to store the response on the client side.
*
* @return array
*/
protected function getHttpHeaders(): array
{
$headers = [
'Expires' => 0,
'Last-Modified' => gmdate('D, d M Y H:i:s') . ' GMT'
];
$cacheControlHeader = 'no-cache, must-revalidate';
$pragmaHeader = 'no-cache';
// Prevent error message in IE when using a https connection
// see http://forge.typo3.org/issues/24125
if (strpos(GeneralUtility::getIndpEnv('HTTP_USER_AGENT'), 'MSIE') !== false
&& GeneralUtility::getIndpEnv('TYPO3_SSL')) {
// Some IEs can not handle no-cache
// see http://support.microsoft.com/kb/323308/en-us
$cacheControlHeader = 'must-revalidate';
// IE needs "Pragma: private" if SSL connection
$pragmaHeader = 'private';
}
$headers['Cache-Control'] = $cacheControlHeader;
$headers['Pragma'] = $pragmaHeader;
return $headers;
}
/**
* Sets the session cookie for the current disposal.
*
* @throws Exception
*/
protected function setSessionCookie()
{
$isSetSessionCookie = $this->isSetSessionCookie();
$isRefreshTimeBasedCookie = $this->isRefreshTimeBasedCookie();
if ($isSetSessionCookie || $isRefreshTimeBasedCookie) {
$settings = $GLOBALS['TYPO3_CONF_VARS']['SYS'];
// Get the domain to be used for the cookie (if any):
$cookieDomain = $this->getCookieDomain();
// If no cookie domain is set, use the base path:
$cookiePath = $cookieDomain ? '/' : GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
// If the cookie lifetime is set, use it:
$cookieExpire = $isRefreshTimeBasedCookie ? $GLOBALS['EXEC_TIME'] + $this->lifetime : 0;
// Use the secure option when the current request is served by a secure connection:
$cookieSecure = (bool)$settings['cookieSecure'] && GeneralUtility::getIndpEnv('TYPO3_SSL');
// Do not set cookie if cookieSecure is set to "1" (force HTTPS) and no secure channel is used:
if ((int)$settings['cookieSecure'] !== 1 || GeneralUtility::getIndpEnv('TYPO3_SSL')) {
setcookie($this->name, $this->id, $cookieExpire, $cookiePath, $cookieDomain, $cookieSecure, true);
$this->cookieWasSetOnCurrentRequest = true;
} else {
throw new Exception('Cookie was not set since HTTPS was forced in $TYPO3_CONF_VARS[SYS][cookieSecure].', 1254325546);
}
$this->logger->debug(
($isRefreshTimeBasedCookie ? 'Updated Cookie: ' : 'Set Cookie: ')
. $this->id . ($cookieDomain ? ', ' . $cookieDomain : '')
);
}
}
/**
* Gets the domain to be used on setting cookies.
* The information is taken from the value in $GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieDomain'].
*
* @return string The domain to be used on setting cookies
*/
protected function getCookieDomain()
{
$result = '';
$cookieDomain = $GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieDomain'];
// If a specific cookie domain is defined for a given TYPO3_MODE,
// use that domain
if (!empty($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['cookieDomain'])) {
$cookieDomain = $GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['cookieDomain'];
}
if ($cookieDomain) {
if ($cookieDomain[0] === '/') {
$match = [];
$matchCnt = @preg_match($cookieDomain, GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'), $match);
if ($matchCnt === false) {
$this->logger->critical('The regular expression for the cookie domain (' . $cookieDomain . ') contains errors. The session is not shared across sub-domains.');
} elseif ($matchCnt) {
$result = $match[0];
}
} else {
$result = $cookieDomain;
}
}
return $result;
}
/**
* Get the value of a specified cookie.
*
* @param string $cookieName The cookie ID
* @return string The value stored in the cookie
*/
protected function getCookie($cookieName)
{
return isset($_COOKIE[$cookieName]) ? stripslashes($_COOKIE[$cookieName]) : '';
}
/**
* Determine whether a session cookie needs to be set (lifetime=0)
*
* @return bool
* @internal
*/
public function isSetSessionCookie()
{
return ($this->newSessionID || $this->forceSetCookie) && $this->lifetime == 0;
}
/**
* Determine whether a non-session cookie needs to be set (lifetime>0)
*
* @return bool
* @internal
*/
public function isRefreshTimeBasedCookie()
{
return $this->lifetime > 0;
}
/**
* Checks if a submission of username and password is present or use other authentication by auth services
*
* @throws \RuntimeException
* @internal
*/
public function checkAuthentication()
{
// No user for now - will be searched by service below
$tempuserArr = [];
$tempuser = false;
// User is not authenticated by default
$authenticated = false;
// User want to login with passed login data (name/password)
$activeLogin = false;
// Indicates if an active authentication failed (not auto login)
$this->loginFailure = false;
$this->logger->debug('Login type: ' . $this->loginType);
// The info array provide additional information for auth services
$authInfo = $this->getAuthInfoArray();
// Get Login/Logout data submitted by a form or params
$loginData = $this->getLoginFormData();
$this->logger->debug('Login data', $loginData);
// Active logout (eg. with "logout" button)
if ($loginData['status'] === LoginType::LOGOUT) {
if ($this->writeStdLog) {
// $type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid
$this->writelog(255, 2, 0, 2, 'User %s logged out', [$this->user['username']], '', 0, 0);
}
$this->logger->info('User logged out. Id: ' . $this->id);
$this->logoff();
}
// Determine whether we need to skip session update.
// This is used mainly for checking session timeout in advance without refreshing the current session's timeout.
$skipSessionUpdate = (bool)GeneralUtility::_GP('skipSessionUpdate');
$haveSession = false;
$anonymousSession = false;
if (!$this->newSessionID) {
// Read user session
$authInfo['userSession'] = $this->fetchUserSession($skipSessionUpdate);
$haveSession = is_array($authInfo['userSession']);
if ($haveSession && !empty($authInfo['userSession']['ses_anonymous'])) {
$anonymousSession = true;
}
}
// Active login (eg. with login form).
if (!$haveSession && $loginData['status'] === LoginType::LOGIN) {
$activeLogin = true;
$this->logger->debug('Active login (eg. with login form)');
// check referrer for submitted login values
if ($this->formfield_status && $loginData['uident'] && $loginData['uname']) {
// Delete old user session if any
$this->logoff();
}
// Refuse login for _CLI users, if not processing a CLI request type
// (although we shouldn't be here in case of a CLI request type)
if (stripos($loginData['uname'], '_CLI_') === 0 && !Environment::isCli()) {
throw new \RuntimeException('TYPO3 Fatal Error: You have tried to login using a CLI user. Access prohibited!', 1270853931);
}
}
// Cause elevation of privilege, make sure regenerateSessionId is called later on
if ($anonymousSession && $loginData['status'] === LoginType::LOGIN) {
$activeLogin = true;
}
if ($haveSession) {
$this->logger->debug('User session found', [
$this->userid_column => $authInfo['userSession'][$this->userid_column] ?? null,
$this->username_column => $authInfo['userSession'][$this->username_column] ?? null,
]);
} else {
$this->logger->debug('No user session found');
}
if (is_array($this->svConfig['setup'] ?? false)) {
$this->logger->debug('SV setup', $this->svConfig['setup']);
}
// Fetch user if ...
if (
$activeLogin || !empty($this->svConfig['setup'][$this->loginType . '_alwaysFetchUser'])
|| !$haveSession && !empty($this->svConfig['setup'][$this->loginType . '_fetchUserIfNoSession'])
) {
// Use 'auth' service to find the user
// First found user will be used
$subType = 'getUser' . $this->loginType;
/** @var AuthenticationService $serviceObj */
foreach ($this->getAuthServices($subType, $loginData, $authInfo) as $serviceObj) {
if ($row = $serviceObj->getUser()) {
$tempuserArr[] = $row;
$this->logger->debug('User found', [
$this->userid_column => $row[$this->userid_column],
$this->username_column => $row[$this->username_column],
]);
// User found, just stop to search for more if not configured to go on
if (empty($this->svConfig['setup'][$this->loginType . '_fetchAllUsers'])) {
break;
}
}
}
if (!empty($this->svConfig['setup'][$this->loginType . '_alwaysFetchUser'])) {
$this->logger->debug($this->loginType . '_alwaysFetchUser option is enabled');
}
if (empty($tempuserArr)) {
$this->logger->debug('No user found by services');
} else {
$this->logger->debug(count($tempuserArr) . ' user records found by services');
}
}
// If no new user was set we use the already found user session
if (empty($tempuserArr) && $haveSession && !$anonymousSession) {
$tempuserArr[] = $authInfo['userSession'];
$tempuser = $authInfo['userSession'];
// User is authenticated because we found a user session
$authenticated = true;
$this->logger->debug('User session used', [
$this->userid_column => $authInfo['userSession'][$this->userid_column],
$this->username_column => $authInfo['userSession'][$this->username_column],
]);
}
// Re-auth user when 'auth'-service option is set
if (!empty($this->svConfig['setup'][$this->loginType . '_alwaysAuthUser'])) {
$authenticated = false;
$this->logger->debug('alwaysAuthUser option is enabled');
}
// Authenticate the user if needed
if (!empty($tempuserArr) && !$authenticated) {
foreach ($tempuserArr as $tempuser) {
// Use 'auth' service to authenticate the user
// If one service returns FALSE then authentication failed
// a service might return 100 which means there's no reason to stop but the user can't be authenticated by that service
$this->logger->debug('Auth user', $tempuser);
$subType = 'authUser' . $this->loginType;
/** @var AuthenticationService $serviceObj */
foreach ($this->getAuthServices($subType, $loginData, $authInfo) as $serviceObj) {
if (($ret = $serviceObj->authUser($tempuser)) > 0) {
// If the service returns >=200 then no more checking is needed - useful for IP checking without password
if ((int)$ret >= 200) {
$authenticated = true;
break;
}
if ((int)$ret >= 100) {
} else {
$authenticated = true;
}
} else {
$authenticated = false;
break;
}
}
if ($authenticated) {
// Leave foreach() because a user is authenticated
break;
}
}
}
// If user is authenticated a valid user is in $tempuser
if ($authenticated) {
// Reset failure flag
$this->loginFailure = false;
// Insert session record if needed:
if (!$haveSession || $anonymousSession || $tempuser['ses_id'] != $this->id && $tempuser['uid'] != $authInfo['userSession']['ses_userid']) {
$sessionData = $this->createUserSession($tempuser);
// Preserve session data on login
if ($anonymousSession) {
$sessionData = $this->getSessionBackend()->update(
$this->id,
['ses_data' => $authInfo['userSession']['ses_data']]
);
}
$this->user = array_merge(
$tempuser,
$sessionData
);
// The login session is started.
$this->loginSessionStarted = true;
if (is_array($this->user)) {
$this->logger->debug('User session finally read', [
$this->userid_column => $this->user[$this->userid_column],
$this->username_column => $this->user[$this->username_column],
]);
}
} elseif ($haveSession) {
// if we come here the current session is for sure not anonymous as this is a pre-condition for $authenticated = true
$this->user = $authInfo['userSession'];
}
if ($activeLogin && !$this->newSessionID) {
$this->regenerateSessionId();
}
// User logged in - write that to the log!
if ($this->writeStdLog && $activeLogin) {
$this->writelog(255, 1, 0, 1, 'User %s logged in from ###IP###', [$tempuser[$this->username_column]], '', '', '');
}
if ($activeLogin) {
$this->logger->info('User ' . $tempuser[$this->username_column] . ' logged in from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR'));
}
if (!$activeLogin) {
$this->logger->debug('User ' . $tempuser[$this->username_column] . ' authenticated from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR'));
}
} else {
// User was not authenticated, so we should reuse the existing anonymous session
if ($anonymousSession) {
$this->user = $authInfo['userSession'];
}
// Mark the current login attempt as failed
if ($activeLogin || !empty($tempuserArr)) {
$this->loginFailure = true;
if (empty($tempuserArr) && $activeLogin) {
$logData = [
'loginData' => $loginData
];
$this->logger->debug('Login failed', $logData);
}
if (!empty($tempuserArr)) {
$logData = [
$this->userid_column => $tempuser[$this->userid_column],
$this->username_column => $tempuser[$this->username_column],
];
$this->logger->debug('Login failed', $logData);
}
}
}
// If there were a login failure, check to see if a warning email should be sent:
if ($this->loginFailure && $activeLogin) {
$this->logger->debug(
'Call checkLogFailures',
[
'warningEmail' => $this->warningEmail,
'warningPeriod' => $this->warningPeriod,
'warningMax' => $this->warningMax
]
);
// Hook to implement login failure tracking methods
$_params = [];
$sleep = true;
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postLoginFailureProcessing'] ?? [] as $_funcRef) {
GeneralUtility::callUserFunction($_funcRef, $_params, $this);
$sleep = false;
}
if ($sleep) {
// No hooks were triggered - default login failure behavior is to sleep 5 seconds
sleep(5);
}
$this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax);
}
}
/**
* Creates a new session ID.
*
* @return string The new session ID
*/
public function createSessionId()
{
return GeneralUtility::makeInstance(Random::class)->generateRandomHexString($this->hash_length);
}
/**
* Initializes authentication services to be used in a foreach loop
*
* @param string $subType e.g. getUserFE
* @param array $loginData
* @param array $authInfo
* @return \Traversable A generator of service objects
*/
protected function getAuthServices(string $subType, array $loginData, array $authInfo): \Traversable
{
$serviceChain = '';
while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
$serviceChain .= ',' . $serviceObj->getServiceKey();
$serviceObj->initAuth($subType, $loginData, $authInfo, $this);
yield $serviceObj;
}
if ($serviceChain) {
$this->logger->debug($subType . ' auth services called: ' . $serviceChain);
}
}
/**
* Regenerate the session ID and transfer the session to new ID
* Call this method whenever a user proceeds to a higher authorization level
* e.g. when an anonymous session is now authenticated.
*
* @param array $existingSessionRecord If given, this session record will be used instead of fetching again
* @param bool $anonymous If true session will be regenerated as anonymous session
*/
protected function regenerateSessionId(array $existingSessionRecord = [], bool $anonymous = false)
{
if (empty($existingSessionRecord)) {
$existingSessionRecord = $this->getSessionBackend()->get($this->id);
}
// Update session record with new ID
$oldSessionId = $this->id;
$this->id = $this->createSessionId();
$updatedSession = $this->getSessionBackend()->set($this->id, $existingSessionRecord);
$this->sessionData = unserialize($updatedSession['ses_data']);
// Merge new session data into user/session array
$this->user = array_merge($this->user ?? [], $updatedSession);
$this->getSessionBackend()->remove($oldSessionId);
$this->newSessionID = true;
}
/*************************
*
* User Sessions
*
*************************/
/**
* Creates a user session record and returns its values.
*
* @param array $tempuser User data array
*
* @return array The session data for the newly created session.
*/
public function createUserSession($tempuser)
{
$this->logger->debug('Create session ses_id = ' . $this->id);
// Delete any session entry first
$this->getSessionBackend()->remove($this->id);
// Re-create session entry
$sessionRecord = $this->getNewSessionRecord($tempuser);
$sessionRecord = $this->getSessionBackend()->set($this->id, $sessionRecord);
// Updating lastLogin_column carrying information about last login.
$this->updateLoginTimestamp($tempuser[$this->userid_column]);
return $sessionRecord;
}
/**
* Updates the last login column in the user with the given id
*
* @param int $userId
*/
protected function updateLoginTimestamp(int $userId)
{
if ($this->lastLogin_column) {
$connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->user_table);
$connection->update(
$this->user_table,
[$this->lastLogin_column => $GLOBALS['EXEC_TIME']],
[$this->userid_column => $userId]
);
}
}
/**
* Returns a new session record for the current user for insertion into the DB.
* This function is mainly there as a wrapper for inheriting classes to override it.
*
* @param array $tempuser
* @return array User session record
*/
public function getNewSessionRecord($tempuser)
{
$sessionIpLock = '[DISABLED]';
if ($this->lockIP && empty($tempuser['disableIPlock'])) {
$sessionIpLock = $this->ipLockClause_remoteIPNumber($this->lockIP);
}
return [
'ses_id' => $this->id,
'ses_iplock' => $sessionIpLock,
'ses_userid' => $tempuser[$this->userid_column] ?? 0,
'ses_tstamp' => $GLOBALS['EXEC_TIME'],
'ses_data' => '',
];
}
/**
* Read the user session from db.
*
* @param bool $skipSessionUpdate
* @return array|bool User session data, false if $this->id does not represent valid session
*/
public function fetchUserSession($skipSessionUpdate = false)
{
$this->logger->debug('Fetch session ses_id = ' . $this->id);
try {
$sessionRecord = $this->getSessionBackend()->get($this->id);
} catch (SessionNotFoundException $e) {
return false;
}
$this->sessionData = unserialize($sessionRecord['ses_data']);
// Session is anonymous so no need to fetch user
if (!empty($sessionRecord['ses_anonymous'])) {
return $sessionRecord;
}
// Fetch the user from the DB
$userRecord = $this->getRawUserByUid((int)$sessionRecord['ses_userid']);
if ($userRecord) {
$userRecord = array_merge($sessionRecord, $userRecord);
// A user was found
$userRecord['ses_tstamp'] = (int)$userRecord['ses_tstamp'];
$userRecord['is_online'] = (int)$userRecord['ses_tstamp'];
if (!empty($this->auth_timeout_field)) {
// Get timeout-time from usertable
$timeout = (int)$userRecord[$this->auth_timeout_field];
} else {
$timeout = $this->sessionTimeout;
}
// If timeout > 0 (TRUE) and current time has not exceeded the latest sessions-time plus the timeout in seconds then accept user
// Use a gracetime-value to avoid updating a session-record too often
if ($timeout > 0 && $GLOBALS['EXEC_TIME'] < $userRecord['ses_tstamp'] + $timeout) {
$sessionUpdateGracePeriod = 61;
if (!$skipSessionUpdate && $GLOBALS['EXEC_TIME'] > ($userRecord['ses_tstamp'] + $sessionUpdateGracePeriod)) {
// Update the session timestamp by writing a dummy update. (Backend will update the timestamp)
$updatesSession = $this->getSessionBackend()->update($this->id, []);
$userRecord = array_merge($userRecord, $updatesSession);
}
} else {
// Delete any user set...
$this->logoff();
$userRecord = false;
}
}
return $userRecord;
}
/**
* Regenerates the session ID and sets the cookie again.
*
* @internal
*/
public function enforceNewSessionId()
{
$this->regenerateSessionId();
$this->setSessionCookie();
}
/**
* Log out current user!
* Removes the current session record, sets the internal ->user array to a blank string;
* Thereby the current user (if any) is effectively logged out!
*/
public function logoff()
{
$this->logger->debug('logoff: ses_id = ' . $this->id);
$_params = [];
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'] ?? [] as $_funcRef) {
if ($_funcRef) {
GeneralUtility::callUserFunction($_funcRef, $_params, $this);
}
}
$this->performLogoff();
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'] ?? [] as $_funcRef) {
if ($_funcRef) {
GeneralUtility::callUserFunction($_funcRef, $_params, $this);
}
}
}
/**
* Perform the logoff action. Called from logoff() as a way to allow subclasses to override
* what happens when a user logs off, without needing to reproduce the hook calls and logging