LoginController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017, Sandro Lutz <sandro.lutz@temparus.ch>
  4. * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
  5. * @copyright Copyright (c) 2016, ownCloud, Inc.
  6. *
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Michael Weimann <mail@michael-weimann.eu>
  14. * @author Rayn0r <andrew@ilpss8.myfirewall.org>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OC\Core\Controller;
  33. use OC\AppFramework\Http\Request;
  34. use OC\Authentication\Login\Chain;
  35. use OC\Authentication\Login\LoginData;
  36. use OC\Authentication\WebAuthn\Manager as WebAuthnManager;
  37. use OC\Security\Bruteforce\Throttler;
  38. use OC\User\Session;
  39. use OC_App;
  40. use OCP\AppFramework\Controller;
  41. use OCP\AppFramework\Http;
  42. use OCP\AppFramework\Http\DataResponse;
  43. use OCP\AppFramework\Http\RedirectResponse;
  44. use OCP\AppFramework\Http\TemplateResponse;
  45. use OCP\Defaults;
  46. use OCP\IConfig;
  47. use OCP\IInitialStateService;
  48. use OCP\IL10N;
  49. use OCP\IRequest;
  50. use OCP\ISession;
  51. use OCP\IURLGenerator;
  52. use OCP\IUser;
  53. use OCP\IUserManager;
  54. use OCP\IUserSession;
  55. use OCP\Notification\IManager;
  56. use OCP\Util;
  57. class LoginController extends Controller {
  58. public const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
  59. public const LOGIN_MSG_USERDISABLED = 'userdisabled';
  60. private IUserManager $userManager;
  61. private IConfig $config;
  62. private ISession $session;
  63. /** @var IUserSession|Session */
  64. private $userSession;
  65. private IURLGenerator $urlGenerator;
  66. private Defaults $defaults;
  67. private Throttler $throttler;
  68. private Chain $loginChain;
  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. Chain $loginChain,
  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->loginChain = $loginChain;
  96. $this->initialStateService = $initialStateService;
  97. $this->webAuthnManager = $webAuthnManager;
  98. $this->manager = $manager;
  99. $this->l10n = $l10n;
  100. }
  101. /**
  102. * @NoAdminRequired
  103. * @UseSession
  104. *
  105. * @return RedirectResponse
  106. */
  107. public function logout() {
  108. $loginToken = $this->request->getCookie('nc_token');
  109. if (!is_null($loginToken)) {
  110. $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
  111. }
  112. $this->userSession->logout();
  113. $response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
  114. 'core.login.showLoginForm',
  115. ['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
  116. ));
  117. $this->session->set('clearingExecutionContexts', '1');
  118. $this->session->close();
  119. if (!$this->request->isUserAgent([Request::USER_AGENT_CHROME, Request::USER_AGENT_ANDROID_MOBILE_CHROME])) {
  120. $response->addHeader('Clear-Site-Data', '"cache", "storage"');
  121. }
  122. return $response;
  123. }
  124. /**
  125. * @PublicPage
  126. * @NoCSRFRequired
  127. * @UseSession
  128. *
  129. * @param string $user
  130. * @param string $redirect_url
  131. *
  132. * @return TemplateResponse|RedirectResponse
  133. */
  134. public function showLoginForm(string $user = null, string $redirect_url = null): Http\Response {
  135. if ($this->userSession->isLoggedIn()) {
  136. return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
  137. }
  138. $loginMessages = $this->session->get('loginMessages');
  139. if (!$this->manager->isFairUseOfFreePushService()) {
  140. if (!is_array($loginMessages)) {
  141. $loginMessages = [[], []];
  142. }
  143. $loginMessages[1][] = $this->l10n->t('This community release of Nextcloud is unsupported and push notifications are limited.');
  144. }
  145. if (is_array($loginMessages)) {
  146. [$errors, $messages] = $loginMessages;
  147. $this->initialStateService->provideInitialState('core', 'loginMessages', $messages);
  148. $this->initialStateService->provideInitialState('core', 'loginErrors', $errors);
  149. }
  150. $this->session->remove('loginMessages');
  151. if ($user !== null && $user !== '') {
  152. $this->initialStateService->provideInitialState('core', 'loginUsername', $user);
  153. } else {
  154. $this->initialStateService->provideInitialState('core', 'loginUsername', '');
  155. }
  156. $this->initialStateService->provideInitialState(
  157. 'core',
  158. 'loginAutocomplete',
  159. $this->config->getSystemValue('login_form_autocomplete', true) === true
  160. );
  161. if (!empty($redirect_url)) {
  162. [$url, ] = explode('?', $redirect_url);
  163. if ($url !== $this->urlGenerator->linkToRoute('core.login.logout')) {
  164. $this->initialStateService->provideInitialState('core', 'loginRedirectUrl', $redirect_url);
  165. }
  166. }
  167. $this->initialStateService->provideInitialState(
  168. 'core',
  169. 'loginThrottleDelay',
  170. $this->throttler->getDelay($this->request->getRemoteAddress())
  171. );
  172. $this->setPasswordResetInitialState($user);
  173. $this->initialStateService->provideInitialState('core', 'webauthn-available', $this->webAuthnManager->isWebAuthnAvailable());
  174. $this->initialStateService->provideInitialState('core', 'hideLoginForm', $this->config->getSystemValueBool('hide_login_form', false));
  175. // OpenGraph Support: http://ogp.me/
  176. Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  177. Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
  178. Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  179. Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
  180. Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
  181. Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
  182. $parameters = [
  183. 'alt_login' => OC_App::getAlternativeLogIns(),
  184. 'pageTitle' => $this->l10n->t('Login'),
  185. ];
  186. $this->initialStateService->provideInitialState('core', 'countAlternativeLogins', count($parameters['alt_login']));
  187. $this->initialStateService->provideInitialState('core', 'alternativeLogins', $parameters['alt_login']);
  188. return new TemplateResponse(
  189. $this->appName,
  190. 'login',
  191. $parameters,
  192. TemplateResponse::RENDER_AS_GUEST,
  193. );
  194. }
  195. /**
  196. * Sets the password reset state
  197. *
  198. * @param string $username
  199. */
  200. private function setPasswordResetInitialState(?string $username): void {
  201. if ($username !== null && $username !== '') {
  202. $user = $this->userManager->get($username);
  203. } else {
  204. $user = null;
  205. }
  206. $passwordLink = $this->config->getSystemValue('lost_password_link', '');
  207. $this->initialStateService->provideInitialState(
  208. 'core',
  209. 'loginResetPasswordLink',
  210. $passwordLink
  211. );
  212. $this->initialStateService->provideInitialState(
  213. 'core',
  214. 'loginCanResetPassword',
  215. $this->canResetPassword($passwordLink, $user)
  216. );
  217. }
  218. /**
  219. * @param string|null $passwordLink
  220. * @param IUser|null $user
  221. *
  222. * Users may not change their passwords if:
  223. * - The account is disabled
  224. * - The backend doesn't support password resets
  225. * - The password reset function is disabled
  226. *
  227. * @return bool
  228. */
  229. private function canResetPassword(?string $passwordLink, ?IUser $user): bool {
  230. if ($passwordLink === 'disabled') {
  231. return false;
  232. }
  233. if (!$passwordLink && $user !== null) {
  234. return $user->canChangePassword();
  235. }
  236. if ($user !== null && $user->isEnabled() === false) {
  237. return false;
  238. }
  239. return true;
  240. }
  241. private function generateRedirect(?string $redirectUrl): RedirectResponse {
  242. if ($redirectUrl !== null && $this->userSession->isLoggedIn()) {
  243. $location = $this->urlGenerator->getAbsoluteURL($redirectUrl);
  244. // Deny the redirect if the URL contains a @
  245. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  246. if (strpos($location, '@') === false) {
  247. return new RedirectResponse($location);
  248. }
  249. }
  250. return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
  251. }
  252. /**
  253. * @PublicPage
  254. * @UseSession
  255. * @NoCSRFRequired
  256. * @BruteForceProtection(action=login)
  257. *
  258. * @param string $user
  259. * @param string $password
  260. * @param string $redirect_url
  261. * @param string $timezone
  262. * @param string $timezone_offset
  263. *
  264. * @return RedirectResponse
  265. */
  266. public function tryLogin(string $user,
  267. string $password,
  268. string $redirect_url = null,
  269. string $timezone = '',
  270. string $timezone_offset = ''): RedirectResponse {
  271. // If the user is already logged in and the CSRF check does not pass then
  272. // simply redirect the user to the correct page as required. This is the
  273. // case when an user has already logged-in, in another tab.
  274. if (!$this->request->passesCSRFCheck()) {
  275. return $this->generateRedirect($redirect_url);
  276. }
  277. $data = new LoginData(
  278. $this->request,
  279. trim($user),
  280. $password,
  281. $redirect_url,
  282. $timezone,
  283. $timezone_offset
  284. );
  285. $result = $this->loginChain->process($data);
  286. if (!$result->isSuccess()) {
  287. return $this->createLoginFailedResponse(
  288. $data->getUsername(),
  289. $user,
  290. $redirect_url,
  291. $result->getErrorMessage()
  292. );
  293. }
  294. if ($result->getRedirectUrl() !== null) {
  295. return new RedirectResponse($result->getRedirectUrl());
  296. }
  297. return $this->generateRedirect($redirect_url);
  298. }
  299. /**
  300. * Creates a login failed response.
  301. *
  302. * @param string $user
  303. * @param string $originalUser
  304. * @param string $redirect_url
  305. * @param string $loginMessage
  306. *
  307. * @return RedirectResponse
  308. */
  309. private function createLoginFailedResponse(
  310. $user, $originalUser, $redirect_url, string $loginMessage) {
  311. // Read current user and append if possible we need to
  312. // return the unmodified user otherwise we will leak the login name
  313. $args = $user !== null ? ['user' => $originalUser, 'direct' => 1] : [];
  314. if ($redirect_url !== null) {
  315. $args['redirect_url'] = $redirect_url;
  316. }
  317. $response = new RedirectResponse(
  318. $this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
  319. );
  320. $response->throttle(['user' => substr($user, 0, 64)]);
  321. $this->session->set('loginMessages', [
  322. [$loginMessage], []
  323. ]);
  324. return $response;
  325. }
  326. /**
  327. * @NoAdminRequired
  328. * @UseSession
  329. * @BruteForceProtection(action=sudo)
  330. *
  331. * @license GNU AGPL version 3 or any later version
  332. *
  333. */
  334. public function confirmPassword(string $password): DataResponse {
  335. $loginName = $this->userSession->getLoginName();
  336. $loginResult = $this->userManager->checkPassword($loginName, $password);
  337. if ($loginResult === false) {
  338. $response = new DataResponse([], Http::STATUS_FORBIDDEN);
  339. $response->throttle();
  340. return $response;
  341. }
  342. $confirmTimestamp = time();
  343. $this->session->set('last-password-confirm', $confirmTimestamp);
  344. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  345. }
  346. }