-
Notifications
You must be signed in to change notification settings - Fork 638
/
LoginController.php
553 lines (505 loc) · 21.9 KB
/
LoginController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
<?php
namespace TYPO3\CMS\Backend\Controller;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use TYPO3\CMS\Backend\Exception;
use TYPO3\CMS\Backend\LoginProvider\LoginProviderInterface;
use TYPO3\CMS\Backend\Routing\UriBuilder;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\FormProtection\BackendFormProtection;
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
use TYPO3\CMS\Core\Http\HtmlResponse;
use TYPO3\CMS\Core\Localization\Locales;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\Fluid\View\StandaloneView;
/**
* Script Class for rendering the login form
*/
class LoginController implements LoggerAwareInterface
{
use LoggerAwareTrait;
/**
* The URL to redirect to after login.
*
* @var string
*/
protected $redirectUrl;
/**
* Set to the redirect URL of the form (may be redirect_url or "index.php?M=main")
*
* @var string
*/
protected $redirectToURL;
/**
* the active login provider identifier
*
* @var string
*/
protected $loginProviderIdentifier = null;
/**
* List of registered and sorted login providers
*
* @var array
*/
protected $loginProviders = [];
/**
* Login-refresh bool; The backend will call this script
* with this value set when the login is close to being expired
* and the form needs to be redrawn.
*
* @var bool
*/
protected $loginRefresh;
/**
* Value of forms submit button for login.
*
* @var string
*/
protected $submitValue;
/**
* @var StandaloneView
*/
protected $view;
/**
* Initialize the login box. Will also react on a &L=OUT flag and exit.
*/
public function __construct()
{
$this->validateAndSortLoginProviders();
// We need a PHP session session for most login levels
session_start();
$this->redirectUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('redirect_url'));
$this->loginProviderIdentifier = $this->detectLoginProvider();
$this->loginRefresh = (bool)GeneralUtility::_GP('loginRefresh');
// Value of "Login" button. If set, the login button was pressed.
$this->submitValue = GeneralUtility::_GP('commandLI');
// Try to get the preferred browser language
/** @var Locales $locales */
$locales = GeneralUtility::makeInstance(Locales::class);
$preferredBrowserLanguage = $locales
->getPreferredClientLanguage(GeneralUtility::getIndpEnv('HTTP_ACCEPT_LANGUAGE'));
// If we found a $preferredBrowserLanguage and it is not the default language and no be_user is logged in
// initialize $this->getLanguageService() again with $preferredBrowserLanguage
if ($preferredBrowserLanguage !== 'default' && empty($this->getBackendUserAuthentication()->user['uid'])) {
$this->getLanguageService()->init($preferredBrowserLanguage);
GeneralUtility::makeInstance(PageRenderer::class)->setLanguage($preferredBrowserLanguage);
}
$this->getLanguageService()->includeLLFile('EXT:lang/Resources/Private/Language/locallang_login.xlf');
// Setting the redirect URL to "index.php?M=main" if no alternative input is given
if ($this->redirectUrl) {
$this->redirectToURL = $this->redirectUrl;
} else {
$uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
$this->redirectToURL = (string)$uriBuilder->buildUriFromRoute('main');
}
// If "L" is "OUT", then any logged in is logged out. If redirect_url is given, we redirect to it
if (GeneralUtility::_GP('L') === 'OUT' && is_object($this->getBackendUserAuthentication())) {
$this->getBackendUserAuthentication()->logoff();
HttpUtility::redirect($this->redirectUrl);
}
$this->view = $this->getFluidTemplateObject();
}
/**
* Injects the request and response objects for the current request or subrequest
* As this controller goes only through the main() method, it is rather simple for now
*
* @param ServerRequestInterface $request the current request
* @return ResponseInterface the finished response with the content
*/
public function formAction(ServerRequestInterface $request): ResponseInterface
{
return new HtmlResponse($this->main());
}
/**
* Main function - creating the login/logout form
*
* @throws Exception
* @return string The content to output
*/
public function main()
{
/** @var $pageRenderer PageRenderer */
$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
$pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Login');
// Checking, if we should make a redirect.
// Might set JavaScript in the header to close window.
$this->checkRedirect();
// Extension Configuration
$extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('backend');
// Background Image
if (!empty($extConf['loginBackgroundImage'])) {
$backgroundImage = $this->getUriForFileName($extConf['loginBackgroundImage']);
if ($backgroundImage === '') {
$this->logger->warning(
'The configured TYPO3 backend login background image "' . htmlspecialchars($extConf['loginBackgroundImage']) .
'" can\'t be resolved. Please check if the file exists and the extension is activated.'
);
}
$this->getDocumentTemplate()->inDocStylesArray[] = '
.typo3-login-carousel-control.right,
.typo3-login-carousel-control.left,
.panel-login { border: 0; }
.typo3-login { background-image: url("' . $backgroundImage . '"); }
.typo3-login-footnote { background-color: #000000; color: #ffffff; opacity: 0.5; }
';
}
// Login Footnote
if (!empty($extConf['loginFootnote'])) {
$this->view->assign('loginFootnote', strip_tags(trim($extConf['loginFootnote'])));
}
// Add additional css to use the highlight color in the login screen
if (!empty($extConf['loginHighlightColor'])) {
$this->getDocumentTemplate()->inDocStylesArray[] = '
.btn-login.disabled, .btn-login[disabled], fieldset[disabled] .btn-login,
.btn-login.disabled:hover, .btn-login[disabled]:hover, fieldset[disabled] .btn-login:hover,
.btn-login.disabled:focus, .btn-login[disabled]:focus, fieldset[disabled] .btn-login:focus,
.btn-login.disabled.focus, .btn-login[disabled].focus, fieldset[disabled] .btn-login.focus,
.btn-login.disabled:active, .btn-login[disabled]:active, fieldset[disabled] .btn-login:active,
.btn-login.disabled.active, .btn-login[disabled].active, fieldset[disabled] .btn-login.active,
.btn-login:hover, .btn-login:focus, .btn-login:active,
.btn-login:active:hover, .btn-login:active:focus,
.btn-login { background-color: ' . $extConf['loginHighlightColor'] . '; }
.panel-login .panel-body { border-color: ' . $extConf['loginHighlightColor'] . '; }
';
}
// Logo
if (!empty($extConf['loginLogo'])) {
if ($this->getUriForFileName($extConf['loginLogo']) === '') {
$this->logger->warning(
'The configured TYPO3 backend login logo "' . htmlspecialchars($extConf['loginLogo']) .
'" can\'t be resolved. Please check if the file exists and the extension is activated.'
);
}
$logo = $extConf['loginLogo'];
} else {
// Use TYPO3 logo depending on highlight color
if (!empty($extConf['loginHighlightColor'])) {
$logo = 'EXT:backend/Resources/Public/Images/typo3_black.svg';
} else {
$logo = 'EXT:backend/Resources/Public/Images/typo3_orange.svg';
}
$this->getDocumentTemplate()->inDocStylesArray[] = '
.typo3-login-logo .typo3-login-image { max-width: 150px; }
';
}
$logo = $this->getUriForFileName($logo);
// Start form
$formType = empty($this->getBackendUserAuthentication()->user['uid']) ? 'LoginForm' : 'LogoutForm';
$this->view->assignMultiple([
'backendUser' => $this->getBackendUserAuthentication()->user,
'hasLoginError' => $this->isLoginInProgress(),
'formType' => $formType,
'logo' => $logo,
'images' => [
'capslock' => $this->getUriForFileName('EXT:backend/Resources/Public/Images/icon_capslock.svg'),
'typo3' => $this->getUriForFileName('EXT:backend/Resources/Public/Images/typo3_orange.svg'),
],
'copyright' => BackendUtility::TYPO3_copyRightNotice(),
'redirectUrl' => $this->redirectUrl,
'loginNewsItems' => $this->getSystemNews(),
'loginProviderIdentifier' => $this->loginProviderIdentifier,
'loginProviders' => $this->loginProviders
]);
// Initialize interface selectors:
$this->makeInterfaceSelectorBox();
/** @var LoginProviderInterface $loginProvider */
$loginProvider = GeneralUtility::makeInstance($this->loginProviders[$this->loginProviderIdentifier]['provider']);
$loginProvider->render($this->view, $pageRenderer, $this);
$content = $this->getDocumentTemplate()->startPage('TYPO3 CMS Login: ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']);
$content .= $this->view->render();
$content .= $this->getDocumentTemplate()->endPage();
return $content;
}
/**
* Checking, if we should perform some sort of redirection OR closing of windows.
*
* Do redirect:
*
* If a user is logged in AND
* a) if either the login is just done (isLoginInProgress) or
* b) a loginRefresh is done
*
* @throws \RuntimeException
* @throws \UnexpectedValueException
*/
protected function checkRedirect()
{
if (
empty($this->getBackendUserAuthentication()->user['uid'])
&& ($this->isLoginInProgress() || !$this->loginRefresh)
) {
return;
}
/*
* If no cookie has been set previously, we tell people that this is a problem.
* This assumes that a cookie-setting script (like this one) has been hit at
* least once prior to this instance.
*/
if (!$_COOKIE[BackendUserAuthentication::getCookieName()]) {
if ($this->submitValue === 'setCookie') {
/*
* we tried it a second time but still no cookie
* 26/4 2005: This does not work anymore, because the saving of challenge values
* in $_SESSION means the system will act as if the password was wrong.
*/
throw new \RuntimeException('Login-error: Yeah, that\'s a classic. No cookies, no TYPO3. ' .
'Please accept cookies from TYPO3 - otherwise you\'ll not be able to use the system.', 1294586846);
}
// try it once again - that might be needed for auto login
$this->redirectToURL = 'index.php?commandLI=setCookie';
}
$redirectToUrl = (string)$this->getBackendUserAuthentication()->getTSConfigVal('auth.BE.redirectToURL');
if (empty($redirectToUrl)) {
// Based on the interface we set the redirect script
switch (GeneralUtility::_GP('interface')) {
case 'frontend':
$interface = 'frontend';
$this->redirectToURL = '../';
break;
case 'backend':
$interface = 'backend';
$uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
$this->redirectToURL = (string)$uriBuilder->buildUriFromRoute('main');
break;
default:
$interface = '';
}
} else {
$this->redirectToURL = $redirectToUrl;
$interface = '';
}
// store interface
$this->getBackendUserAuthentication()->uc['interfaceSetup'] = $interface;
$this->getBackendUserAuthentication()->writeUC();
$formProtection = FormProtectionFactory::get();
if (!$formProtection instanceof BackendFormProtection) {
throw new \RuntimeException('The Form Protection retrieved does not match the expected one.', 1432080411);
}
if ($this->loginRefresh) {
$formProtection->setSessionTokenFromRegistry();
$formProtection->persistSessionToken();
$this->getDocumentTemplate()->JScode .= GeneralUtility::wrapJS('
if (parent.opener && parent.opener.TYPO3 && parent.opener.TYPO3.LoginRefresh) {
parent.opener.TYPO3.LoginRefresh.startTask();
parent.close();
}
');
} else {
$formProtection->storeSessionTokenInRegistry();
HttpUtility::redirect($this->redirectToURL);
}
}
/**
* Making interface selector:
*/
public function makeInterfaceSelectorBox()
{
// If interfaces are defined AND no input redirect URL in GET vars:
if ($GLOBALS['TYPO3_CONF_VARS']['BE']['interfaces'] && ($this->isLoginInProgress() || !$this->redirectUrl)) {
$parts = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['BE']['interfaces']);
if (count($parts) > 1) {
// Only if more than one interface is defined we will show the selector
$uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
$interfaces = [
'backend' => [
'label' => $this->getLanguageService()->getLL('interface.backend'),
'jumpScript' => (string)$uriBuilder->buildUriFromRoute('main'),
'interface' => 'backend'
],
'frontend' => [
'label' => $this->getLanguageService()->getLL('interface.frontend'),
'jumpScript' => '../',
'interface' => 'frontend'
]
];
$this->view->assign('showInterfaceSelector', true);
$this->view->assign('interfaces', $interfaces);
} elseif (!$this->redirectUrl) {
// If there is only ONE interface value set and no redirect_url is present
$this->view->assign('showInterfaceSelector', false);
$this->view->assign('interface', $parts[0]);
}
}
}
/**
* Gets news from sys_news and converts them into a format suitable for
* showing them at the login screen.
*
* @return array An array of login news.
*/
protected function getSystemNews()
{
$systemNewsTable = 'sys_news';
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable($systemNewsTable);
$systemNews = [];
$systemNewsRecords = $queryBuilder
->select('title', 'content', 'crdate')
->from($systemNewsTable)
->orderBy('crdate', 'DESC')
->execute()
->fetchAll();
foreach ($systemNewsRecords as $systemNewsRecord) {
$systemNews[] = [
'date' => date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $systemNewsRecord['crdate']),
'header' => $systemNewsRecord['title'],
'content' => $systemNewsRecord['content']
];
}
return $systemNews;
}
/**
* Returns the uri of a relative reference, resolves the "EXT:" prefix
* (way of referring to files inside extensions) and checks that the file is inside
* the PATH_site of the TYPO3 installation
*
* @param string $filename The input filename/filepath to evaluate
* @return string Returns the filename of $filename if valid, otherwise blank string.
* @internal
*/
private function getUriForFileName($filename)
{
// Check if it's already a URL
if (preg_match('/^(https?:)?\/\//', $filename)) {
return $filename;
}
$absoluteFilename = GeneralUtility::getFileAbsFileName(ltrim($filename, '/'));
$filename = '';
if ($absoluteFilename !== '' && @is_file($absoluteFilename)) {
$filename = PathUtility::getAbsoluteWebPath($absoluteFilename);
}
return $filename;
}
/**
* Checks if login credentials are currently submitted
*
* @return bool
*/
protected function isLoginInProgress()
{
$username = GeneralUtility::_GP('username');
return !empty($username) || !empty($this->submitValue);
}
/**
* returns a new standalone view, shorthand function
*
* @return StandaloneView
*/
protected function getFluidTemplateObject()
{
/** @var StandaloneView $view */
$view = GeneralUtility::makeInstance(StandaloneView::class);
$view->setLayoutRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Layouts')]);
$view->setPartialRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Partials')]);
$view->setTemplateRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates')]);
$view->getRequest()->setControllerExtensionName('Backend');
return $view;
}
/**
* Validates the registered login providers
*
* @throws \RuntimeException
*/
protected function validateAndSortLoginProviders()
{
$providers = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'] ?? [];
if (empty($providers) || !is_array($providers)) {
throw new \RuntimeException('No login providers are registered in $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXTCONF\'][\'backend\'][\'loginProviders\'].', 1433417281);
}
foreach ($providers as $identifier => $configuration) {
if (empty($configuration) || !is_array($configuration)) {
throw new \RuntimeException('Missing configuration for login provider "' . $identifier . '".', 1433416043);
}
if (!is_string($configuration['provider']) || empty($configuration['provider']) || !class_exists($configuration['provider']) || !is_subclass_of($configuration['provider'], LoginProviderInterface::class)) {
throw new \RuntimeException('The login provider "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . LoginProviderInterface::class . '".', 1460977275);
}
if (empty($configuration['label'])) {
throw new \RuntimeException('Missing label definition for login provider "' . $identifier . '".', 1433416044);
}
if (empty($configuration['icon-class'])) {
throw new \RuntimeException('Missing icon definition for login provider "' . $identifier . '".', 1433416045);
}
if (!isset($configuration['sorting'])) {
throw new \RuntimeException('Missing sorting definition for login provider "' . $identifier . '".', 1433416046);
}
}
// sort providers
uasort($providers, function ($a, $b) {
return $b['sorting'] - $a['sorting'];
});
$this->loginProviders = $providers;
}
/**
* Detect the login provider, get from request or choose the
* first one as default
*
* @return string
*/
protected function detectLoginProvider()
{
$loginProvider = GeneralUtility::_GP('loginProvider');
if ((empty($loginProvider) || !isset($this->loginProviders[$loginProvider])) && !empty($_COOKIE['be_lastLoginProvider'])) {
$loginProvider = $_COOKIE['be_lastLoginProvider'];
}
if (empty($loginProvider) || !isset($this->loginProviders[$loginProvider])) {
reset($this->loginProviders);
$loginProvider = key($this->loginProviders);
}
// Use the secure option when the current request is served by a secure connection:
$cookieSecure = (bool)$GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieSecure'] && GeneralUtility::getIndpEnv('TYPO3_SSL');
setcookie('be_lastLoginProvider', $loginProvider, $GLOBALS['EXEC_TIME'] + 7776000, null, null, $cookieSecure, true); // 90 days
return $loginProvider;
}
/**
* @return string
*/
public function getLoginProviderIdentifier()
{
return $this->loginProviderIdentifier;
}
/**
* Returns LanguageService
*
* @return \TYPO3\CMS\Core\Localization\LanguageService
*/
protected function getLanguageService()
{
return $GLOBALS['LANG'];
}
/**
* @return BackendUserAuthentication
*/
protected function getBackendUserAuthentication()
{
return $GLOBALS['BE_USER'];
}
/**
* Returns an instance of DocumentTemplate
*
* @return \TYPO3\CMS\Backend\Template\DocumentTemplate
*/
protected function getDocumentTemplate()
{
return $GLOBALS['TBE_TEMPLATE'];
}
}