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