LoginController.php 13 KB

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