LoginController.php 11 KB

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