LoginController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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\Security\Bruteforce\Throttler;
  36. use OC\User\Session;
  37. use OC_App;
  38. use OC_Util;
  39. use OCP\AppFramework\Controller;
  40. use OCP\AppFramework\Http;
  41. use OCP\AppFramework\Http\DataResponse;
  42. use OCP\AppFramework\Http\RedirectResponse;
  43. use OCP\AppFramework\Http\TemplateResponse;
  44. use OCP\Defaults;
  45. use OCP\IConfig;
  46. use OCP\IInitialStateService;
  47. use OCP\ILogger;
  48. use OCP\IRequest;
  49. use OCP\ISession;
  50. use OCP\IURLGenerator;
  51. use OCP\IUser;
  52. use OCP\IUserManager;
  53. use OCP\IUserSession;
  54. use OCP\Util;
  55. class LoginController extends Controller {
  56. const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
  57. const LOGIN_MSG_USERDISABLED = 'userdisabled';
  58. /** @var IUserManager */
  59. private $userManager;
  60. /** @var IConfig */
  61. private $config;
  62. /** @var ISession */
  63. private $session;
  64. /** @var IUserSession|Session */
  65. private $userSession;
  66. /** @var IURLGenerator */
  67. private $urlGenerator;
  68. /** @var ILogger */
  69. private $logger;
  70. /** @var Defaults */
  71. private $defaults;
  72. /** @var Throttler */
  73. private $throttler;
  74. /** @var Chain */
  75. private $loginChain;
  76. /** @var IInitialStateService */
  77. private $initialStateService;
  78. public function __construct(?string $appName,
  79. IRequest $request,
  80. IUserManager $userManager,
  81. IConfig $config,
  82. ISession $session,
  83. IUserSession $userSession,
  84. IURLGenerator $urlGenerator,
  85. ILogger $logger,
  86. Defaults $defaults,
  87. Throttler $throttler,
  88. Chain $loginChain,
  89. IInitialStateService $initialStateService) {
  90. parent::__construct($appName, $request);
  91. $this->userManager = $userManager;
  92. $this->config = $config;
  93. $this->session = $session;
  94. $this->userSession = $userSession;
  95. $this->urlGenerator = $urlGenerator;
  96. $this->logger = $logger;
  97. $this->defaults = $defaults;
  98. $this->throttler = $throttler;
  99. $this->loginChain = $loginChain;
  100. $this->initialStateService = $initialStateService;
  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(OC_Util::getDefaultPageUrl());
  138. }
  139. $loginMessages = $this->session->get('loginMessages');
  140. if (is_array($loginMessages)) {
  141. list($errors, $messages) = $loginMessages;
  142. $this->initialStateService->provideInitialState('core', 'loginMessages', $messages);
  143. $this->initialStateService->provideInitialState('core', 'loginErrors', $errors);
  144. }
  145. $this->session->remove('loginMessages');
  146. if ($user !== null && $user !== '') {
  147. $this->initialStateService->provideInitialState('core', 'loginUsername', $user);
  148. } else {
  149. $this->initialStateService->provideInitialState('core', 'loginUsername', '');
  150. }
  151. $this->initialStateService->provideInitialState(
  152. 'core',
  153. 'loginAutocomplete',
  154. $this->config->getSystemValue('login_form_autocomplete', true) === true
  155. );
  156. if (!empty($redirect_url)) {
  157. $this->initialStateService->provideInitialState('core', 'loginRedirectUrl', $redirect_url);
  158. }
  159. $this->initialStateService->provideInitialState(
  160. 'core',
  161. 'loginThrottleDelay',
  162. $this->throttler->getDelay($this->request->getRemoteAddress())
  163. );
  164. $this->setPasswordResetInitialState($user);
  165. // OpenGraph Support: http://ogp.me/
  166. Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  167. Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
  168. Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  169. Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
  170. Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
  171. Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
  172. $parameters = [
  173. 'alt_login' => OC_App::getAlternativeLogIns(),
  174. ];
  175. return new TemplateResponse(
  176. $this->appName, 'login', $parameters, 'guest'
  177. );
  178. }
  179. /**
  180. * Sets the password reset state
  181. *
  182. * @param string $username
  183. */
  184. private function setPasswordResetInitialState(?string $username): void {
  185. if ($username !== null && $username !== '') {
  186. $user = $this->userManager->get($username);
  187. } else {
  188. $user = null;
  189. }
  190. $passwordLink = $this->config->getSystemValue('lost_password_link', '');
  191. $this->initialStateService->provideInitialState(
  192. 'core',
  193. 'loginResetPasswordLink',
  194. $passwordLink
  195. );
  196. $this->initialStateService->provideInitialState(
  197. 'core',
  198. 'loginCanResetPassword',
  199. $this->canResetPassword($passwordLink, $user)
  200. );
  201. }
  202. /**
  203. * @param string|null $passwordLink
  204. * @param IUser|null $user
  205. *
  206. * Users may not change their passwords if:
  207. * - The account is disabled
  208. * - The backend doesn't support password resets
  209. * - The password reset function is disabled
  210. *
  211. * @return bool
  212. */
  213. private function canResetPassword(?string $passwordLink, ?IUser $user): bool {
  214. if ($passwordLink === 'disabled') {
  215. return false;
  216. }
  217. if (!$passwordLink && $user !== null) {
  218. return $user->canChangePassword();
  219. }
  220. if ($user !== null && $user->isEnabled() === false) {
  221. return false;
  222. }
  223. return true;
  224. }
  225. private function generateRedirect(?string $redirectUrl): RedirectResponse {
  226. if ($redirectUrl !== null && $this->userSession->isLoggedIn()) {
  227. $location = $this->urlGenerator->getAbsoluteURL(urldecode($redirectUrl));
  228. // Deny the redirect if the URL contains a @
  229. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  230. if (strpos($location, '@') === false) {
  231. return new RedirectResponse($location);
  232. }
  233. }
  234. return new RedirectResponse(OC_Util::getDefaultPageUrl());
  235. }
  236. /**
  237. * @PublicPage
  238. * @UseSession
  239. * @NoCSRFRequired
  240. * @BruteForceProtection(action=login)
  241. *
  242. * @param string $user
  243. * @param string $password
  244. * @param string $redirect_url
  245. * @param string $timezone
  246. * @param string $timezone_offset
  247. *
  248. * @return RedirectResponse
  249. */
  250. public function tryLogin(string $user,
  251. string $password,
  252. string $redirect_url = null,
  253. string $timezone = '',
  254. string $timezone_offset = ''): RedirectResponse {
  255. // If the user is already logged in and the CSRF check does not pass then
  256. // simply redirect the user to the correct page as required. This is the
  257. // case when an user has already logged-in, in another tab.
  258. if (!$this->request->passesCSRFCheck()) {
  259. return $this->generateRedirect($redirect_url);
  260. }
  261. $data = new LoginData(
  262. $this->request,
  263. trim($user),
  264. $password,
  265. $redirect_url,
  266. $timezone,
  267. $timezone_offset
  268. );
  269. $result = $this->loginChain->process($data);
  270. if (!$result->isSuccess()) {
  271. return $this->createLoginFailedResponse(
  272. $data->getUsername(),
  273. $user,
  274. $redirect_url,
  275. $result->getErrorMessage()
  276. );
  277. }
  278. if ($result->getRedirectUrl() !== null) {
  279. return new RedirectResponse($result->getRedirectUrl());
  280. }
  281. return $this->generateRedirect($redirect_url);
  282. }
  283. /**
  284. * Creates a login failed response.
  285. *
  286. * @param string $user
  287. * @param string $originalUser
  288. * @param string $redirect_url
  289. * @param string $loginMessage
  290. *
  291. * @return RedirectResponse
  292. */
  293. private function createLoginFailedResponse(
  294. $user, $originalUser, $redirect_url, string $loginMessage) {
  295. // Read current user and append if possible we need to
  296. // return the unmodified user otherwise we will leak the login name
  297. $args = $user !== null ? ['user' => $originalUser] : [];
  298. if ($redirect_url !== null) {
  299. $args['redirect_url'] = $redirect_url;
  300. }
  301. $response = new RedirectResponse(
  302. $this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
  303. );
  304. $response->throttle(['user' => substr($user, 0, 64)]);
  305. $this->session->set('loginMessages', [
  306. [$loginMessage], []
  307. ]);
  308. return $response;
  309. }
  310. /**
  311. * @NoAdminRequired
  312. * @UseSession
  313. * @BruteForceProtection(action=sudo)
  314. *
  315. * @param string $password
  316. *
  317. * @return DataResponse
  318. * @license GNU AGPL version 3 or any later version
  319. *
  320. */
  321. public function confirmPassword($password) {
  322. $loginName = $this->userSession->getLoginName();
  323. $loginResult = $this->userManager->checkPassword($loginName, $password);
  324. if ($loginResult === false) {
  325. $response = new DataResponse([], Http::STATUS_FORBIDDEN);
  326. $response->throttle();
  327. return $response;
  328. }
  329. $confirmTimestamp = time();
  330. $this->session->set('last-password-confirm', $confirmTimestamp);
  331. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  332. }
  333. }