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