[!!!][TASK] Cleanup dual-use of auth_timeout_field in AbstractUserAuthentication
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Authentication / FrontendUserAuthentication.php
1 <?php
2 namespace TYPO3\CMS\Frontend\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\Authentication\AbstractUserAuthentication;
18 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Extension class for Front End User Authentication.
23 */
24 class FrontendUserAuthentication extends AbstractUserAuthentication
25 {
26 /**
27 * form field with 0 or 1
28 * 1 = permanent login enabled
29 * 0 = session is valid for a browser session only
30 * @var string
31 */
32 public $formfield_permanent = 'permalogin';
33
34 /**
35 * Lifetime of session data in seconds.
36 * @var int
37 */
38 protected $sessionDataLifetime = 86400;
39
40 /**
41 * if > 0 : session-timeout in seconds.
42 * if FALSE/<0 : no timeout.
43 * if string: The string is field name from the user table where the timeout can be found.
44 * @var string|int
45 */
46 public $sessionTimeout = 6000;
47
48 /**
49 * @var string
50 */
51 public $usergroup_column = 'usergroup';
52
53 /**
54 * @var string
55 */
56 public $usergroup_table = 'fe_groups';
57
58 /**
59 * @var array
60 */
61 public $groupData = array(
62 'title' => array(),
63 'uid' => array(),
64 'pid' => array()
65 );
66
67 /**
68 * Used to accumulate the TSconfig data of the user
69 * @var array
70 */
71 public $TSdataArray = array();
72
73 /**
74 * @var array
75 */
76 public $userTS = array();
77
78 /**
79 * @var bool
80 */
81 public $userTSUpdated = false;
82
83 /**
84 * Session and user data:
85 * There are two types of data that can be stored: UserData and Session-Data.
86 * Userdata is for the login-user, and session-data for anyone viewing the pages.
87 * 'Keys' are keys in the internal data array of the data.
88 * When you get or set a key in one of the data-spaces (user or session) you decide the type of the variable (not object though)
89 * 'Reserved' keys are:
90 * - 'recs': Array: Used to 'register' records, eg in a shopping basket. Structure: [recs][tablename][record_uid]=number
91 * - sys: Reserved for TypoScript standard code.
92 *
93 * @var array
94 */
95 public $sesData = array();
96
97 /**
98 * @var bool
99 */
100 public $sesData_change = false;
101
102 /**
103 * @var bool
104 */
105 public $userData_change = false;
106
107 /**
108 * @var bool
109 */
110 public $is_permanent = false;
111
112 /**
113 * @var int|NULL
114 */
115 protected $sessionDataTimestamp = null;
116
117 /**
118 * @var bool
119 */
120 protected $loginHidden = false;
121
122 /**
123 * Default constructor.
124 */
125 public function __construct()
126 {
127 parent::__construct();
128
129 // Disable cookie by default, will be activated if saveSessionData() is called,
130 // a user is logging-in or an existing session is found
131 $this->dontSetCookie = true;
132
133 $this->session_table = 'fe_sessions';
134 $this->name = self::getCookieName();
135 $this->get_name = 'ftu';
136 $this->loginType = 'FE';
137 $this->user_table = 'fe_users';
138 $this->username_column = 'username';
139 $this->userident_column = 'password';
140 $this->userid_column = 'uid';
141 $this->lastLogin_column = 'lastlogin';
142 $this->enablecolumns = array(
143 'deleted' => 'deleted',
144 'disabled' => 'disable',
145 'starttime' => 'starttime',
146 'endtime' => 'endtime'
147 );
148 $this->formfield_uname = 'user';
149 $this->formfield_uident = 'pass';
150 $this->formfield_status = 'logintype';
151 $this->sendNoCacheHeaders = false;
152 $this->getFallBack = true;
153 $this->getMethodEnabled = true;
154 }
155
156 /**
157 * Returns the configured cookie name
158 *
159 * @return string
160 */
161 public static function getCookieName()
162 {
163 $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['FE']['cookieName']);
164 if (empty($configuredCookieName)) {
165 $configuredCookieName = 'fe_typo_user';
166 }
167 return $configuredCookieName;
168 }
169
170 /**
171 * Starts a user session
172 *
173 * @return void
174 * @see AbstractUserAuthentication::start()
175 */
176 public function start()
177 {
178 if ((int)$this->sessionTimeout > 0 && $this->sessionTimeout < $this->lifetime) {
179 // If server session timeout is non-zero but less than client session timeout: Copy this value instead.
180 $this->sessionTimeout = $this->lifetime;
181 }
182 $this->sessionDataLifetime = (int)$GLOBALS['TYPO3_CONF_VARS']['FE']['sessionDataLifetime'];
183 if ($this->sessionDataLifetime <= 0) {
184 $this->sessionDataLifetime = 86400;
185 }
186 parent::start();
187 }
188
189 /**
190 * Returns a new session record for the current user for insertion into the DB.
191 *
192 * @param array $tempuser
193 * @return array User session record
194 */
195 public function getNewSessionRecord($tempuser)
196 {
197 $insertFields = parent::getNewSessionRecord($tempuser);
198 $insertFields['ses_permanent'] = $this->is_permanent ? 1 : 0;
199 return $insertFields;
200 }
201
202 /**
203 * Determine whether a session cookie needs to be set (lifetime=0)
204 *
205 * @return bool
206 * @internal
207 */
208 public function isSetSessionCookie()
209 {
210 return ($this->newSessionID || $this->forceSetCookie)
211 && ($this->lifetime == 0 || !isset($this->user['ses_permanent']) || !$this->user['ses_permanent']);
212 }
213
214 /**
215 * Determine whether a non-session cookie needs to be set (lifetime>0)
216 *
217 * @return bool
218 * @internal
219 */
220 public function isRefreshTimeBasedCookie()
221 {
222 return $this->lifetime > 0 && isset($this->user['ses_permanent']) && $this->user['ses_permanent'];
223 }
224
225 /**
226 * Returns an info array with Login/Logout data submitted by a form or params
227 *
228 * @return array
229 * @see AbstractUserAuthentication::getLoginFormData()
230 */
231 public function getLoginFormData()
232 {
233 $loginData = parent::getLoginFormData();
234 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 0 || $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 1) {
235 if ($this->getMethodEnabled) {
236 $isPermanent = GeneralUtility::_GP($this->formfield_permanent);
237 } else {
238 $isPermanent = GeneralUtility::_POST($this->formfield_permanent);
239 }
240 if (strlen($isPermanent) != 1) {
241 $isPermanent = $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'];
242 } elseif (!$isPermanent) {
243 // To make sure the user gets a session cookie and doesn't keep a possibly existing time based cookie,
244 // we need to force setting the session cookie here
245 $this->forceSetCookie = true;
246 }
247 $isPermanent = (bool)$isPermanent;
248 } elseif ($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 2) {
249 $isPermanent = true;
250 } else {
251 $isPermanent = false;
252 }
253 $loginData['permanent'] = $isPermanent;
254 $this->is_permanent = $isPermanent;
255 return $loginData;
256 }
257
258 /**
259 * Creates a user session record and returns its values.
260 * However, as the FE user cookie is normally not set, this has to be done
261 * before the parent class is doing the rest.
262 *
263 * @param array $tempuser User data array
264 * @return array The session data for the newly created session.
265 */
266 public function createUserSession($tempuser)
267 {
268 // At this point we do not know if we need to set a session or a "permanant" cookie
269 // So we force the cookie to be set after authentication took place, which will
270 // then call setSessionCookie(), which will set a cookie with correct settings.
271 $this->dontSetCookie = false;
272 return parent::createUserSession($tempuser);
273 }
274
275 /**
276 * Will select all fe_groups records that the current fe_user is member of
277 * and which groups are also allowed in the current domain.
278 * It also accumulates the TSconfig for the fe_user/fe_groups in ->TSdataArray
279 *
280 * @return int Returns the number of usergroups for the frontend users (if the internal user record exists and the usergroup field contains a value)
281 */
282 public function fetchGroupData()
283 {
284 $this->TSdataArray = array();
285 $this->userTS = array();
286 $this->userTSUpdated = false;
287 $this->groupData = array(
288 'title' => array(),
289 'uid' => array(),
290 'pid' => array()
291 );
292 // Setting default configuration:
293 $this->TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultUserTSconfig'];
294 // Get the info data for auth services
295 $authInfo = $this->getAuthInfoArray();
296 if ($this->writeDevLog) {
297 if (is_array($this->user)) {
298 GeneralUtility::devLog('Get usergroups for user: ' . GeneralUtility::arrayToLogString($this->user, array($this->userid_column, $this->username_column)), __CLASS__);
299 } else {
300 GeneralUtility::devLog('Get usergroups for "anonymous" user', __CLASS__);
301 }
302 }
303 $groupDataArr = array();
304 // Use 'auth' service to find the groups for the user
305 $serviceChain = '';
306 $subType = 'getGroups' . $this->loginType;
307 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
308 $serviceChain .= ',' . $serviceObj->getServiceKey();
309 $serviceObj->initAuth($subType, array(), $authInfo, $this);
310 $groupData = $serviceObj->getGroups($this->user, $groupDataArr);
311 if (is_array($groupData) && !empty($groupData)) {
312 // Keys in $groupData should be unique ids of the groups (like "uid") so this function will override groups.
313 $groupDataArr = $groupData + $groupDataArr;
314 }
315 unset($serviceObj);
316 }
317 if ($this->writeDevLog && $serviceChain) {
318 GeneralUtility::devLog($subType . ' auth services called: ' . $serviceChain, __CLASS__);
319 }
320 if ($this->writeDevLog && empty($groupDataArr)) {
321 GeneralUtility::devLog('No usergroups found by services', __CLASS__);
322 }
323 if ($this->writeDevLog && !empty($groupDataArr)) {
324 GeneralUtility::devLog(count($groupDataArr) . ' usergroup records found by services', __CLASS__);
325 }
326 // Use 'auth' service to check the usergroups if they are really valid
327 foreach ($groupDataArr as $groupData) {
328 // By default a group is valid
329 $validGroup = true;
330 $serviceChain = '';
331 $subType = 'authGroups' . $this->loginType;
332 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
333 $serviceChain .= ',' . $serviceObj->getServiceKey();
334 $serviceObj->initAuth($subType, array(), $authInfo, $this);
335 if (!$serviceObj->authGroup($this->user, $groupData)) {
336 $validGroup = false;
337 if ($this->writeDevLog) {
338 GeneralUtility::devLog($subType . ' auth service did not auth group: ' . GeneralUtility::arrayToLogString($groupData, 'uid,title'), __CLASS__, 2);
339 }
340 break;
341 }
342 unset($serviceObj);
343 }
344 unset($serviceObj);
345 if ($validGroup && (string)$groupData['uid'] !== '') {
346 $this->groupData['title'][$groupData['uid']] = $groupData['title'];
347 $this->groupData['uid'][$groupData['uid']] = $groupData['uid'];
348 $this->groupData['pid'][$groupData['uid']] = $groupData['pid'];
349 $this->groupData['TSconfig'][$groupData['uid']] = $groupData['TSconfig'];
350 }
351 }
352 if (!empty($this->groupData) && !empty($this->groupData['TSconfig'])) {
353 // TSconfig: collect it in the order it was collected
354 foreach ($this->groupData['TSconfig'] as $TSdata) {
355 $this->TSdataArray[] = $TSdata;
356 }
357 $this->TSdataArray[] = $this->user['TSconfig'];
358 // Sort information
359 ksort($this->groupData['title']);
360 ksort($this->groupData['uid']);
361 ksort($this->groupData['pid']);
362 }
363 return !empty($this->groupData['uid']) ? count($this->groupData['uid']) : 0;
364 }
365
366 /**
367 * Returns the parsed TSconfig for the fe_user
368 * The TSconfig will be cached in $this->userTS.
369 *
370 * @return array TSconfig array for the fe_user
371 */
372 public function getUserTSconf()
373 {
374 if (!$this->userTSUpdated) {
375 // Parsing the user TS (or getting from cache)
376 $this->TSdataArray = TypoScriptParser::checkIncludeLines_array($this->TSdataArray);
377 $userTS = implode(LF . '[GLOBAL]' . LF, $this->TSdataArray);
378 $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
379 $parseObj->parse($userTS);
380 $this->userTS = $parseObj->setup;
381 $this->userTSUpdated = true;
382 }
383 return $this->userTS;
384 }
385
386 /*****************************************
387 *
388 * Session data management functions
389 *
390 ****************************************/
391 /**
392 * Fetches the session data for the user (from the fe_session_data table) based on the ->id of the current user-session.
393 * The session data is restored to $this->sesData
394 * 1/100 calls will also do a garbage collection.
395 *
396 * @return void
397 * @access private
398 * @see storeSessionData()
399 */
400 public function fetchSessionData()
401 {
402 // Gets SesData if any AND if not already selected by session fixation check in ->isExistingSessionRecord()
403 if ($this->id && empty($this->sesData)) {
404 $statement = $this->db->prepare_SELECTquery('*', 'fe_session_data', 'hash = :hash');
405 $statement->execute(array(':hash' => $this->id));
406 if (($sesDataRow = $statement->fetch()) !== false) {
407 $this->sesData = unserialize($sesDataRow['content']);
408 $this->sessionDataTimestamp = $sesDataRow['tstamp'];
409 }
410 $statement->free();
411 }
412 }
413
414 /**
415 * Will write UC and session data.
416 * If the flag $this->userData_change has been set, the function ->writeUC is called (which will save persistent user session data)
417 * If the flag $this->sesData_change has been set, the fe_session_data table is updated with the content of $this->sesData
418 * If the $this->sessionDataTimestamp is NULL there was no session record yet, so we need to insert it into the database
419 *
420 * @return void
421 * @see fetchSessionData(), getKey(), setKey()
422 */
423 public function storeSessionData()
424 {
425 // Saves UC and SesData if changed.
426 if ($this->userData_change) {
427 $this->writeUC('');
428 }
429 if ($this->sesData_change && $this->id) {
430 if (empty($this->sesData)) {
431 // Remove session-data
432 $this->removeSessionData();
433 // Remove cookie if not logged in as the session data is removed as well
434 if (empty($this->user['uid']) && !$this->loginHidden && $this->isCookieSet()) {
435 $this->removeCookie($this->name);
436 }
437 } elseif ($this->sessionDataTimestamp === null) {
438 // Write new session-data
439 $insertFields = array(
440 'hash' => $this->id,
441 'content' => serialize($this->sesData),
442 'tstamp' => $GLOBALS['EXEC_TIME']
443 );
444 $this->sessionDataTimestamp = $GLOBALS['EXEC_TIME'];
445 $this->db->exec_INSERTquery('fe_session_data', $insertFields);
446 // Now set the cookie (= fix the session)
447 $this->setSessionCookie();
448 } else {
449 // Update session data
450 $updateFields = array(
451 'content' => serialize($this->sesData),
452 'tstamp' => $GLOBALS['EXEC_TIME']
453 );
454 $this->sessionDataTimestamp = $GLOBALS['EXEC_TIME'];
455 $this->db->exec_UPDATEquery('fe_session_data', 'hash=' . $this->db->fullQuoteStr($this->id, 'fe_session_data'), $updateFields);
456 }
457 }
458 }
459
460 /**
461 * Removes data of the current session.
462 *
463 * @return void
464 */
465 public function removeSessionData()
466 {
467 $this->sessionDataTimestamp = null;
468 $this->db->exec_DELETEquery('fe_session_data', 'hash=' . $this->db->fullQuoteStr($this->id, 'fe_session_data'));
469 }
470
471 /**
472 * Log out current user!
473 * Removes the current session record, sets the internal ->user array to a blank string
474 * Thereby the current user (if any) is effectively logged out!
475 * Additionally the cookie is removed
476 *
477 * @return void
478 */
479 public function logoff()
480 {
481 parent::logoff();
482 // Remove the cookie on log-off, but only if we do not have an anonymous session
483 if (!$this->isExistingSessionRecord($this->id) && $this->isCookieSet()) {
484 $this->removeCookie($this->name);
485 }
486 }
487
488 /**
489 * Regenerate the id, take seperate session data table into account
490 * and set cookie again
491 */
492 protected function regenerateSessionId()
493 {
494 $oldSessionId = $this->id;
495 parent::regenerateSessionId();
496 // Update session data with new ID
497 $this->db->exec_UPDATEquery(
498 'fe_session_data',
499 'hash=' . $this->db->fullQuoteStr($oldSessionId, 'fe_session_data'),
500 array('hash' => $this->id)
501 );
502
503 // We force the cookie to be set later in the authentication process
504 $this->dontSetCookie = false;
505 }
506
507 /**
508 * Executes the garbage collection of session data and session.
509 * The lifetime of session data is defined by $TYPO3_CONF_VARS['FE']['sessionDataLifetime'].
510 *
511 * @return void
512 */
513 public function gc()
514 {
515 $timeoutTimeStamp = (int)($GLOBALS['EXEC_TIME'] - $this->sessionDataLifetime);
516 $this->db->exec_DELETEquery('fe_session_data', 'tstamp < ' . $timeoutTimeStamp);
517 parent::gc();
518 }
519
520 /**
521 * Returns session data for the fe_user; Either persistent data following the fe_users uid/profile (requires login)
522 * or current-session based (not available when browse is closed, but does not require login)
523 *
524 * @param string $type Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
525 * @param string $key Key from the data array to return; The session data (in either case) is an array ($this->uc / $this->sesData) and this value determines which key to return the value for.
526 * @return mixed Returns whatever value there was in the array for the key, $key
527 * @see setKey()
528 */
529 public function getKey($type, $key)
530 {
531 if (!$key) {
532 return null;
533 }
534 $value = null;
535 switch ($type) {
536 case 'user':
537 $value = $this->uc[$key];
538 break;
539 case 'ses':
540 $value = $this->sesData[$key];
541 break;
542 }
543 return $value;
544 }
545
546 /**
547 * Saves session data, either persistent or bound to current session cookie. Please see getKey() for more details.
548 * When a value is set the flags $this->userData_change or $this->sesData_change will be set so that the final call to ->storeSessionData() will know if a change has occurred and needs to be saved to the database.
549 * Notice: The key "recs" is already used by the function record_registration() which stores table/uid=value pairs in that key. This is used for the shopping basket among other things.
550 * Notice: Simply calling this function will not save the data to the database! The actual saving is done in storeSessionData() which is called as some of the last things in \TYPO3\CMS\Frontend\Http\RequestHandler. So if you exit before this point, nothing gets saved of course! And the solution is to call $GLOBALS['TSFE']->storeSessionData(); before you exit.
551 *
552 * @param string $type Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
553 * @param string $key Key from the data array to store incoming data in; The session data (in either case) is an array ($this->uc / $this->sesData) and this value determines in which key the $data value will be stored.
554 * @param mixed $data The data value to store in $key
555 * @return void
556 * @see setKey(), storeSessionData(), record_registration()
557 */
558 public function setKey($type, $key, $data)
559 {
560 if (!$key) {
561 return;
562 }
563 switch ($type) {
564 case 'user':
565 if ($this->user['uid']) {
566 if ($data === null) {
567 unset($this->uc[$key]);
568 } else {
569 $this->uc[$key] = $data;
570 }
571 $this->userData_change = true;
572 }
573 break;
574 case 'ses':
575 if ($data === null) {
576 unset($this->sesData[$key]);
577 } else {
578 $this->sesData[$key] = $data;
579 }
580 $this->sesData_change = true;
581 break;
582 }
583 }
584
585 /**
586 * Returns the session data stored for $key.
587 * The data will last only for this login session since it is stored in the session table.
588 *
589 * @param string $key
590 * @return mixed
591 */
592 public function getSessionData($key)
593 {
594 return $this->getKey('ses', $key);
595 }
596
597 /**
598 * Saves the tokens so that they can be used by a later incarnation of this class.
599 *
600 * @param string $key
601 * @param mixed $data
602 * @return void
603 */
604 public function setAndSaveSessionData($key, $data)
605 {
606 $this->setKey('ses', $key, $data);
607 $this->storeSessionData();
608 }
609
610 /**
611 * Registration of records/"shopping basket" in session data
612 * This will take the input array, $recs, and merge into the current "recs" array found in the session data.
613 * If a change in the recs storage happens (which it probably does) the function setKey() is called in order to store the array again.
614 *
615 * @param array $recs The data array to merge into/override the current recs values. The $recs array is constructed as [table]][uid] = scalar-value (eg. string/integer).
616 * @param int $maxSizeOfSessionData The maximum size of stored session data. If zero, no limit is applied and even confirmation of cookie session is discarded.
617 * @return void
618 */
619 public function record_registration($recs, $maxSizeOfSessionData = 0)
620 {
621 // Storing value ONLY if there is a confirmed cookie set,
622 // otherwise a shellscript could easily be spamming the fe_sessions table
623 // with bogus content and thus bloat the database
624 if (!$maxSizeOfSessionData || $this->isCookieSet()) {
625 if ($recs['clear_all']) {
626 $this->setKey('ses', 'recs', array());
627 }
628 $change = 0;
629 $recs_array = $this->getKey('ses', 'recs');
630 foreach ($recs as $table => $data) {
631 if (is_array($data)) {
632 foreach ($data as $rec_id => $value) {
633 if ($value != $recs_array[$table][$rec_id]) {
634 $recs_array[$table][$rec_id] = $value;
635 $change = 1;
636 }
637 }
638 }
639 }
640 if ($change && (!$maxSizeOfSessionData || strlen(serialize($recs_array)) < $maxSizeOfSessionData)) {
641 $this->setKey('ses', 'recs', $recs_array);
642 }
643 }
644 }
645
646 /**
647 * Determine whether there's an according session record to a given session_id
648 * in the database. Don't care if session record is still valid or not.
649 *
650 * This calls the parent function but additionally tries to look up the session ID in the "fe_session_data" table.
651 *
652 * @param int $id Claimed Session ID
653 * @return bool Returns TRUE if a corresponding session was found in the database
654 */
655 public function isExistingSessionRecord($id)
656 {
657 // Perform check in parent function
658 $count = parent::isExistingSessionRecord($id);
659 // Check if there are any fe_session_data records for the session ID the client claims to have
660 if ($count == false) {
661 $statement = $this->db->prepare_SELECTquery('content,tstamp', 'fe_session_data', 'hash = :hash');
662 $res = $statement->execute(array(':hash' => $id));
663 if ($res !== false) {
664 if ($sesDataRow = $statement->fetch()) {
665 $count = true;
666 $this->sesData = unserialize($sesDataRow['content']);
667 $this->sessionDataTimestamp = $sesDataRow['tstamp'];
668 }
669 $statement->free();
670 }
671 }
672 return $count;
673 }
674
675 /**
676 * Hide the current login
677 *
678 * This is used by the fe_login_mode feature for pages.
679 * A current login is unset, but we remember that there has been one.
680 *
681 * @return void
682 */
683 public function hideActiveLogin()
684 {
685 $this->user = null;
686 $this->loginHidden = true;
687 }
688 }