LoginController.php 12 KB

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