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