LoginController.php 13 KB

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