[TASK] Add LoginType enumeration
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Authentication / AbstractUserAuthentication.php
1 <?php
2 namespace TYPO3\CMS\Core\Authentication;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Psr\Log\LoggerAwareInterface;
18 use Psr\Log\LoggerAwareTrait;
19 use TYPO3\CMS\Backend\Utility\BackendUtility;
20 use TYPO3\CMS\Core\Core\Environment;
21 use TYPO3\CMS\Core\Crypto\Random;
22 use TYPO3\CMS\Core\Database\Connection;
23 use TYPO3\CMS\Core\Database\ConnectionPool;
24 use TYPO3\CMS\Core\Database\Query\QueryHelper;
25 use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
26 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
27 use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
28 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
29 use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
30 use TYPO3\CMS\Core\Database\Query\Restriction\RootLevelRestriction;
31 use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
32 use TYPO3\CMS\Core\Exception;
33 use TYPO3\CMS\Core\Session\Backend\Exception\SessionNotFoundException;
34 use TYPO3\CMS\Core\Session\Backend\SessionBackendInterface;
35 use TYPO3\CMS\Core\Session\SessionManager;
36 use TYPO3\CMS\Core\Utility\GeneralUtility;
37 use TYPO3\CMS\Core\Utility\MathUtility;
38
39 /**
40 * Authentication of users in TYPO3
41 *
42 * This class is used to authenticate a login user.
43 * The class is used by both the frontend and backend.
44 * In both cases this class is a parent class to BackendUserAuthentication and FrontendUserAuthentication
45 *
46 * See Inside TYPO3 for more information about the API of the class and internal variables.
47 */
48 abstract class AbstractUserAuthentication implements LoggerAwareInterface
49 {
50 use LoggerAwareTrait;
51
52 /**
53 * Session/Cookie name
54 * @var string
55 */
56 public $name = '';
57
58 /**
59 * Session/GET-var name
60 * @var string
61 */
62 public $get_name = '';
63
64 /**
65 * Table in database with user data
66 * @var string
67 */
68 public $user_table = '';
69
70 /**
71 * Table in database with user groups
72 * @var string
73 */
74 public $usergroup_table = '';
75
76 /**
77 * Column for login-name
78 * @var string
79 */
80 public $username_column = '';
81
82 /**
83 * Column for password
84 * @var string
85 */
86 public $userident_column = '';
87
88 /**
89 * Column for user-id
90 * @var string
91 */
92 public $userid_column = '';
93
94 /**
95 * Column for user group information
96 * @var string
97 */
98 public $usergroup_column = '';
99
100 /**
101 * Column name for last login timestamp
102 * @var string
103 */
104 public $lastLogin_column = '';
105
106 /**
107 * Enable field columns of user table
108 * @var array
109 */
110 public $enablecolumns = [
111 'rootLevel' => '',
112 // Boolean: If TRUE, 'AND pid=0' will be a part of the query...
113 'disabled' => '',
114 'starttime' => '',
115 'endtime' => '',
116 'deleted' => '',
117 ];
118
119 /**
120 * @var bool
121 */
122 public $showHiddenRecords = false;
123
124 /**
125 * Form field with login-name
126 * @var string
127 */
128 public $formfield_uname = '';
129
130 /**
131 * Form field with password
132 * @var string
133 */
134 public $formfield_uident = '';
135
136 /**
137 * Form field with status: *'login', 'logout'. If empty login is not verified.
138 * @var string
139 */
140 public $formfield_status = '';
141
142 /**
143 * Session timeout (on the server)
144 *
145 * If >0: session-timeout in seconds.
146 * If <=0: Instant logout after login.
147 *
148 * @var int
149 */
150 public $sessionTimeout = 0;
151
152 /**
153 * Name for a field to fetch the server session timeout from.
154 * If not empty this is a field name from the user table where the timeout can be found.
155 * @var string
156 */
157 public $auth_timeout_field = '';
158
159 /**
160 * Lifetime for the session-cookie (on the client)
161 *
162 * If >0: permanent cookie with given lifetime
163 * If 0: session-cookie
164 * Session-cookie means the browser will remove it when the browser is closed.
165 *
166 * @var int
167 */
168 public $lifetime = 0;
169
170 /**
171 * GarbageCollection
172 * Purge all server session data older than $gc_time seconds.
173 * 0 = default to $this->sessionTimeout or use 86400 seconds (1 day) if $this->sessionTimeout == 0
174 * @var int
175 */
176 public $gc_time = 0;
177
178 /**
179 * Probability for garbage collection to be run (in percent)
180 * @var int
181 */
182 public $gc_probability = 1;
183
184 /**
185 * Decides if the writelog() function is called at login and logout
186 * @var bool
187 */
188 public $writeStdLog = false;
189
190 /**
191 * Log failed login attempts
192 * @var bool
193 */
194 public $writeAttemptLog = false;
195
196 /**
197 * Send no-cache headers
198 * @var bool
199 */
200 public $sendNoCacheHeaders = true;
201
202 /**
203 * If this is set, authentication is also accepted by $_GET.
204 * Notice that the identification is NOT 128bit MD5 hash but reduced.
205 * This is done in order to minimize the size for mobile-devices, such as WAP-phones
206 * @var bool
207 */
208 public $getFallBack = false;
209
210 /**
211 * The ident-hash is normally 32 characters and should be!
212 * But if you are making sites for WAP-devices or other low-bandwidth stuff,
213 * you may shorten the length.
214 * Never let this value drop below 6!
215 * A length of 6 would give you more than 16 mio possibilities.
216 * @var int
217 */
218 public $hash_length = 32;
219
220 /**
221 * Setting this flag TRUE lets user-authentication happen from GET_VARS if
222 * POST_VARS are not set. Thus you may supply username/password with the URL.
223 * @var bool
224 */
225 public $getMethodEnabled = false;
226
227 /**
228 * If set to 4, the session will be locked to the user's IP address (all four numbers).
229 * Reducing this to 1-3 means that only the given number of parts of the IP address is used.
230 * @var int
231 */
232 public $lockIP = 4;
233
234 /**
235 * @var string
236 */
237 public $warningEmail = '';
238
239 /**
240 * Time span (in seconds) within the number of failed logins are collected
241 * @var int
242 */
243 public $warningPeriod = 3600;
244
245 /**
246 * The maximum accepted number of warnings before an email to $warningEmail is sent
247 * @var int
248 */
249 public $warningMax = 3;
250
251 /**
252 * If set, the user-record must be stored at the page defined by $checkPid_value
253 * @var bool
254 */
255 public $checkPid = true;
256
257 /**
258 * The page id the user record must be stored at
259 * @var int
260 */
261 public $checkPid_value = 0;
262
263 /**
264 * session_id (MD5-hash)
265 * @var string
266 * @internal
267 */
268 public $id;
269
270 /**
271 * Indicates if an authentication was started but failed
272 * @var bool
273 */
274 public $loginFailure = false;
275
276 /**
277 * Will be set to TRUE if the login session is actually written during auth-check.
278 * @var bool
279 */
280 public $loginSessionStarted = false;
281
282 /**
283 * @var array|null contains user- AND session-data from database (joined tables)
284 * @internal
285 */
286 public $user;
287
288 /**
289 * Will be added to the url (eg. '&login=ab7ef8d...')
290 * GET-auth-var if getFallBack is TRUE. Should be inserted in links!
291 * @var string
292 * @internal
293 */
294 public $get_URL_ID = '';
295
296 /**
297 * Will be set to TRUE if a new session ID was created
298 * @var bool
299 */
300 public $newSessionID = false;
301
302 /**
303 * Will force the session cookie to be set every time (lifetime must be 0)
304 * @var bool
305 */
306 public $forceSetCookie = false;
307
308 /**
309 * Will prevent the setting of the session cookie (takes precedence over forceSetCookie)
310 * @var bool
311 */
312 public $dontSetCookie = false;
313
314 /**
315 * @var bool
316 */
317 protected $cookieWasSetOnCurrentRequest = false;
318
319 /**
320 * Login type, used for services.
321 * @var string
322 */
323 public $loginType = '';
324
325 /**
326 * "auth" services configuration array from $GLOBALS['TYPO3_CONF_VARS']['SVCONF']['auth']
327 * @var array
328 */
329 public $svConfig = [];
330
331 /**
332 * @var array
333 */
334 public $uc;
335
336 /**
337 * @var SessionBackendInterface
338 */
339 protected $sessionBackend;
340
341 /**
342 * Holds deserialized data from session records.
343 * 'Reserved' keys are:
344 * - 'sys': Reserved for TypoScript standard code.
345 * @var array
346 */
347 protected $sessionData = [];
348
349 /**
350 * Initialize some important variables
351 */
352 public function __construct()
353 {
354 // This function has to stay even if it's empty
355 // Implementations of that abstract class might call parent::__construct();
356 }
357
358 /**
359 * Starts a user session
360 * Typical configurations will:
361 * a) check if session cookie was set and if not, set one,
362 * b) check if a password/username was sent and if so, try to authenticate the user
363 * c) Lookup a session attached to a user and check timeout etc.
364 * d) Garbage collection, setting of no-cache headers.
365 * If a user is authenticated the database record of the user (array) will be set in the ->user internal variable.
366 *
367 * @throws Exception
368 */
369 public function start()
370 {
371 // Backend or frontend login - used for auth services
372 if (empty($this->loginType)) {
373 throw new Exception('No loginType defined, should be set explicitly by subclass', 1476045345);
374 }
375 $this->logger->debug('## Beginning of auth logging.');
376 // Init vars.
377 $mode = '';
378 $this->newSessionID = false;
379 // $id is set to ses_id if cookie is present. Else set to FALSE, which will start a new session
380 $id = $this->getCookie($this->name);
381 $this->svConfig = $GLOBALS['TYPO3_CONF_VARS']['SVCONF']['auth'] ?? [];
382
383 // If fallback to get mode....
384 if (!$id && $this->getFallBack && $this->get_name) {
385 $id = isset($_GET[$this->get_name]) ? GeneralUtility::_GET($this->get_name) : '';
386 if (strlen($id) != $this->hash_length) {
387 $id = '';
388 }
389 $mode = 'get';
390 }
391
392 // If new session or client tries to fix session...
393 if (!$id || !$this->isExistingSessionRecord($id)) {
394 // New random session-$id is made
395 $id = $this->createSessionId();
396 // New session
397 $this->newSessionID = true;
398 }
399 // Internal var 'id' is set
400 $this->id = $id;
401 // If fallback to get mode....
402 if ($mode === 'get' && $this->getFallBack && $this->get_name) {
403 $this->get_URL_ID = '&' . $this->get_name . '=' . $id;
404 }
405 // Make certain that NO user is set initially
406 $this->user = null;
407 // Set all possible headers that could ensure that the script is not cached on the client-side
408 if ($this->sendNoCacheHeaders && !Environment::isCli()) {
409 header('Expires: 0');
410 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
411 $cacheControlHeader = 'no-cache, must-revalidate';
412 $pragmaHeader = 'no-cache';
413 // Prevent error message in IE when using a https connection
414 // see http://forge.typo3.org/issues/24125
415 $clientInfo = GeneralUtility::clientInfo();
416 if ($clientInfo['BROWSER'] === 'msie' && GeneralUtility::getIndpEnv('TYPO3_SSL')) {
417 // Some IEs can not handle no-cache
418 // see http://support.microsoft.com/kb/323308/en-us
419 $cacheControlHeader = 'must-revalidate';
420 // IE needs "Pragma: private" if SSL connection
421 $pragmaHeader = 'private';
422 }
423 header('Cache-Control: ' . $cacheControlHeader);
424 header('Pragma: ' . $pragmaHeader);
425 }
426 // Load user session, check to see if anyone has submitted login-information and if so authenticate
427 // the user with the session. $this->user[uid] may be used to write log...
428 $this->checkAuthentication();
429 // Setting cookies
430 if (!$this->dontSetCookie) {
431 $this->setSessionCookie();
432 }
433 // Hook for alternative ways of filling the $this->user array (is used by the "timtaw" extension)
434 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'] ?? [] as $funcName) {
435 $_params = [
436 'pObj' => $this,
437 ];
438 GeneralUtility::callUserFunction($funcName, $_params, $this);
439 }
440 // Set $this->gc_time if not explicitly specified
441 if ($this->gc_time === 0) {
442 // Default to 86400 seconds (1 day) if $this->sessionTimeout is 0
443 $this->gc_time = $this->sessionTimeout === 0 ? 86400 : $this->sessionTimeout;
444 }
445 // If we're lucky we'll get to clean up old sessions
446 if (rand() % 100 <= $this->gc_probability) {
447 $this->gc();
448 }
449 }
450
451 /**
452 * Sets the session cookie for the current disposal.
453 *
454 * @throws Exception
455 */
456 protected function setSessionCookie()
457 {
458 $isSetSessionCookie = $this->isSetSessionCookie();
459 $isRefreshTimeBasedCookie = $this->isRefreshTimeBasedCookie();
460 if ($isSetSessionCookie || $isRefreshTimeBasedCookie) {
461 $settings = $GLOBALS['TYPO3_CONF_VARS']['SYS'];
462 // Get the domain to be used for the cookie (if any):
463 $cookieDomain = $this->getCookieDomain();
464 // If no cookie domain is set, use the base path:
465 $cookiePath = $cookieDomain ? '/' : GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
466 // If the cookie lifetime is set, use it:
467 $cookieExpire = $isRefreshTimeBasedCookie ? $GLOBALS['EXEC_TIME'] + $this->lifetime : 0;
468 // Use the secure option when the current request is served by a secure connection:
469 $cookieSecure = (bool)$settings['cookieSecure'] && GeneralUtility::getIndpEnv('TYPO3_SSL');
470 // Do not set cookie if cookieSecure is set to "1" (force HTTPS) and no secure channel is used:
471 if ((int)$settings['cookieSecure'] !== 1 || GeneralUtility::getIndpEnv('TYPO3_SSL')) {
472 setcookie($this->name, $this->id, $cookieExpire, $cookiePath, $cookieDomain, $cookieSecure, true);
473 $this->cookieWasSetOnCurrentRequest = true;
474 } else {
475 throw new Exception('Cookie was not set since HTTPS was forced in $TYPO3_CONF_VARS[SYS][cookieSecure].', 1254325546);
476 }
477 $this->logger->debug(
478 ($isRefreshTimeBasedCookie ? 'Updated Cookie: ' : 'Set Cookie: ')
479 . $this->id . ($cookieDomain ? ', ' . $cookieDomain : '')
480 );
481 }
482 }
483
484 /**
485 * Gets the domain to be used on setting cookies.
486 * The information is taken from the value in $GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieDomain'].
487 *
488 * @return string The domain to be used on setting cookies
489 */
490 protected function getCookieDomain()
491 {
492 $result = '';
493 $cookieDomain = $GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieDomain'];
494 // If a specific cookie domain is defined for a given TYPO3_MODE,
495 // use that domain
496 if (!empty($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['cookieDomain'])) {
497 $cookieDomain = $GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['cookieDomain'];
498 }
499 if ($cookieDomain) {
500 if ($cookieDomain[0] === '/') {
501 $match = [];
502 $matchCnt = @preg_match($cookieDomain, GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'), $match);
503 if ($matchCnt === false) {
504 $this->logger->critical('The regular expression for the cookie domain (' . $cookieDomain . ') contains errors. The session is not shared across sub-domains.');
505 } elseif ($matchCnt) {
506 $result = $match[0];
507 }
508 } else {
509 $result = $cookieDomain;
510 }
511 }
512 return $result;
513 }
514
515 /**
516 * Get the value of a specified cookie.
517 *
518 * @param string $cookieName The cookie ID
519 * @return string The value stored in the cookie
520 */
521 protected function getCookie($cookieName)
522 {
523 return isset($_COOKIE[$cookieName]) ? stripslashes($_COOKIE[$cookieName]) : '';
524 }
525
526 /**
527 * Determine whether a session cookie needs to be set (lifetime=0)
528 *
529 * @return bool
530 * @internal
531 */
532 public function isSetSessionCookie()
533 {
534 return ($this->newSessionID || $this->forceSetCookie) && $this->lifetime == 0;
535 }
536
537 /**
538 * Determine whether a non-session cookie needs to be set (lifetime>0)
539 *
540 * @return bool
541 * @internal
542 */
543 public function isRefreshTimeBasedCookie()
544 {
545 return $this->lifetime > 0;
546 }
547
548 /**
549 * Checks if a submission of username and password is present or use other authentication by auth services
550 *
551 * @throws \RuntimeException
552 * @internal
553 */
554 public function checkAuthentication()
555 {
556 // No user for now - will be searched by service below
557 $tempuserArr = [];
558 $tempuser = false;
559 // User is not authenticated by default
560 $authenticated = false;
561 // User want to login with passed login data (name/password)
562 $activeLogin = false;
563 // Indicates if an active authentication failed (not auto login)
564 $this->loginFailure = false;
565 $this->logger->debug('Login type: ' . $this->loginType);
566 // The info array provide additional information for auth services
567 $authInfo = $this->getAuthInfoArray();
568 // Get Login/Logout data submitted by a form or params
569 $loginData = $this->getLoginFormData();
570 $this->logger->debug('Login data', $loginData);
571 // Active logout (eg. with "logout" button)
572 if ($loginData['status'] === LoginType::LOGOUT) {
573 if ($this->writeStdLog) {
574 // $type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid
575 $this->writelog(255, 2, 0, 2, 'User %s logged out', [$this->user['username']], '', 0, 0);
576 }
577 $this->logger->info('User logged out. Id: ' . $this->id);
578 $this->logoff();
579 }
580 // Determine whether we need to skip session update.
581 // This is used mainly for checking session timeout in advance without refreshing the current session's timeout.
582 $skipSessionUpdate = (bool)GeneralUtility::_GP('skipSessionUpdate');
583 $haveSession = false;
584 $anonymousSession = false;
585 if (!$this->newSessionID) {
586 // Read user session
587 $authInfo['userSession'] = $this->fetchUserSession($skipSessionUpdate);
588 $haveSession = is_array($authInfo['userSession']);
589 if ($haveSession && !empty($authInfo['userSession']['ses_anonymous'])) {
590 $anonymousSession = true;
591 }
592 }
593
594 // Active login (eg. with login form).
595 if (!$haveSession && $loginData['status'] === LoginType::LOGIN) {
596 $activeLogin = true;
597 $this->logger->debug('Active login (eg. with login form)');
598 // check referrer for submitted login values
599 if ($this->formfield_status && $loginData['uident'] && $loginData['uname']) {
600 // Delete old user session if any
601 $this->logoff();
602 }
603 // Refuse login for _CLI users, if not processing a CLI request type
604 // (although we shouldn't be here in case of a CLI request type)
605 if (strtoupper(substr($loginData['uname'], 0, 5)) === '_CLI_' && !Environment::isCli()) {
606 throw new \RuntimeException('TYPO3 Fatal Error: You have tried to login using a CLI user. Access prohibited!', 1270853931);
607 }
608 }
609
610 // Cause elevation of privilege, make sure regenerateSessionId is called later on
611 if ($anonymousSession && $loginData['status'] === LoginType::LOGIN) {
612 $activeLogin = true;
613 }
614
615 if ($haveSession) {
616 $this->logger->debug('User session found', [
617 $this->userid_column => $authInfo['userSession'][$this->userid_column] ?? null,
618 $this->username_column => $authInfo['userSession'][$this->username_column] ?? null,
619 ]);
620 } else {
621 $this->logger->debug('No user session found');
622 }
623 if (is_array($this->svConfig['setup'] ?? false)) {
624 $this->logger->debug('SV setup', $this->svConfig['setup']);
625 }
626
627 // Fetch user if ...
628 if (
629 $activeLogin || !empty($this->svConfig['setup'][$this->loginType . '_alwaysFetchUser'])
630 || !$haveSession && !empty($this->svConfig['setup'][$this->loginType . '_fetchUserIfNoSession'])
631 ) {
632 // Use 'auth' service to find the user
633 // First found user will be used
634 $subType = 'getUser' . $this->loginType;
635 foreach ($this->getAuthServices($subType, $loginData, $authInfo) as $serviceObj) {
636 if ($row = $serviceObj->getUser()) {
637 $tempuserArr[] = $row;
638 $this->logger->debug('User found', [
639 $this->userid_column => $row[$this->userid_column],
640 $this->username_column => $row[$this->username_column],
641 ]);
642 // User found, just stop to search for more if not configured to go on
643 if (empty($this->svConfig['setup'][$this->loginType . '_fetchAllUsers'])) {
644 break;
645 }
646 }
647 }
648
649 if (!empty($this->svConfig['setup'][$this->loginType . '_alwaysFetchUser'])) {
650 $this->logger->debug($this->loginType . '_alwaysFetchUser option is enabled');
651 }
652 if (empty($tempuserArr)) {
653 $this->logger->debug('No user found by services');
654 } else {
655 $this->logger->debug(count($tempuserArr) . ' user records found by services');
656 }
657 }
658
659 // If no new user was set we use the already found user session
660 if (empty($tempuserArr) && $haveSession && !$anonymousSession) {
661 $tempuserArr[] = $authInfo['userSession'];
662 $tempuser = $authInfo['userSession'];
663 // User is authenticated because we found a user session
664 $authenticated = true;
665 $this->logger->debug('User session used', [
666 $this->userid_column => $authInfo['userSession'][$this->userid_column],
667 $this->username_column => $authInfo['userSession'][$this->username_column],
668 ]);
669 }
670 // Re-auth user when 'auth'-service option is set
671 if (!empty($this->svConfig['setup'][$this->loginType . '_alwaysAuthUser'])) {
672 $authenticated = false;
673 $this->logger->debug('alwaysAuthUser option is enabled');
674 }
675 // Authenticate the user if needed
676 if (!empty($tempuserArr) && !$authenticated) {
677 foreach ($tempuserArr as $tempuser) {
678 // Use 'auth' service to authenticate the user
679 // If one service returns FALSE then authentication failed
680 // a service might return 100 which means there's no reason to stop but the user can't be authenticated by that service
681 $this->logger->debug('Auth user', $tempuser);
682 $subType = 'authUser' . $this->loginType;
683
684 foreach ($this->getAuthServices($subType, $loginData, $authInfo) as $serviceObj) {
685 if (($ret = $serviceObj->authUser($tempuser)) > 0) {
686 // If the service returns >=200 then no more checking is needed - useful for IP checking without password
687 if ((int)$ret >= 200) {
688 $authenticated = true;
689 break;
690 }
691 if ((int)$ret >= 100) {
692 } else {
693 $authenticated = true;
694 }
695 } else {
696 $authenticated = false;
697 break;
698 }
699 }
700
701 if ($authenticated) {
702 // Leave foreach() because a user is authenticated
703 break;
704 }
705 }
706 }
707
708 // If user is authenticated a valid user is in $tempuser
709 if ($authenticated) {
710 // Reset failure flag
711 $this->loginFailure = false;
712 // Insert session record if needed:
713 if (!$haveSession || $anonymousSession || $tempuser['ses_id'] != $this->id && $tempuser['uid'] != $authInfo['userSession']['ses_userid']) {
714 $sessionData = $this->createUserSession($tempuser);
715
716 // Preserve session data on login
717 if ($anonymousSession) {
718 $sessionData = $this->getSessionBackend()->update(
719 $this->id,
720 ['ses_data' => $authInfo['userSession']['ses_data']]
721 );
722 }
723
724 $this->user = array_merge(
725 $tempuser,
726 $sessionData
727 );
728 // The login session is started.
729 $this->loginSessionStarted = true;
730 if (is_array($this->user)) {
731 $this->logger->debug('User session finally read', [
732 $this->userid_column => $this->user[$this->userid_column],
733 $this->username_column => $this->user[$this->username_column],
734 ]);
735 }
736 } elseif ($haveSession) {
737 // if we come here the current session is for sure not anonymous as this is a pre-condition for $authenticated = true
738 $this->user = $authInfo['userSession'];
739 }
740
741 if ($activeLogin && !$this->newSessionID) {
742 $this->regenerateSessionId();
743 }
744
745 // User logged in - write that to the log!
746 if ($this->writeStdLog && $activeLogin) {
747 $this->writelog(255, 1, 0, 1, 'User %s logged in from ###IP### (%s)', [$tempuser[$this->username_column], GeneralUtility::getIndpEnv('REMOTE_HOST')], '', '', '');
748 }
749 if ($activeLogin) {
750 $this->logger->info('User ' . $tempuser[$this->username_column] . ' logged in from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR') . ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')');
751 }
752 if (!$activeLogin) {
753 $this->logger->debug('User ' . $tempuser[$this->username_column] . ' authenticated from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR') . ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')');
754 }
755 } else {
756 // User was not authenticated, so we should reuse the existing anonymous session
757 if ($anonymousSession) {
758 $this->user = $authInfo['userSession'];
759 }
760
761 // Mark the current login attempt as failed
762 if ($activeLogin || !empty($tempuserArr)) {
763 $this->loginFailure = true;
764 if (empty($tempuserArr) && $activeLogin) {
765 $logData = [
766 'loginData' => $loginData
767 ];
768 $this->logger->warning('Login failed', $logData);
769 }
770 if (!empty($tempuserArr)) {
771 $logData = [
772 $this->userid_column => $tempuser[$this->userid_column],
773 $this->username_column => $tempuser[$this->username_column],
774 ];
775 $this->logger->warning('Login failed', $logData);
776 }
777 }
778 }
779
780 // If there were a login failure, check to see if a warning email should be sent:
781 if ($this->loginFailure && $activeLogin) {
782 $this->logger->debug(
783 'Call checkLogFailures',
784 [
785 'warningEmail' => $this->warningEmail,
786 'warningPeriod' => $this->warningPeriod,
787 'warningMax' => $this->warningMax
788 ]
789 );
790
791 // Hook to implement login failure tracking methods
792 $_params = [];
793 $sleep = true;
794 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postLoginFailureProcessing'] ?? [] as $_funcRef) {
795 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
796 $sleep = false;
797 }
798
799 if ($sleep) {
800 // No hooks were triggered - default login failure behavior is to sleep 5 seconds
801 sleep(5);
802 }
803
804 $this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax);
805 }
806 }
807
808 /**
809 * Creates a new session ID.
810 *
811 * @return string The new session ID
812 */
813 public function createSessionId()
814 {
815 return GeneralUtility::makeInstance(Random::class)->generateRandomHexString($this->hash_length);
816 }
817
818 /**
819 * Initializes authentication services to be used in a foreach loop
820 *
821 * @param string $subType e.g. getUserFE
822 * @param array $loginData
823 * @param array $authInfo
824 * @return \Traversable A generator of service objects
825 */
826 protected function getAuthServices(string $subType, array $loginData, array $authInfo): \Traversable
827 {
828 $serviceChain = '';
829 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
830 $serviceChain .= ',' . $serviceObj->getServiceKey();
831 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
832 yield $serviceObj;
833 }
834 if ($serviceChain) {
835 $this->logger->debug($subType . ' auth services called: ' . $serviceChain);
836 }
837 }
838
839 /**
840 * Regenerate the session ID and transfer the session to new ID
841 * Call this method whenever a user proceeds to a higher authorization level
842 * e.g. when an anonymous session is now authenticated.
843 *
844 * @param array $existingSessionRecord If given, this session record will be used instead of fetching again
845 * @param bool $anonymous If true session will be regenerated as anonymous session
846 */
847 protected function regenerateSessionId(array $existingSessionRecord = [], bool $anonymous = false)
848 {
849 if (empty($existingSessionRecord)) {
850 $existingSessionRecord = $this->getSessionBackend()->get($this->id);
851 }
852
853 // Update session record with new ID
854 $oldSessionId = $this->id;
855 $this->id = $this->createSessionId();
856 $updatedSession = $this->getSessionBackend()->set($this->id, $existingSessionRecord);
857 $this->sessionData = unserialize($updatedSession['ses_data']);
858 // Merge new session data into user/session array
859 $this->user = array_merge($this->user ?? [], $updatedSession);
860 $this->getSessionBackend()->remove($oldSessionId);
861 $this->newSessionID = true;
862 }
863
864 /*************************
865 *
866 * User Sessions
867 *
868 *************************/
869
870 /**
871 * Creates a user session record and returns its values.
872 *
873 * @param array $tempuser User data array
874 *
875 * @return array The session data for the newly created session.
876 */
877 public function createUserSession($tempuser)
878 {
879 $this->logger->debug('Create session ses_id = ' . $this->id);
880 // Delete any session entry first
881 $this->getSessionBackend()->remove($this->id);
882 // Re-create session entry
883 $sessionRecord = $this->getNewSessionRecord($tempuser);
884 $sessionRecord = $this->getSessionBackend()->set($this->id, $sessionRecord);
885 // Updating lastLogin_column carrying information about last login.
886 $this->updateLoginTimestamp($tempuser[$this->userid_column]);
887 return $sessionRecord;
888 }
889
890 /**
891 * Updates the last login column in the user with the given id
892 *
893 * @param int $userId
894 */
895 protected function updateLoginTimestamp(int $userId)
896 {
897 if ($this->lastLogin_column) {
898 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->user_table);
899 $connection->update(
900 $this->user_table,
901 [$this->lastLogin_column => $GLOBALS['EXEC_TIME']],
902 [$this->userid_column => $userId]
903 );
904 }
905 }
906
907 /**
908 * Returns a new session record for the current user for insertion into the DB.
909 * This function is mainly there as a wrapper for inheriting classes to override it.
910 *
911 * @param array $tempuser
912 * @return array User session record
913 */
914 public function getNewSessionRecord($tempuser)
915 {
916 $sessionIpLock = '[DISABLED]';
917 if ($this->lockIP && empty($tempuser['disableIPlock'])) {
918 $sessionIpLock = $this->ipLockClause_remoteIPNumber($this->lockIP);
919 }
920
921 return [
922 'ses_id' => $this->id,
923 'ses_iplock' => $sessionIpLock,
924 'ses_userid' => $tempuser[$this->userid_column] ?? 0,
925 'ses_tstamp' => $GLOBALS['EXEC_TIME'],
926 'ses_data' => '',
927 ];
928 }
929
930 /**
931 * Read the user session from db.
932 *
933 * @param bool $skipSessionUpdate
934 * @return array|bool User session data, false if $this->id does not represent valid session
935 */
936 public function fetchUserSession($skipSessionUpdate = false)
937 {
938 $this->logger->debug('Fetch session ses_id = ' . $this->id);
939 try {
940 $sessionRecord = $this->getSessionBackend()->get($this->id);
941 } catch (SessionNotFoundException $e) {
942 return false;
943 }
944
945 $this->sessionData = unserialize($sessionRecord['ses_data']);
946 // Session is anonymous so no need to fetch user
947 if (!empty($sessionRecord['ses_anonymous'])) {
948 return $sessionRecord;
949 }
950
951 // Fetch the user from the DB
952 $userRecord = $this->getRawUserByUid((int)$sessionRecord['ses_userid']);
953 if ($userRecord) {
954 $userRecord = array_merge($sessionRecord, $userRecord);
955 // A user was found
956 $userRecord['ses_tstamp'] = (int)$userRecord['ses_tstamp'];
957 $userRecord['is_online'] = (int)$userRecord['ses_tstamp'];
958
959 if (!empty($this->auth_timeout_field)) {
960 // Get timeout-time from usertable
961 $timeout = (int)$userRecord[$this->auth_timeout_field];
962 } else {
963 $timeout = $this->sessionTimeout;
964 }
965 // If timeout > 0 (TRUE) and current time has not exceeded the latest sessions-time plus the timeout in seconds then accept user
966 // Use a gracetime-value to avoid updating a session-record too often
967 if ($timeout > 0 && $GLOBALS['EXEC_TIME'] < $userRecord['ses_tstamp'] + $timeout) {
968 $sessionUpdateGracePeriod = 61;
969 if (!$skipSessionUpdate && $GLOBALS['EXEC_TIME'] > ($userRecord['ses_tstamp'] + $sessionUpdateGracePeriod)) {
970 // Update the session timestamp by writing a dummy update. (Backend will update the timestamp)
971 $updatesSession = $this->getSessionBackend()->update($this->id, []);
972 $userRecord = array_merge($userRecord, $updatesSession);
973 }
974 } else {
975 // Delete any user set...
976 $this->logoff();
977 $userRecord = false;
978 }
979 }
980 return $userRecord;
981 }
982
983 /**
984 * Log out current user!
985 * Removes the current session record, sets the internal ->user array to a blank string;
986 * Thereby the current user (if any) is effectively logged out!
987 */
988 public function logoff()
989 {
990 $this->logger->debug('logoff: ses_id = ' . $this->id);
991 // Release the locked records
992 BackendUtility::lockRecords();
993
994 $_params = [];
995 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'] ?? [] as $_funcRef) {
996 if ($_funcRef) {
997 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
998 }
999 }
1000 $this->performLogoff();
1001
1002 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'] ?? [] as $_funcRef) {
1003 if ($_funcRef) {
1004 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1005 }
1006 }
1007 }
1008
1009 /**
1010 * Perform the logoff action. Called from logoff() as a way to allow subclasses to override
1011 * what happens when a user logs off, without needing to reproduce the hook calls and logging
1012 * that happens in the public logoff() API method.
1013 */
1014 protected function performLogoff()
1015 {
1016 if ($this->id) {
1017 $this->getSessionBackend()->remove($this->id);
1018 }
1019 $this->user = null;
1020 }
1021
1022 /**
1023 * Empty / unset the cookie
1024 *
1025 * @param string $cookieName usually, this is $this->name
1026 */
1027 public function removeCookie($cookieName)
1028 {
1029 $cookieDomain = $this->getCookieDomain();
1030 // If no cookie domain is set, use the base path
1031 $cookiePath = $cookieDomain ? '/' : GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
1032 setcookie($cookieName, null, -1, $cookiePath, $cookieDomain);
1033 }
1034
1035 /**
1036 * Determine whether there's an according session record to a given session_id.
1037 * Don't care if session record is still valid or not.
1038 *
1039 * @param string $id Claimed Session ID
1040 * @return bool Returns TRUE if a corresponding session was found in the database
1041 */
1042 public function isExistingSessionRecord($id)
1043 {
1044 try {
1045 $sessionRecord = $this->getSessionBackend()->get($id);
1046 if (empty($sessionRecord)) {
1047 return false;
1048 }
1049 // If the session does not match the current IP lock, it should be treated as invalid
1050 // and a new session should be created.
1051 if ($sessionRecord['ses_iplock'] !== $this->ipLockClause_remoteIPNumber($this->lockIP) && $sessionRecord['ses_iplock'] !== '[DISABLED]') {
1052 return false;
1053 }
1054 return true;
1055 } catch (SessionNotFoundException $e) {
1056 return false;
1057 }
1058 }
1059
1060 /**
1061 * Returns whether this request is going to set a cookie
1062 * or a cookie was already found in the system
1063 *
1064 * @return bool Returns TRUE if a cookie is set
1065 */
1066 public function isCookieSet()
1067 {
1068 return $this->cookieWasSetOnCurrentRequest || $this->getCookie($this->name);
1069 }
1070
1071 /*************************
1072 *
1073 * SQL Functions
1074 *
1075 *************************/
1076 /**
1077 * This returns the restrictions needed to select the user respecting
1078 * enable columns and flags like deleted, hidden, starttime, endtime
1079 * and rootLevel
1080 *
1081 * @return QueryRestrictionContainerInterface
1082 * @internal
1083 */
1084 protected function userConstraints(): QueryRestrictionContainerInterface
1085 {
1086 $restrictionContainer = GeneralUtility::makeInstance(DefaultRestrictionContainer::class);
1087
1088 if (empty($this->enablecolumns['disabled'])) {
1089 $restrictionContainer->removeByType(HiddenRestriction::class);
1090 }
1091
1092 if (empty($this->enablecolumns['deleted'])) {
1093 $restrictionContainer->removeByType(DeletedRestriction::class);
1094 }
1095
1096 if (empty($this->enablecolumns['starttime'])) {
1097 $restrictionContainer->removeByType(StartTimeRestriction::class);
1098 }
1099
1100 if (empty($this->enablecolumns['endtime'])) {
1101 $restrictionContainer->removeByType(EndTimeRestriction::class);
1102 }
1103
1104 if (!empty($this->enablecolumns['rootLevel'])) {
1105 $restrictionContainer->add(GeneralUtility::makeInstance(RootLevelRestriction::class, [$this->user_table]));
1106 }
1107
1108 return $restrictionContainer;
1109 }
1110
1111 /**
1112 * Returns the IP address to lock to.
1113 * The IP address may be partial based on $parts.
1114 *
1115 * @param int $parts 1-4: Indicates how many parts of the IP address to return. 4 means all, 1 means only first number.
1116 * @return string (Partial) IP address for REMOTE_ADDR
1117 */
1118 protected function ipLockClause_remoteIPNumber($parts)
1119 {
1120 $IP = GeneralUtility::getIndpEnv('REMOTE_ADDR');
1121 if ($parts >= 4) {
1122 return $IP;
1123 }
1124 $parts = MathUtility::forceIntegerInRange($parts, 1, 3);
1125 $IPparts = explode('.', $IP);
1126 for ($a = 4; $a > $parts; $a--) {
1127 unset($IPparts[$a - 1]);
1128 }
1129 return implode('.', $IPparts);
1130 }
1131
1132 /*************************
1133 *
1134 * Session and Configuration Handling
1135 *
1136 *************************/
1137 /**
1138 * This writes $variable to the user-record. This is a way of providing session-data.
1139 * You can fetch the data again through $this->uc in this class!
1140 * If $variable is not an array, $this->uc is saved!
1141 *
1142 * @param array|string $variable An array you want to store for the user as session data. If $variable is not supplied (is null), the internal variable, ->uc, is stored by default
1143 */
1144 public function writeUC($variable = '')
1145 {
1146 if (is_array($this->user) && $this->user[$this->userid_column]) {
1147 if (!is_array($variable)) {
1148 $variable = $this->uc;
1149 }
1150 $this->logger->debug('writeUC: ' . $this->userid_column . '=' . (int)$this->user[$this->userid_column]);
1151 GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->user_table)->update(
1152 $this->user_table,
1153 ['uc' => serialize($variable)],
1154 [$this->userid_column => (int)$this->user[$this->userid_column]],
1155 ['uc' => Connection::PARAM_LOB]
1156 );
1157 }
1158 }
1159
1160 /**
1161 * Sets $theUC as the internal variable ->uc IF $theUC is an array.
1162 * If $theUC is FALSE, the 'uc' content from the ->user array will be unserialized and restored in ->uc
1163 *
1164 * @param mixed $theUC If an array, then set as ->uc, otherwise load from user record
1165 */
1166 public function unpack_uc($theUC = '')
1167 {
1168 if (!$theUC && isset($this->user['uc'])) {
1169 $theUC = unserialize($this->user['uc']);
1170 }
1171 if (is_array($theUC)) {
1172 $this->uc = $theUC;
1173 }
1174 }
1175
1176 /**
1177 * Stores data for a module.
1178 * The data is stored with the session id so you can even check upon retrieval
1179 * if the module data is from a previous session or from the current session.
1180 *
1181 * @param string $module Is the name of the module ($MCONF['name'])
1182 * @param mixed $data Is the data you want to store for that module (array, string, ...)
1183 * @param bool|int $noSave If $noSave is set, then the ->uc array (which carries all kinds of user data) is NOT written immediately, but must be written by some subsequent call.
1184 */
1185 public function pushModuleData($module, $data, $noSave = 0)
1186 {
1187 $this->uc['moduleData'][$module] = $data;
1188 $this->uc['moduleSessionID'][$module] = $this->id;
1189 if (!$noSave) {
1190 $this->writeUC();
1191 }
1192 }
1193
1194 /**
1195 * Gets module data for a module (from a loaded ->uc array)
1196 *
1197 * @param string $module Is the name of the module ($MCONF['name'])
1198 * @param string $type If $type = 'ses' then module data is returned only if it was stored in the current session, otherwise data from a previous session will be returned (if available).
1199 * @return mixed The module data if available: $this->uc['moduleData'][$module];
1200 */
1201 public function getModuleData($module, $type = '')
1202 {
1203 if ($type !== 'ses' || (isset($this->uc['moduleSessionID'][$module]) && $this->uc['moduleSessionID'][$module] == $this->id)) {
1204 return $this->uc['moduleData'][$module];
1205 }
1206 return null;
1207 }
1208
1209 /**
1210 * Returns the session data stored for $key.
1211 * The data will last only for this login session since it is stored in the user session.
1212 *
1213 * @param string $key The key associated with the session data
1214 * @return mixed
1215 */
1216 public function getSessionData($key)
1217 {
1218 return $this->sessionData[$key] ?? null;
1219 }
1220
1221 /**
1222 * Set session data by key.
1223 * The data will last only for this login session since it is stored in the user session.
1224 *
1225 * @param string $key A non empty string to store the data under
1226 * @param mixed $data Data store store in session
1227 */
1228 public function setSessionData($key, $data)
1229 {
1230 if (empty($key)) {
1231 throw new \InvalidArgumentException('Argument key must not be empty', 1484311516);
1232 }
1233 $this->sessionData[$key] = $data;
1234 }
1235
1236 /**
1237 * Sets the session data ($data) for $key and writes all session data (from ->user['ses_data']) to the database.
1238 * The data will last only for this login session since it is stored in the session table.
1239 *
1240 * @param string $key Pointer to an associative key in the session data array which is stored serialized in the field "ses_data" of the session table.
1241 * @param mixed $data The data to store in index $key
1242 */
1243 public function setAndSaveSessionData($key, $data)
1244 {
1245 $this->sessionData[$key] = $data;
1246 $this->user['ses_data'] = serialize($this->sessionData);
1247 $this->logger->debug('setAndSaveSessionData: ses_id = ' . $this->id);
1248 $updatedSession = $this->getSessionBackend()->update(
1249 $this->id,
1250 ['ses_data' => $this->user['ses_data']]
1251 );
1252 $this->user = array_merge($this->user ?? [], $updatedSession);
1253 }
1254
1255 /*************************
1256 *
1257 * Misc
1258 *
1259 *************************/
1260 /**
1261 * Returns an info array with Login/Logout data submitted by a form or params
1262 *
1263 * @return array
1264 * @internal
1265 */
1266 public function getLoginFormData()
1267 {
1268 $loginData = [];
1269 $loginData['status'] = GeneralUtility::_GP($this->formfield_status);
1270 if ($this->getMethodEnabled) {
1271 $loginData['uname'] = GeneralUtility::_GP($this->formfield_uname);
1272 $loginData['uident'] = GeneralUtility::_GP($this->formfield_uident);
1273 } else {
1274 $loginData['uname'] = GeneralUtility::_POST($this->formfield_uname);
1275 $loginData['uident'] = GeneralUtility::_POST($this->formfield_uident);
1276 }
1277 // Only process the login data if a login is requested
1278 if ($loginData['status'] === LoginType::LOGIN) {
1279 $loginData = $this->processLoginData($loginData);
1280 }
1281 $loginData = array_map('trim', $loginData);
1282 return $loginData;
1283 }
1284
1285 /**
1286 * Processes Login data submitted by a form or params depending on the
1287 * passwordTransmissionStrategy
1288 *
1289 * @param array $loginData Login data array
1290 * @param string $passwordTransmissionStrategy Alternative passwordTransmissionStrategy. Used when authentication services wants to override the default.
1291 * @return array
1292 * @internal
1293 */
1294 public function processLoginData($loginData, $passwordTransmissionStrategy = '')
1295 {
1296 $loginSecurityLevel = trim($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['loginSecurityLevel']) ?: 'normal';
1297 $passwordTransmissionStrategy = $passwordTransmissionStrategy ?: $loginSecurityLevel;
1298 $this->logger->debug('Login data before processing', $loginData);
1299 $serviceChain = '';
1300 $subType = 'processLoginData' . $this->loginType;
1301 $authInfo = $this->getAuthInfoArray();
1302 $isLoginDataProcessed = false;
1303 $processedLoginData = $loginData;
1304 while (is_object($serviceObject = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
1305 $serviceChain .= ',' . $serviceObject->getServiceKey();
1306 $serviceObject->initAuth($subType, $loginData, $authInfo, $this);
1307 $serviceResult = $serviceObject->processLoginData($processedLoginData, $passwordTransmissionStrategy);
1308 if (!empty($serviceResult)) {
1309 $isLoginDataProcessed = true;
1310 // If the service returns >=200 then no more processing is needed
1311 if ((int)$serviceResult >= 200) {
1312 unset($serviceObject);
1313 break;
1314 }
1315 }
1316 unset($serviceObject);
1317 }
1318 if ($isLoginDataProcessed) {
1319 $loginData = $processedLoginData;
1320 $this->logger->debug('Processed login data', $processedLoginData);
1321 }
1322 return $loginData;
1323 }
1324
1325 /**
1326 * Returns an info array which provides additional information for auth services
1327 *
1328 * @return array
1329 * @internal
1330 */
1331 public function getAuthInfoArray()
1332 {
1333 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->user_table);
1334 $expressionBuilder = $queryBuilder->expr();
1335 $authInfo = [];
1336 $authInfo['loginType'] = $this->loginType;
1337 $authInfo['refInfo'] = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
1338 $authInfo['HTTP_HOST'] = GeneralUtility::getIndpEnv('HTTP_HOST');
1339 $authInfo['REMOTE_ADDR'] = GeneralUtility::getIndpEnv('REMOTE_ADDR');
1340 $authInfo['REMOTE_HOST'] = GeneralUtility::getIndpEnv('REMOTE_HOST');
1341 $authInfo['showHiddenRecords'] = $this->showHiddenRecords;
1342 // Can be overidden in localconf by SVCONF:
1343 $authInfo['db_user']['table'] = $this->user_table;
1344 $authInfo['db_user']['userid_column'] = $this->userid_column;
1345 $authInfo['db_user']['username_column'] = $this->username_column;
1346 $authInfo['db_user']['userident_column'] = $this->userident_column;
1347 $authInfo['db_user']['usergroup_column'] = $this->usergroup_column;
1348 $authInfo['db_user']['enable_clause'] = $this->userConstraints()->buildExpression(
1349 [$this->user_table => $this->user_table],
1350 $expressionBuilder
1351 );
1352 if ($this->checkPid && $this->checkPid_value !== null) {
1353 $authInfo['db_user']['checkPidList'] = $this->checkPid_value;
1354 $authInfo['db_user']['check_pid_clause'] = $expressionBuilder->in(
1355 'pid',
1356 GeneralUtility::intExplode(',', $this->checkPid_value)
1357 );
1358 } else {
1359 $authInfo['db_user']['checkPidList'] = '';
1360 $authInfo['db_user']['check_pid_clause'] = '';
1361 }
1362 $authInfo['db_groups']['table'] = $this->usergroup_table;
1363 return $authInfo;
1364 }
1365
1366 /**
1367 * Check the login data with the user record data for builtin login methods
1368 *
1369 * @param array $user User data array
1370 * @param array $loginData Login data array
1371 * @param string $passwordCompareStrategy Alternative passwordCompareStrategy. Used when authentication services wants to override the default.
1372 * @return bool TRUE if login data matched
1373 */
1374 public function compareUident($user, $loginData, $passwordCompareStrategy = '')
1375 {
1376 return (string)$loginData['uident_text'] !== '' && (string)$loginData['uident_text'] === (string)$user[$this->userident_column];
1377 }
1378
1379 /**
1380 * Garbage collector, removing old expired sessions.
1381 *
1382 * @internal
1383 */
1384 public function gc()
1385 {
1386 $this->getSessionBackend()->collectGarbage($this->gc_time);
1387 }
1388
1389 /**
1390 * DUMMY: Writes to log database table (in some extension classes)
1391 *
1392 * @param int $type denotes which module that has submitted the entry. This is the current list: 1=tce_db; 2=tce_file; 3=system (eg. sys_history save); 4=modules; 254=Personal settings changed; 255=login / out action: 1=login, 2=logout, 3=failed login (+ errorcode 3), 4=failure_warning_email sent
1393 * @param int $action denotes which specific operation that wrote the entry (eg. 'delete', 'upload', 'update' and so on...). Specific for each $type. Also used to trigger update of the interface. (see the log-module for the meaning of each number !!)
1394 * @param int $error flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1395 * @param int $details_nr The message number. Specific for each $type and $action. in the future this will make it possible to translate errormessages to other languages
1396 * @param string $details Default text that follows the message
1397 * @param array $data Data that follows the log. Might be used to carry special information. If an array the first 5 entries (0-4) will be sprintf'ed the details-text...
1398 * @param string $tablename Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1399 * @param int $recuid Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1400 * @param int $recpid Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1401 */
1402 public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename, $recuid, $recpid)
1403 {
1404 }
1405
1406 /**
1407 * DUMMY: Check login failures (in some extension classes)
1408 *
1409 * @param string $email Email address
1410 * @param int $secondsBack Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance
1411 * @param int $maxFailures Max allowed failures before a warning mail is sent
1412 * @ignore
1413 */
1414 public function checkLogFailures($email, $secondsBack, $maxFailures)
1415 {
1416 }
1417
1418 /**
1419 * Raw initialization of the be_user with uid=$uid
1420 * This will circumvent all login procedures and select a be_users record from the
1421 * database and set the content of ->user to the record selected.
1422 * Thus the BE_USER object will appear like if a user was authenticated - however without
1423 * a session id and the fields from the session table of course.
1424 * Will check the users for disabled, start/endtime, etc. ($this->user_where_clause())
1425 *
1426 * @param int $uid The UID of the backend user to set in ->user
1427 * @internal
1428 * @see SC_mod_tools_be_user_index::compareUsers(), \TYPO3\CMS\Setup\Controller\SetupModuleController::simulateUser(), freesite_admin::startCreate()
1429 */
1430 public function setBeUserByUid($uid)
1431 {
1432 $this->user = $this->getRawUserByUid($uid);
1433 }
1434
1435 /**
1436 * Raw initialization of the be_user with username=$name
1437 *
1438 * @param string $name The username to look up.
1439 * @see \TYPO3\CMS\Core\Authentication\AbstractUserAuthentication::setBeUserByUid()
1440 * @internal
1441 */
1442 public function setBeUserByName($name)
1443 {
1444 $this->user = $this->getRawUserByName($name);
1445 }
1446
1447 /**
1448 * Fetching raw user record with uid=$uid
1449 *
1450 * @param int $uid The UID of the backend user to set in ->user
1451 * @return array user record or FALSE
1452 * @internal
1453 */
1454 public function getRawUserByUid($uid)
1455 {
1456 $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->user_table);
1457 $query->setRestrictions($this->userConstraints());
1458 $query->select('*')
1459 ->from($this->user_table)
1460 ->where($query->expr()->eq('uid', $query->createNamedParameter($uid, \PDO::PARAM_INT)));
1461
1462 return $query->execute()->fetch();
1463 }
1464
1465 /**
1466 * Fetching raw user record with username=$name
1467 *
1468 * @param string $name The username to look up.
1469 * @return array user record or FALSE
1470 * @see \TYPO3\CMS\Core\Authentication\AbstractUserAuthentication::getUserByUid()
1471 * @internal
1472 */
1473 public function getRawUserByName($name)
1474 {
1475 $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->user_table);
1476 $query->setRestrictions($this->userConstraints());
1477 $query->select('*')
1478 ->from($this->user_table)
1479 ->where($query->expr()->eq('username', $query->createNamedParameter($name, \PDO::PARAM_STR)));
1480
1481 return $query->execute()->fetch();
1482 }
1483
1484 /**
1485 * Get a user from DB by username
1486 * provided for usage from services
1487 *
1488 * @param array $dbUser User db table definition: $this->db_user
1489 * @param string $username user name
1490 * @param string $extraWhere Additional WHERE clause: " AND ...
1491 * @return mixed User array or FALSE
1492 */
1493 public function fetchUserRecord($dbUser, $username, $extraWhere = '')
1494 {
1495 $user = false;
1496 if ($username || $extraWhere) {
1497 $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($dbUser['table']);
1498 $query->getRestrictions()->removeAll()
1499 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1500
1501 $constraints = array_filter([
1502 QueryHelper::stripLogicalOperatorPrefix($dbUser['check_pid_clause']),
1503 QueryHelper::stripLogicalOperatorPrefix($dbUser['enable_clause']),
1504 QueryHelper::stripLogicalOperatorPrefix($extraWhere),
1505 ]);
1506
1507 if (!empty($username)) {
1508 array_unshift(
1509 $constraints,
1510 $query->expr()->eq(
1511 $dbUser['username_column'],
1512 $query->createNamedParameter($username, \PDO::PARAM_STR)
1513 )
1514 );
1515 }
1516
1517 $user = $query->select('*')
1518 ->from($dbUser['table'])
1519 ->where(...$constraints)
1520 ->execute()
1521 ->fetch();
1522 }
1523
1524 return $user;
1525 }
1526
1527 /**
1528 * @internal
1529 * @return string
1530 */
1531 public function getSessionId(): string
1532 {
1533 return $this->id;
1534 }
1535
1536 /**
1537 * @internal
1538 * @return string
1539 */
1540 public function getLoginType(): string
1541 {
1542 return $this->loginType;
1543 }
1544
1545 /**
1546 * Returns initialized session backend. Returns same session backend if called multiple times
1547 *
1548 * @return SessionBackendInterface
1549 */
1550 protected function getSessionBackend()
1551 {
1552 if (!isset($this->sessionBackend)) {
1553 $this->sessionBackend = GeneralUtility::makeInstance(SessionManager::class)->getSessionBackend($this->loginType);
1554 }
1555 return $this->sessionBackend;
1556 }
1557 }