LoginController.php 14 KB

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