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