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