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