You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LoginController.php 12KB

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