-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathAuthenticationController.php
More file actions
240 lines (213 loc) · 8.56 KB
/
AuthenticationController.php
File metadata and controls
240 lines (213 loc) · 8.56 KB
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
<?php
// SPDX-FileCopyrightText: 2018 Icinga GmbH <https://icinga.com>
// SPDX-License-Identifier: GPL-3.0-or-later
namespace Icinga\Controllers;
use Icinga\Application\ClassLoader;
use Icinga\Application\Hook\AuthenticationHook;
use Icinga\Application\Hook\LoginButtonHook;
use Icinga\Application\Icinga;
use Icinga\Application\Logger;
use Icinga\Authentication\LoginButton;
use Icinga\Authentication\LoginButtonForm;
use Icinga\Authentication\Auth;
use Icinga\Authentication\TwoFactorState;
use Icinga\Authentication\User\ExternalBackend;
use Icinga\Common\Database;
use Icinga\Exception\AuthenticationException;
use Icinga\Forms\Authentication\LoginForm;
use Icinga\Forms\Authentication\TwoFactorChallengeForm;
use Icinga\Web\Helper\CookieHelper;
use Icinga\Web\RememberMe;
use Icinga\Web\Session;
use Icinga\Web\Url;
use Icinga\Web\Widget\LoginPage;
use ipl\Html\HtmlDocument;
use ipl\Html\Contract\Form;
use ipl\Web\Compat\CompatController;
use RuntimeException;
use Throwable;
/**
* Application wide controller for authentication
*/
class AuthenticationController extends CompatController
{
use Database;
/**
* {@inheritdoc}
*/
protected $requiresAuthentication = false;
/**
* {@inheritdoc}
*/
protected $innerLayout = 'inline';
/**
* Log into the application
*/
public function loginAction()
{
$twoFactorState = new TwoFactorState();
if ($twoFactorState->isChallenged()) {
$this->redirectNow($this->withRedirect('authentication/twofactor'));
}
$icinga = Icinga::app();
if (($requiresSetup = $icinga->requiresSetup()) && $icinga->setupTokenExists()) {
$this->redirectNow(Url::fromPath('setup'));
}
$form = (new LoginForm())
->setAction(Url::fromRequest()->getAbsoluteUrl())
->on(Form::ON_SUBMIT, function (LoginForm $form) {
if ($redirectUrl = $form->getRedirectUrl()) {
$this->redirectNow($redirectUrl);
}
})
->on(Form::ON_REQUEST, function ($request, LoginForm $form) {
$auth = Auth::getInstance();
$onlyExternal = true;
// TODO(el): This may be set on the auth chain once iterated. See Auth::authExternal().
foreach ($auth->getAuthChain() as $backend) {
if (! $backend instanceof ExternalBackend) {
$onlyExternal = false;
}
}
if ($onlyExternal) {
$form->addMessage($this->translate(
'You\'re currently not authenticated using any of the web server\'s authentication'
. 'mechanisms. Make sure you\'ll configure such, otherwise you\'ll not be able to login.'
));
$form->onError();
}
});
if (RememberMe::hasCookie() && $this->hasDb()) {
$authenticated = false;
try {
$rememberMeOld = RememberMe::fromCookie();
$authenticated = $rememberMeOld->authenticate();
if ($authenticated) {
$rememberMe = $rememberMeOld->renew();
$this->getResponse()->setCookie($rememberMe->getCookie());
$rememberMe->persist($rememberMeOld->getAesCrypt()->getIV());
}
} catch (RuntimeException $e) {
Logger::error("Can't authenticate user via remember me cookie: %s", $e->getMessage());
} catch (AuthenticationException $e) {
Logger::error($e);
}
if (! $authenticated) {
$this->getResponse()->setCookie(RememberMe::forget());
}
}
if ($this->Auth()->isAuthenticated()) {
// Call provided AuthenticationHook(s) when login action is called
// but icinga web user is already authenticated
AuthenticationHook::triggerLogin($this->Auth()->getUser());
$redirect = $this->params->get('redirect');
if ($redirect) {
$redirectUrl = Url::fromPath($redirect, [], $this->getRequest());
if ($redirectUrl->isExternal()) {
$this->httpBadRequest('nope');
}
} else {
$redirectUrl = $form->createRedirectUrl();
}
$this->redirectNow($redirectUrl);
}
$request = $this->getServerRequest();
if (! $requiresSetup) {
$cookies = new CookieHelper($this->getRequest());
if (! $cookies->isSupported()) {
$this
->getResponse()
->setBody("Cookies must be enabled to run this application.\n")
->setHttpResponseCode(403)
->sendResponse();
exit;
}
$form->handleRequest($request);
}
$loginButtons = [];
foreach (LoginButtonHook::all() as $class => $hook) {
try {
foreach ($hook->getButtons() as $index => $button) {
assert($button instanceof LoginButton);
$loginButtons[] = (new LoginButtonForm(
sha1("$class!$index"),
$button,
ClassLoader::classBelongsToModule($class) ? ClassLoader::extractModuleName($class) : null
))
->on(LoginButtonForm::ON_SUCCESS, function () use ($button): void {
($button->onClick)();
})
->handleRequest($request);
}
} catch (Throwable $e) {
Logger::error('Failed to execute login button hook: %s', $e);
continue;
}
}
$this->setTitle($this->translate('Icinga Web 2 Login'));
// Suppress the rendering of an empty tab bar
$this->controls = new HtmlDocument();
$this->addContent(new LoginPage($form, $loginButtons, $requiresSetup));
}
/**
* Log out the current user
*/
public function logoutAction()
{
$auth = $this->Auth();
if (! $auth->isAuthenticated()) {
$this->redirectToLogin();
}
// Get info whether the user is externally authenticated before removing authorization which destroys the
// session and the user object
$isExternalUser = $auth->getUser()->isExternalUser();
// Call provided AuthenticationHook(s) when logout action is called
AuthenticationHook::triggerLogout($auth->getUser());
$auth->removeAuthorization();
if ($isExternalUser) {
$this->view->layout()->setLayout('external-logout');
$this->getResponse()->setHttpResponseCode(401);
} else {
if (RememberMe::hasCookie() && $this->hasDb()) {
$this->getResponse()->setCookie(RememberMe::forget());
}
$this->redirectToLogin();
}
}
public function twofactorAction(): void
{
$twoFactorState = new TwoFactorState();
if (! $twoFactorState->isChallenged()) {
$this->redirectToLogin();
}
$form = (new TwoFactorChallengeForm())
->setAction(Url::fromRequest()->getAbsoluteUrl())
->on(Form::ON_SUBMIT, function (TwoFactorChallengeForm $form) {
if ($redirectUrl = $form->getRedirectUrl()) {
$this->redirectNow($redirectUrl);
}
})
->on(Form::ON_SENT, function (TwoFactorChallengeForm $form) {
$isCsrfValid = $form->getElement('CSRFToken')->isValid();
$isCancelPressed =
$form->getPressedSubmitElement()?->getName() === TwoFactorChallengeForm::SUBMIT_CANCEL;
if ($isCsrfValid && $isCancelPressed) {
Session::getSession()->purge();
$this->redirectNow($this->withRedirect('authentication/login'));
}
})
->handleRequest($this->getServerRequest());
$this->setTitle($this->translate('Icinga Web 2 Two-Factor Auth'));
// Suppress the rendering of an empty tab bar
$this->controls = new HtmlDocument();
$this->addContent(new LoginPage($form));
}
protected function withRedirect(string $path): Url
{
$url = Url::fromPath($path);
if ($redirect = $this->params->get('redirect')) {
$url->setParam('redirect', $redirect);
}
return $url;
}
}