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