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