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