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