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