Passed
Push — master ( bcb52d...d3ab26 )
by Roeland
13:43 queued 11s
created
core/Controller/LoginController.php 1 patch
Indentation   +317 added lines, -317 removed lines patch added patch discarded remove patch
@@ -58,321 +58,321 @@
 block discarded – undo
58 58
 use OCP\Util;
59 59
 
60 60
 class LoginController extends Controller {
61
-	public const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
62
-	public const LOGIN_MSG_USERDISABLED = 'userdisabled';
63
-
64
-	/** @var IUserManager */
65
-	private $userManager;
66
-	/** @var IConfig */
67
-	private $config;
68
-	/** @var ISession */
69
-	private $session;
70
-	/** @var IUserSession|Session */
71
-	private $userSession;
72
-	/** @var IURLGenerator */
73
-	private $urlGenerator;
74
-	/** @var ILogger */
75
-	private $logger;
76
-	/** @var Defaults */
77
-	private $defaults;
78
-	/** @var Throttler */
79
-	private $throttler;
80
-	/** @var Chain */
81
-	private $loginChain;
82
-	/** @var IInitialStateService */
83
-	private $initialStateService;
84
-	/** @var WebAuthnManager */
85
-	private $webAuthnManager;
86
-
87
-	public function __construct(?string $appName,
88
-								IRequest $request,
89
-								IUserManager $userManager,
90
-								IConfig $config,
91
-								ISession $session,
92
-								IUserSession $userSession,
93
-								IURLGenerator $urlGenerator,
94
-								ILogger $logger,
95
-								Defaults $defaults,
96
-								Throttler $throttler,
97
-								Chain $loginChain,
98
-								IInitialStateService $initialStateService,
99
-								WebAuthnManager $webAuthnManager) {
100
-		parent::__construct($appName, $request);
101
-		$this->userManager = $userManager;
102
-		$this->config = $config;
103
-		$this->session = $session;
104
-		$this->userSession = $userSession;
105
-		$this->urlGenerator = $urlGenerator;
106
-		$this->logger = $logger;
107
-		$this->defaults = $defaults;
108
-		$this->throttler = $throttler;
109
-		$this->loginChain = $loginChain;
110
-		$this->initialStateService = $initialStateService;
111
-		$this->webAuthnManager = $webAuthnManager;
112
-	}
113
-
114
-	/**
115
-	 * @NoAdminRequired
116
-	 * @UseSession
117
-	 *
118
-	 * @return RedirectResponse
119
-	 */
120
-	public function logout() {
121
-		$loginToken = $this->request->getCookie('nc_token');
122
-		if (!is_null($loginToken)) {
123
-			$this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
124
-		}
125
-		$this->userSession->logout();
126
-
127
-		$response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
128
-			'core.login.showLoginForm',
129
-			['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
130
-		));
131
-
132
-		$this->session->set('clearingExecutionContexts', '1');
133
-		$this->session->close();
134
-
135
-		if (!$this->request->isUserAgent([Request::USER_AGENT_CHROME, Request::USER_AGENT_ANDROID_MOBILE_CHROME])) {
136
-			$response->addHeader('Clear-Site-Data', '"cache", "storage"');
137
-		}
138
-
139
-		return $response;
140
-	}
141
-
142
-	/**
143
-	 * @PublicPage
144
-	 * @NoCSRFRequired
145
-	 * @UseSession
146
-	 *
147
-	 * @param string $user
148
-	 * @param string $redirect_url
149
-	 *
150
-	 * @return TemplateResponse|RedirectResponse
151
-	 */
152
-	public function showLoginForm(string $user = null, string $redirect_url = null): Http\Response {
153
-		if ($this->userSession->isLoggedIn()) {
154
-			return new RedirectResponse(OC_Util::getDefaultPageUrl());
155
-		}
156
-
157
-		$loginMessages = $this->session->get('loginMessages');
158
-		if (is_array($loginMessages)) {
159
-			list($errors, $messages) = $loginMessages;
160
-			$this->initialStateService->provideInitialState('core', 'loginMessages', $messages);
161
-			$this->initialStateService->provideInitialState('core', 'loginErrors', $errors);
162
-		}
163
-		$this->session->remove('loginMessages');
164
-
165
-		if ($user !== null && $user !== '') {
166
-			$this->initialStateService->provideInitialState('core', 'loginUsername', $user);
167
-		} else {
168
-			$this->initialStateService->provideInitialState('core', 'loginUsername', '');
169
-		}
170
-
171
-		$this->initialStateService->provideInitialState(
172
-			'core',
173
-			'loginAutocomplete',
174
-			$this->config->getSystemValue('login_form_autocomplete', true) === true
175
-		);
176
-
177
-		if (!empty($redirect_url)) {
178
-			[$url, ] = explode('?', $redirect_url);
179
-			if ($url !== $this->urlGenerator->linkToRoute('core.login.logout')) {
180
-				$this->initialStateService->provideInitialState('core', 'loginRedirectUrl', $redirect_url);
181
-			}
182
-		}
183
-
184
-		$this->initialStateService->provideInitialState(
185
-			'core',
186
-			'loginThrottleDelay',
187
-			$this->throttler->getDelay($this->request->getRemoteAddress())
188
-		);
189
-
190
-		$this->setPasswordResetInitialState($user);
191
-
192
-		$this->initialStateService->provideInitialState('core', 'webauthn-available', $this->webAuthnManager->isWebAuthnAvailable());
193
-
194
-		// OpenGraph Support: http://ogp.me/
195
-		Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
196
-		Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
197
-		Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
198
-		Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
199
-		Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
200
-		Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
201
-
202
-		$parameters = [
203
-			'alt_login' => OC_App::getAlternativeLogIns(),
204
-		];
205
-		return new TemplateResponse(
206
-			$this->appName, 'login', $parameters, 'guest'
207
-		);
208
-	}
209
-
210
-	/**
211
-	 * Sets the password reset state
212
-	 *
213
-	 * @param string $username
214
-	 */
215
-	private function setPasswordResetInitialState(?string $username): void {
216
-		if ($username !== null && $username !== '') {
217
-			$user = $this->userManager->get($username);
218
-		} else {
219
-			$user = null;
220
-		}
221
-
222
-		$passwordLink = $this->config->getSystemValue('lost_password_link', '');
223
-
224
-		$this->initialStateService->provideInitialState(
225
-			'core',
226
-			'loginResetPasswordLink',
227
-			$passwordLink
228
-		);
229
-
230
-		$this->initialStateService->provideInitialState(
231
-			'core',
232
-			'loginCanResetPassword',
233
-			$this->canResetPassword($passwordLink, $user)
234
-		);
235
-	}
236
-
237
-	/**
238
-	 * @param string|null $passwordLink
239
-	 * @param IUser|null $user
240
-	 *
241
-	 * Users may not change their passwords if:
242
-	 * - The account is disabled
243
-	 * - The backend doesn't support password resets
244
-	 * - The password reset function is disabled
245
-	 *
246
-	 * @return bool
247
-	 */
248
-	private function canResetPassword(?string $passwordLink, ?IUser $user): bool {
249
-		if ($passwordLink === 'disabled') {
250
-			return false;
251
-		}
252
-
253
-		if (!$passwordLink && $user !== null) {
254
-			return $user->canChangePassword();
255
-		}
256
-
257
-		if ($user !== null && $user->isEnabled() === false) {
258
-			return false;
259
-		}
260
-
261
-		return true;
262
-	}
263
-
264
-	private function generateRedirect(?string $redirectUrl): RedirectResponse {
265
-		if ($redirectUrl !== null && $this->userSession->isLoggedIn()) {
266
-			$location = $this->urlGenerator->getAbsoluteURL($redirectUrl);
267
-			// Deny the redirect if the URL contains a @
268
-			// This prevents unvalidated redirects like ?redirect_url=:[email protected]
269
-			if (strpos($location, '@') === false) {
270
-				return new RedirectResponse($location);
271
-			}
272
-		}
273
-		return new RedirectResponse(OC_Util::getDefaultPageUrl());
274
-	}
275
-
276
-	/**
277
-	 * @PublicPage
278
-	 * @UseSession
279
-	 * @NoCSRFRequired
280
-	 * @BruteForceProtection(action=login)
281
-	 *
282
-	 * @param string $user
283
-	 * @param string $password
284
-	 * @param string $redirect_url
285
-	 * @param string $timezone
286
-	 * @param string $timezone_offset
287
-	 *
288
-	 * @return RedirectResponse
289
-	 */
290
-	public function tryLogin(string $user,
291
-							 string $password,
292
-							 string $redirect_url = null,
293
-							 string $timezone = '',
294
-							 string $timezone_offset = ''): RedirectResponse {
295
-		// If the user is already logged in and the CSRF check does not pass then
296
-		// simply redirect the user to the correct page as required. This is the
297
-		// case when an user has already logged-in, in another tab.
298
-		if (!$this->request->passesCSRFCheck()) {
299
-			return $this->generateRedirect($redirect_url);
300
-		}
301
-
302
-		$data = new LoginData(
303
-			$this->request,
304
-			trim($user),
305
-			$password,
306
-			$redirect_url,
307
-			$timezone,
308
-			$timezone_offset
309
-		);
310
-		$result = $this->loginChain->process($data);
311
-		if (!$result->isSuccess()) {
312
-			return $this->createLoginFailedResponse(
313
-				$data->getUsername(),
314
-				$user,
315
-				$redirect_url,
316
-				$result->getErrorMessage()
317
-			);
318
-		}
319
-
320
-		if ($result->getRedirectUrl() !== null) {
321
-			return new RedirectResponse($result->getRedirectUrl());
322
-		}
323
-		return $this->generateRedirect($redirect_url);
324
-	}
325
-
326
-	/**
327
-	 * Creates a login failed response.
328
-	 *
329
-	 * @param string $user
330
-	 * @param string $originalUser
331
-	 * @param string $redirect_url
332
-	 * @param string $loginMessage
333
-	 *
334
-	 * @return RedirectResponse
335
-	 */
336
-	private function createLoginFailedResponse(
337
-		$user, $originalUser, $redirect_url, string $loginMessage) {
338
-		// Read current user and append if possible we need to
339
-		// return the unmodified user otherwise we will leak the login name
340
-		$args = $user !== null ? ['user' => $originalUser] : [];
341
-		if ($redirect_url !== null) {
342
-			$args['redirect_url'] = $redirect_url;
343
-		}
344
-		$response = new RedirectResponse(
345
-			$this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
346
-		);
347
-		$response->throttle(['user' => substr($user, 0, 64)]);
348
-		$this->session->set('loginMessages', [
349
-			[$loginMessage], []
350
-		]);
351
-		return $response;
352
-	}
353
-
354
-	/**
355
-	 * @NoAdminRequired
356
-	 * @UseSession
357
-	 * @BruteForceProtection(action=sudo)
358
-	 *
359
-	 * @param string $password
360
-	 *
361
-	 * @return DataResponse
362
-	 * @license GNU AGPL version 3 or any later version
363
-	 *
364
-	 */
365
-	public function confirmPassword($password) {
366
-		$loginName = $this->userSession->getLoginName();
367
-		$loginResult = $this->userManager->checkPassword($loginName, $password);
368
-		if ($loginResult === false) {
369
-			$response = new DataResponse([], Http::STATUS_FORBIDDEN);
370
-			$response->throttle();
371
-			return $response;
372
-		}
373
-
374
-		$confirmTimestamp = time();
375
-		$this->session->set('last-password-confirm', $confirmTimestamp);
376
-		return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
377
-	}
61
+    public const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
62
+    public const LOGIN_MSG_USERDISABLED = 'userdisabled';
63
+
64
+    /** @var IUserManager */
65
+    private $userManager;
66
+    /** @var IConfig */
67
+    private $config;
68
+    /** @var ISession */
69
+    private $session;
70
+    /** @var IUserSession|Session */
71
+    private $userSession;
72
+    /** @var IURLGenerator */
73
+    private $urlGenerator;
74
+    /** @var ILogger */
75
+    private $logger;
76
+    /** @var Defaults */
77
+    private $defaults;
78
+    /** @var Throttler */
79
+    private $throttler;
80
+    /** @var Chain */
81
+    private $loginChain;
82
+    /** @var IInitialStateService */
83
+    private $initialStateService;
84
+    /** @var WebAuthnManager */
85
+    private $webAuthnManager;
86
+
87
+    public function __construct(?string $appName,
88
+                                IRequest $request,
89
+                                IUserManager $userManager,
90
+                                IConfig $config,
91
+                                ISession $session,
92
+                                IUserSession $userSession,
93
+                                IURLGenerator $urlGenerator,
94
+                                ILogger $logger,
95
+                                Defaults $defaults,
96
+                                Throttler $throttler,
97
+                                Chain $loginChain,
98
+                                IInitialStateService $initialStateService,
99
+                                WebAuthnManager $webAuthnManager) {
100
+        parent::__construct($appName, $request);
101
+        $this->userManager = $userManager;
102
+        $this->config = $config;
103
+        $this->session = $session;
104
+        $this->userSession = $userSession;
105
+        $this->urlGenerator = $urlGenerator;
106
+        $this->logger = $logger;
107
+        $this->defaults = $defaults;
108
+        $this->throttler = $throttler;
109
+        $this->loginChain = $loginChain;
110
+        $this->initialStateService = $initialStateService;
111
+        $this->webAuthnManager = $webAuthnManager;
112
+    }
113
+
114
+    /**
115
+     * @NoAdminRequired
116
+     * @UseSession
117
+     *
118
+     * @return RedirectResponse
119
+     */
120
+    public function logout() {
121
+        $loginToken = $this->request->getCookie('nc_token');
122
+        if (!is_null($loginToken)) {
123
+            $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
124
+        }
125
+        $this->userSession->logout();
126
+
127
+        $response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
128
+            'core.login.showLoginForm',
129
+            ['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
130
+        ));
131
+
132
+        $this->session->set('clearingExecutionContexts', '1');
133
+        $this->session->close();
134
+
135
+        if (!$this->request->isUserAgent([Request::USER_AGENT_CHROME, Request::USER_AGENT_ANDROID_MOBILE_CHROME])) {
136
+            $response->addHeader('Clear-Site-Data', '"cache", "storage"');
137
+        }
138
+
139
+        return $response;
140
+    }
141
+
142
+    /**
143
+     * @PublicPage
144
+     * @NoCSRFRequired
145
+     * @UseSession
146
+     *
147
+     * @param string $user
148
+     * @param string $redirect_url
149
+     *
150
+     * @return TemplateResponse|RedirectResponse
151
+     */
152
+    public function showLoginForm(string $user = null, string $redirect_url = null): Http\Response {
153
+        if ($this->userSession->isLoggedIn()) {
154
+            return new RedirectResponse(OC_Util::getDefaultPageUrl());
155
+        }
156
+
157
+        $loginMessages = $this->session->get('loginMessages');
158
+        if (is_array($loginMessages)) {
159
+            list($errors, $messages) = $loginMessages;
160
+            $this->initialStateService->provideInitialState('core', 'loginMessages', $messages);
161
+            $this->initialStateService->provideInitialState('core', 'loginErrors', $errors);
162
+        }
163
+        $this->session->remove('loginMessages');
164
+
165
+        if ($user !== null && $user !== '') {
166
+            $this->initialStateService->provideInitialState('core', 'loginUsername', $user);
167
+        } else {
168
+            $this->initialStateService->provideInitialState('core', 'loginUsername', '');
169
+        }
170
+
171
+        $this->initialStateService->provideInitialState(
172
+            'core',
173
+            'loginAutocomplete',
174
+            $this->config->getSystemValue('login_form_autocomplete', true) === true
175
+        );
176
+
177
+        if (!empty($redirect_url)) {
178
+            [$url, ] = explode('?', $redirect_url);
179
+            if ($url !== $this->urlGenerator->linkToRoute('core.login.logout')) {
180
+                $this->initialStateService->provideInitialState('core', 'loginRedirectUrl', $redirect_url);
181
+            }
182
+        }
183
+
184
+        $this->initialStateService->provideInitialState(
185
+            'core',
186
+            'loginThrottleDelay',
187
+            $this->throttler->getDelay($this->request->getRemoteAddress())
188
+        );
189
+
190
+        $this->setPasswordResetInitialState($user);
191
+
192
+        $this->initialStateService->provideInitialState('core', 'webauthn-available', $this->webAuthnManager->isWebAuthnAvailable());
193
+
194
+        // OpenGraph Support: http://ogp.me/
195
+        Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
196
+        Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
197
+        Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
198
+        Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
199
+        Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
200
+        Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
201
+
202
+        $parameters = [
203
+            'alt_login' => OC_App::getAlternativeLogIns(),
204
+        ];
205
+        return new TemplateResponse(
206
+            $this->appName, 'login', $parameters, 'guest'
207
+        );
208
+    }
209
+
210
+    /**
211
+     * Sets the password reset state
212
+     *
213
+     * @param string $username
214
+     */
215
+    private function setPasswordResetInitialState(?string $username): void {
216
+        if ($username !== null && $username !== '') {
217
+            $user = $this->userManager->get($username);
218
+        } else {
219
+            $user = null;
220
+        }
221
+
222
+        $passwordLink = $this->config->getSystemValue('lost_password_link', '');
223
+
224
+        $this->initialStateService->provideInitialState(
225
+            'core',
226
+            'loginResetPasswordLink',
227
+            $passwordLink
228
+        );
229
+
230
+        $this->initialStateService->provideInitialState(
231
+            'core',
232
+            'loginCanResetPassword',
233
+            $this->canResetPassword($passwordLink, $user)
234
+        );
235
+    }
236
+
237
+    /**
238
+     * @param string|null $passwordLink
239
+     * @param IUser|null $user
240
+     *
241
+     * Users may not change their passwords if:
242
+     * - The account is disabled
243
+     * - The backend doesn't support password resets
244
+     * - The password reset function is disabled
245
+     *
246
+     * @return bool
247
+     */
248
+    private function canResetPassword(?string $passwordLink, ?IUser $user): bool {
249
+        if ($passwordLink === 'disabled') {
250
+            return false;
251
+        }
252
+
253
+        if (!$passwordLink && $user !== null) {
254
+            return $user->canChangePassword();
255
+        }
256
+
257
+        if ($user !== null && $user->isEnabled() === false) {
258
+            return false;
259
+        }
260
+
261
+        return true;
262
+    }
263
+
264
+    private function generateRedirect(?string $redirectUrl): RedirectResponse {
265
+        if ($redirectUrl !== null && $this->userSession->isLoggedIn()) {
266
+            $location = $this->urlGenerator->getAbsoluteURL($redirectUrl);
267
+            // Deny the redirect if the URL contains a @
268
+            // This prevents unvalidated redirects like ?redirect_url=:[email protected]
269
+            if (strpos($location, '@') === false) {
270
+                return new RedirectResponse($location);
271
+            }
272
+        }
273
+        return new RedirectResponse(OC_Util::getDefaultPageUrl());
274
+    }
275
+
276
+    /**
277
+     * @PublicPage
278
+     * @UseSession
279
+     * @NoCSRFRequired
280
+     * @BruteForceProtection(action=login)
281
+     *
282
+     * @param string $user
283
+     * @param string $password
284
+     * @param string $redirect_url
285
+     * @param string $timezone
286
+     * @param string $timezone_offset
287
+     *
288
+     * @return RedirectResponse
289
+     */
290
+    public function tryLogin(string $user,
291
+                                string $password,
292
+                                string $redirect_url = null,
293
+                                string $timezone = '',
294
+                                string $timezone_offset = ''): RedirectResponse {
295
+        // If the user is already logged in and the CSRF check does not pass then
296
+        // simply redirect the user to the correct page as required. This is the
297
+        // case when an user has already logged-in, in another tab.
298
+        if (!$this->request->passesCSRFCheck()) {
299
+            return $this->generateRedirect($redirect_url);
300
+        }
301
+
302
+        $data = new LoginData(
303
+            $this->request,
304
+            trim($user),
305
+            $password,
306
+            $redirect_url,
307
+            $timezone,
308
+            $timezone_offset
309
+        );
310
+        $result = $this->loginChain->process($data);
311
+        if (!$result->isSuccess()) {
312
+            return $this->createLoginFailedResponse(
313
+                $data->getUsername(),
314
+                $user,
315
+                $redirect_url,
316
+                $result->getErrorMessage()
317
+            );
318
+        }
319
+
320
+        if ($result->getRedirectUrl() !== null) {
321
+            return new RedirectResponse($result->getRedirectUrl());
322
+        }
323
+        return $this->generateRedirect($redirect_url);
324
+    }
325
+
326
+    /**
327
+     * Creates a login failed response.
328
+     *
329
+     * @param string $user
330
+     * @param string $originalUser
331
+     * @param string $redirect_url
332
+     * @param string $loginMessage
333
+     *
334
+     * @return RedirectResponse
335
+     */
336
+    private function createLoginFailedResponse(
337
+        $user, $originalUser, $redirect_url, string $loginMessage) {
338
+        // Read current user and append if possible we need to
339
+        // return the unmodified user otherwise we will leak the login name
340
+        $args = $user !== null ? ['user' => $originalUser] : [];
341
+        if ($redirect_url !== null) {
342
+            $args['redirect_url'] = $redirect_url;
343
+        }
344
+        $response = new RedirectResponse(
345
+            $this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
346
+        );
347
+        $response->throttle(['user' => substr($user, 0, 64)]);
348
+        $this->session->set('loginMessages', [
349
+            [$loginMessage], []
350
+        ]);
351
+        return $response;
352
+    }
353
+
354
+    /**
355
+     * @NoAdminRequired
356
+     * @UseSession
357
+     * @BruteForceProtection(action=sudo)
358
+     *
359
+     * @param string $password
360
+     *
361
+     * @return DataResponse
362
+     * @license GNU AGPL version 3 or any later version
363
+     *
364
+     */
365
+    public function confirmPassword($password) {
366
+        $loginName = $this->userSession->getLoginName();
367
+        $loginResult = $this->userManager->checkPassword($loginName, $password);
368
+        if ($loginResult === false) {
369
+            $response = new DataResponse([], Http::STATUS_FORBIDDEN);
370
+            $response->throttle();
371
+            return $response;
372
+        }
373
+
374
+        $confirmTimestamp = time();
375
+        $this->session->set('last-password-confirm', $confirmTimestamp);
376
+        return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
377
+    }
378 378
 }
Please login to merge, or discard this patch.