You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LoginController.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2017, Sandro Lutz <sandro.lutz@temparus.ch>
  5. * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
  6. * @copyright Copyright (c) 2016, ownCloud, Inc.
  7. *
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author John Molakvoæ <skjnldsv@protonmail.com>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Michael Weimann <mail@michael-weimann.eu>
  15. * @author Rayn0r <andrew@ilpss8.myfirewall.org>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Kate Döen <kate.doeen@nextcloud.com>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OC\Core\Controller;
  35. use OC\AppFramework\Http\Request;
  36. use OC\Authentication\Login\Chain;
  37. use OC\Authentication\Login\LoginData;
  38. use OC\Authentication\WebAuthn\Manager as WebAuthnManager;
  39. use OC\User\Session;
  40. use OC_App;
  41. use OCP\AppFramework\Controller;
  42. use OCP\AppFramework\Http;
  43. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  44. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  45. use OCP\AppFramework\Http\Attribute\OpenAPI;
  46. use OCP\AppFramework\Http\Attribute\UseSession;
  47. use OCP\AppFramework\Http\DataResponse;
  48. use OCP\AppFramework\Http\RedirectResponse;
  49. use OCP\AppFramework\Http\TemplateResponse;
  50. use OCP\Defaults;
  51. use OCP\IConfig;
  52. use OCP\IInitialStateService;
  53. use OCP\IL10N;
  54. use OCP\IRequest;
  55. use OCP\ISession;
  56. use OCP\IURLGenerator;
  57. use OCP\IUser;
  58. use OCP\IUserManager;
  59. use OCP\Notification\IManager;
  60. use OCP\Security\Bruteforce\IThrottler;
  61. use OCP\Util;
  62. class LoginController extends Controller {
  63. public const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
  64. public const LOGIN_MSG_USERDISABLED = 'userdisabled';
  65. public const LOGIN_MSG_CSRFCHECKFAILED = 'csrfCheckFailed';
  66. public function __construct(
  67. ?string $appName,
  68. IRequest $request,
  69. private IUserManager $userManager,
  70. private IConfig $config,
  71. private ISession $session,
  72. private Session $userSession,
  73. private IURLGenerator $urlGenerator,
  74. private Defaults $defaults,
  75. private IThrottler $throttler,
  76. private IInitialStateService $initialStateService,
  77. private WebAuthnManager $webAuthnManager,
  78. private IManager $manager,
  79. private IL10N $l10n,
  80. ) {
  81. parent::__construct($appName, $request);
  82. }
  83. /**
  84. * @NoAdminRequired
  85. *
  86. * @return RedirectResponse
  87. */
  88. #[UseSession]
  89. #[FrontpageRoute(verb: 'GET', url: '/logout')]
  90. public function logout() {
  91. $loginToken = $this->request->getCookie('nc_token');
  92. if (!is_null($loginToken)) {
  93. $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
  94. }
  95. $this->userSession->logout();
  96. $response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
  97. 'core.login.showLoginForm',
  98. ['clear' => true] // this param the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
  99. ));
  100. $this->session->set('clearingExecutionContexts', '1');
  101. $this->session->close();
  102. if (
  103. $this->request->getServerProtocol() === 'https' &&
  104. !$this->request->isUserAgent([Request::USER_AGENT_CHROME, Request::USER_AGENT_ANDROID_MOBILE_CHROME])
  105. ) {
  106. $response->addHeader('Clear-Site-Data', '"cache", "storage"');
  107. }
  108. return $response;
  109. }
  110. /**
  111. * @PublicPage
  112. * @NoCSRFRequired
  113. *
  114. * @param string $user
  115. * @param string $redirect_url
  116. *
  117. * @return TemplateResponse|RedirectResponse
  118. */
  119. #[UseSession]
  120. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  121. #[FrontpageRoute(verb: 'GET', url: '/login')]
  122. public function showLoginForm(string $user = null, string $redirect_url = null): Http\Response {
  123. if ($this->userSession->isLoggedIn()) {
  124. return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
  125. }
  126. $loginMessages = $this->session->get('loginMessages');
  127. if (!$this->manager->isFairUseOfFreePushService()) {
  128. if (!is_array($loginMessages)) {
  129. $loginMessages = [[], []];
  130. }
  131. $loginMessages[1][] = $this->l10n->t('This community release of Nextcloud is unsupported and push notifications are limited.');
  132. }
  133. if (is_array($loginMessages)) {
  134. [$errors, $messages] = $loginMessages;
  135. $this->initialStateService->provideInitialState('core', 'loginMessages', $messages);
  136. $this->initialStateService->provideInitialState('core', 'loginErrors', $errors);
  137. }
  138. $this->session->remove('loginMessages');
  139. if ($user !== null && $user !== '') {
  140. $this->initialStateService->provideInitialState('core', 'loginUsername', $user);
  141. } else {
  142. $this->initialStateService->provideInitialState('core', 'loginUsername', '');
  143. }
  144. $this->initialStateService->provideInitialState(
  145. 'core',
  146. 'loginAutocomplete',
  147. $this->config->getSystemValue('login_form_autocomplete', true) === true
  148. );
  149. if (!empty($redirect_url)) {
  150. [$url, ] = explode('?', $redirect_url);
  151. if ($url !== $this->urlGenerator->linkToRoute('core.login.logout')) {
  152. $this->initialStateService->provideInitialState('core', 'loginRedirectUrl', $redirect_url);
  153. }
  154. }
  155. $this->initialStateService->provideInitialState(
  156. 'core',
  157. 'loginThrottleDelay',
  158. $this->throttler->getDelay($this->request->getRemoteAddress())
  159. );
  160. $this->setPasswordResetInitialState($user);
  161. $this->initialStateService->provideInitialState('core', 'webauthn-available', $this->webAuthnManager->isWebAuthnAvailable());
  162. $this->initialStateService->provideInitialState('core', 'hideLoginForm', $this->config->getSystemValueBool('hide_login_form', false));
  163. // OpenGraph Support: http://ogp.me/
  164. Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  165. Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
  166. Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  167. Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
  168. Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
  169. Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
  170. $parameters = [
  171. 'alt_login' => OC_App::getAlternativeLogIns(),
  172. 'pageTitle' => $this->l10n->t('Login'),
  173. ];
  174. $this->initialStateService->provideInitialState('core', 'countAlternativeLogins', count($parameters['alt_login']));
  175. $this->initialStateService->provideInitialState('core', 'alternativeLogins', $parameters['alt_login']);
  176. return new TemplateResponse(
  177. $this->appName,
  178. 'login',
  179. $parameters,
  180. TemplateResponse::RENDER_AS_GUEST,
  181. );
  182. }
  183. /**
  184. * Sets the password reset state
  185. *
  186. * @param string $username
  187. */
  188. private function setPasswordResetInitialState(?string $username): void {
  189. if ($username !== null && $username !== '') {
  190. $user = $this->userManager->get($username);
  191. } else {
  192. $user = null;
  193. }
  194. $passwordLink = $this->config->getSystemValueString('lost_password_link', '');
  195. $this->initialStateService->provideInitialState(
  196. 'core',
  197. 'loginResetPasswordLink',
  198. $passwordLink
  199. );
  200. $this->initialStateService->provideInitialState(
  201. 'core',
  202. 'loginCanResetPassword',
  203. $this->canResetPassword($passwordLink, $user)
  204. );
  205. }
  206. /**
  207. * @param string|null $passwordLink
  208. * @param IUser|null $user
  209. *
  210. * Users may not change their passwords if:
  211. * - The account is disabled
  212. * - The backend doesn't support password resets
  213. * - The password reset function is disabled
  214. *
  215. * @return bool
  216. */
  217. private function canResetPassword(?string $passwordLink, ?IUser $user): bool {
  218. if ($passwordLink === 'disabled') {
  219. return false;
  220. }
  221. if (!$passwordLink && $user !== null) {
  222. return $user->canChangePassword();
  223. }
  224. if ($user !== null && $user->isEnabled() === false) {
  225. return false;
  226. }
  227. return true;
  228. }
  229. private function generateRedirect(?string $redirectUrl): RedirectResponse {
  230. if ($redirectUrl !== null && $this->userSession->isLoggedIn()) {
  231. $location = $this->urlGenerator->getAbsoluteURL($redirectUrl);
  232. // Deny the redirect if the URL contains a @
  233. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  234. if (!str_contains($location, '@')) {
  235. return new RedirectResponse($location);
  236. }
  237. }
  238. return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
  239. }
  240. /**
  241. * @PublicPage
  242. * @NoCSRFRequired
  243. * @BruteForceProtection(action=login)
  244. *
  245. * @return RedirectResponse
  246. */
  247. #[UseSession]
  248. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  249. #[FrontpageRoute(verb: 'POST', url: '/login')]
  250. public function tryLogin(Chain $loginChain,
  251. string $user = '',
  252. string $password = '',
  253. string $redirect_url = null,
  254. string $timezone = '',
  255. string $timezone_offset = ''): RedirectResponse {
  256. if (!$this->request->passesCSRFCheck()) {
  257. if ($this->userSession->isLoggedIn()) {
  258. // If the user is already logged in and the CSRF check does not pass then
  259. // simply redirect the user to the correct page as required. This is the
  260. // case when a user has already logged-in, in another tab.
  261. return $this->generateRedirect($redirect_url);
  262. }
  263. // Clear any auth remnants like cookies to ensure a clean login
  264. // For the next attempt
  265. $this->userSession->logout();
  266. return $this->createLoginFailedResponse(
  267. $user,
  268. $user,
  269. $redirect_url,
  270. self::LOGIN_MSG_CSRFCHECKFAILED
  271. );
  272. }
  273. $data = new LoginData(
  274. $this->request,
  275. trim($user),
  276. $password,
  277. $redirect_url,
  278. $timezone,
  279. $timezone_offset
  280. );
  281. $result = $loginChain->process($data);
  282. if (!$result->isSuccess()) {
  283. return $this->createLoginFailedResponse(
  284. $data->getUsername(),
  285. $user,
  286. $redirect_url,
  287. $result->getErrorMessage()
  288. );
  289. }
  290. if ($result->getRedirectUrl() !== null) {
  291. return new RedirectResponse($result->getRedirectUrl());
  292. }
  293. return $this->generateRedirect($redirect_url);
  294. }
  295. /**
  296. * Creates a login failed response.
  297. *
  298. * @param string $user
  299. * @param string $originalUser
  300. * @param string $redirect_url
  301. * @param string $loginMessage
  302. *
  303. * @return RedirectResponse
  304. */
  305. private function createLoginFailedResponse(
  306. $user, $originalUser, $redirect_url, string $loginMessage) {
  307. // Read current user and append if possible we need to
  308. // return the unmodified user otherwise we will leak the login name
  309. $args = $user !== null ? ['user' => $originalUser, 'direct' => 1] : [];
  310. if ($redirect_url !== null) {
  311. $args['redirect_url'] = $redirect_url;
  312. }
  313. $response = new RedirectResponse(
  314. $this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
  315. );
  316. $response->throttle(['user' => substr($user, 0, 64)]);
  317. $this->session->set('loginMessages', [
  318. [$loginMessage], []
  319. ]);
  320. return $response;
  321. }
  322. /**
  323. * Confirm the user password
  324. *
  325. * @NoAdminRequired
  326. * @BruteForceProtection(action=sudo)
  327. *
  328. * @license GNU AGPL version 3 or any later version
  329. *
  330. * @param string $password The password of the user
  331. *
  332. * @return DataResponse<Http::STATUS_OK, array{lastLogin: int}, array{}>|DataResponse<Http::STATUS_FORBIDDEN, array<empty>, array{}>
  333. *
  334. * 200: Password confirmation succeeded
  335. * 403: Password confirmation failed
  336. */
  337. #[UseSession]
  338. #[NoCSRFRequired]
  339. #[FrontpageRoute(verb: 'POST', url: '/login/confirm')]
  340. public function confirmPassword(string $password): DataResponse {
  341. $loginName = $this->userSession->getLoginName();
  342. $loginResult = $this->userManager->checkPassword($loginName, $password);
  343. if ($loginResult === false) {
  344. $response = new DataResponse([], Http::STATUS_FORBIDDEN);
  345. $response->throttle(['loginName' => $loginName]);
  346. return $response;
  347. }
  348. $confirmTimestamp = time();
  349. $this->session->set('last-password-confirm', $confirmTimestamp);
  350. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'sudo', ['loginName' => $loginName]);
  351. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  352. }
  353. }