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