11b98a7f5e9c3ac136aac20655f7052c328f68f2
[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 $this->logger->debug('Get usergroups for user', [
284 $this->userid_column => $this->user[$this->userid_column],
285 $this->username_column => $this->user[$this->username_column]
286 ]);
287 } else {
288 $this->logger->debug('Get usergroups for "anonymous" user');
289 }
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 ($this->writeDevLog) {
306 if ($serviceChain) {
307 $this->logger->debug($subType . ' auth services called: ' . $serviceChain);
308 }
309 if (empty($groupDataArr)) {
310 $this->logger->debug('No usergroups found by services');
311 }
312 if (!empty($groupDataArr)) {
313 $this->logger->debug(count($groupDataArr) . ' usergroup records found by services');
314 }
315 }
316 // Use 'auth' service to check the usergroups if they are really valid
317 foreach ($groupDataArr as $groupData) {
318 // By default a group is valid
319 $validGroup = true;
320 $serviceChain = '';
321 $subType = 'authGroups' . $this->loginType;
322 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
323 $serviceChain .= ',' . $serviceObj->getServiceKey();
324 $serviceObj->initAuth($subType, [], $authInfo, $this);
325 if (!$serviceObj->authGroup($this->user, $groupData)) {
326 $validGroup = false;
327 if ($this->writeDevLog) {
328 $this->logger->debug($subType . ' auth service did not auth group', [
329 'uid ' => $groupData['uid'],
330 'title' => $groupData['title']
331 ]);
332 }
333 break;
334 }
335 unset($serviceObj);
336 }
337 unset($serviceObj);
338 if ($validGroup && (string)$groupData['uid'] !== '') {
339 $this->groupData['title'][$groupData['uid']] = $groupData['title'];
340 $this->groupData['uid'][$groupData['uid']] = $groupData['uid'];
341 $this->groupData['pid'][$groupData['uid']] = $groupData['pid'];
342 $this->groupData['TSconfig'][$groupData['uid']] = $groupData['TSconfig'];
343 }
344 }
345 if (!empty($this->groupData) && !empty($this->groupData['TSconfig'])) {
346 // TSconfig: collect it in the order it was collected
347 foreach ($this->groupData['TSconfig'] as $TSdata) {
348 $this->TSdataArray[] = $TSdata;
349 }
350 $this->TSdataArray[] = $this->user['TSconfig'];
351 // Sort information
352 ksort($this->groupData['title']);
353 ksort($this->groupData['uid']);
354 ksort($this->groupData['pid']);
355 }
356 return !empty($this->groupData['uid']) ? count($this->groupData['uid']) : 0;
357 }
358
359 /**
360 * Returns the parsed TSconfig for the fe_user
361 * The TSconfig will be cached in $this->userTS.
362 *
363 * @return array TSconfig array for the fe_user
364 */
365 public function getUserTSconf()
366 {
367 if (!$this->userTSUpdated) {
368 // Parsing the user TS (or getting from cache)
369 $this->TSdataArray = TypoScriptParser::checkIncludeLines_array($this->TSdataArray);
370 $userTS = implode(LF . '[GLOBAL]' . LF, $this->TSdataArray);
371 $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
372 $parseObj->parse($userTS);
373 $this->userTS = $parseObj->setup;
374 $this->userTSUpdated = true;
375 }
376 return $this->userTS;
377 }
378
379 /*****************************************
380 *
381 * Session data management functions
382 *
383 ****************************************/
384 /**
385 * Will write UC and session data.
386 * If the flag $this->userData_change has been set, the function ->writeUC is called (which will save persistent user session data)
387 * If the flag $this->sesData_change has been set, the current session record is updated with the content of $this->sessionData
388 *
389 * @see getKey(), setKey()
390 */
391 public function storeSessionData()
392 {
393 // Saves UC and SesData if changed.
394 if ($this->userData_change) {
395 $this->writeUC();
396 }
397
398 if ($this->sesData_change && $this->id) {
399 if (empty($this->sessionData)) {
400 // Remove session-data
401 $this->removeSessionData();
402 // Remove cookie if not logged in as the session data is removed as well
403 if (empty($this->user['uid']) && !$this->loginHidden && $this->isCookieSet()) {
404 $this->removeCookie($this->name);
405 }
406 } elseif (!$this->isExistingSessionRecord($this->id)) {
407 $sessionRecord = $this->getNewSessionRecord([]);
408 $sessionRecord['ses_anonymous'] = 1;
409 $sessionRecord['ses_data'] = serialize($this->sessionData);
410 $updatedSession = $this->getSessionBackend()->set($this->id, $sessionRecord);
411 $this->user = array_merge($this->user ?? [], $updatedSession);
412 // Now set the cookie (= fix the session)
413 $this->setSessionCookie();
414 } else {
415 // Update session data
416 $insertFields = [
417 'ses_data' => serialize($this->sessionData)
418 ];
419 $updatedSession = $this->getSessionBackend()->update($this->id, $insertFields);
420 $this->user = array_merge($this->user ?? [], $updatedSession);
421 }
422 }
423 }
424
425 /**
426 * Removes data of the current session.
427 */
428 public function removeSessionData()
429 {
430 if (!empty($this->sessionData)) {
431 $this->sesData_change = true;
432 }
433 $this->sessionData = [];
434
435 if ($this->isExistingSessionRecord($this->id)) {
436 // Remove session record if $this->user is empty is if session is anonymous
437 if ((empty($this->user) && !$this->loginHidden) || $this->user['ses_anonymous']) {
438 $this->getSessionBackend()->remove($this->id);
439 } else {
440 $this->getSessionBackend()->update($this->id, [
441 'ses_data' => ''
442 ]);
443 }
444 }
445 }
446
447 /**
448 * Removes the current session record, sets the internal ->user array to null,
449 * Thereby the current user (if any) is effectively logged out!
450 * Additionally the cookie is removed, but only if there is no session data.
451 * If session data exists, only the user information is removed and the session
452 * gets converted into an anonymous session.
453 */
454 protected function performLogoff()
455 {
456 $oldSession = [];
457 $sessionData = [];
458 try {
459 // Session might not be loaded at this point, so fetch it
460 $oldSession = $this->getSessionBackend()->get($this->id);
461 $sessionData = unserialize($oldSession['ses_data']);
462 } catch (SessionNotFoundException $e) {
463 // Leave uncaught, will unset cookie later in this method
464 }
465
466 if (!empty($sessionData)) {
467 // Regenerate session as anonymous
468 $this->regenerateSessionId($oldSession, true);
469 } else {
470 $this->user = null;
471 $this->getSessionBackend()->remove($this->id);
472 if ($this->isCookieSet()) {
473 $this->removeCookie($this->name);
474 }
475 }
476 }
477
478 /**
479 * Regenerate the session ID and transfer the session to new ID
480 * Call this method whenever a user proceeds to a higher authorization level
481 * e.g. when an anonymous session is now authenticated.
482 * Forces cookie to be set
483 *
484 * @param array $existingSessionRecord If given, this session record will be used instead of fetching again'
485 * @param bool $anonymous If true session will be regenerated as anonymous session
486 */
487 protected function regenerateSessionId(array $existingSessionRecord = [], bool $anonymous = false)
488 {
489 if (empty($existingSessionRecord)) {
490 $existingSessionRecord = $this->getSessionBackend()->get($this->id);
491 }
492 $existingSessionRecord['ses_anonymous'] = (int)$anonymous;
493 if ($anonymous) {
494 $existingSessionRecord['ses_userid'] = 0;
495 }
496 parent::regenerateSessionId($existingSessionRecord, $anonymous);
497 // We force the cookie to be set later in the authentication process
498 $this->dontSetCookie = false;
499 }
500
501 /**
502 * Returns session data for the fe_user; Either persistent data following the fe_users uid/profile (requires login)
503 * or current-session based (not available when browse is closed, but does not require login)
504 *
505 * @param string $type Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
506 * @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.
507 * @return mixed Returns whatever value there was in the array for the key, $key
508 * @see setKey()
509 */
510 public function getKey($type, $key)
511 {
512 if (!$key) {
513 return null;
514 }
515 $value = null;
516 switch ($type) {
517 case 'user':
518 $value = $this->uc[$key];
519 break;
520 case 'ses':
521 $value = $this->getSessionData($key);
522 break;
523 }
524 return $value;
525 }
526
527 /**
528 * Saves session data, either persistent or bound to current session cookie. Please see getKey() for more details.
529 * 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.
530 * 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.
531 *
532 * @param string $type Session data type; Either "user" (persistent, bound to fe_users profile) or "ses" (temporary, bound to current session cookie)
533 * @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.
534 * @param mixed $data The data value to store in $key
535 * @see setKey(), storeSessionData()
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 */
566 public function setSessionData($key, $data)
567 {
568 $this->sesData_change = true;
569 if ($data === null) {
570 unset($this->sessionData[$key]);
571 return;
572 }
573 parent::setSessionData($key, $data);
574 }
575
576 /**
577 * Saves the tokens so that they can be used by a later incarnation of this class.
578 *
579 * @param string $key
580 * @param mixed $data
581 */
582 public function setAndSaveSessionData($key, $data)
583 {
584 $this->setSessionData($key, $data);
585 $this->storeSessionData();
586 }
587
588 /**
589 * Garbage collector, removing old expired sessions.
590 *
591 * @internal
592 */
593 public function gc()
594 {
595 $this->getSessionBackend()->collectGarbage($this->gc_time, $this->sessionDataLifetime);
596 }
597
598 /**
599 * Hide the current login
600 *
601 * This is used by the fe_login_mode feature for pages.
602 * A current login is unset, but we remember that there has been one.
603 */
604 public function hideActiveLogin()
605 {
606 $this->user = null;
607 $this->loginHidden = true;
608 }
609 }