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