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