LoginController.php 12 KB

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