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 11KB

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