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