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