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