1
0

LoginController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Christoph Wurst <christoph@owncloud.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Julius Härtl <jus@bitgrid.net>
  11. * @author justin-sleep <justin@quarterfull.com>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Sandro Lutz <sandro.lutz@temparus.ch>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. * @author Ujjwal Bhardwaj <ujjwalb1996@gmail.com>
  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\Authentication\Login\Chain;
  35. use OC\Authentication\Login\LoginData;
  36. use OC\Authentication\TwoFactorAuth\Manager;
  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. const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
  59. 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. public function __construct(?string $appName,
  81. IRequest $request,
  82. IUserManager $userManager,
  83. IConfig $config,
  84. ISession $session,
  85. IUserSession $userSession,
  86. IURLGenerator $urlGenerator,
  87. ILogger $logger,
  88. Defaults $defaults,
  89. Throttler $throttler,
  90. Chain $loginChain,
  91. IInitialStateService $initialStateService) {
  92. parent::__construct($appName, $request);
  93. $this->userManager = $userManager;
  94. $this->config = $config;
  95. $this->session = $session;
  96. $this->userSession = $userSession;
  97. $this->urlGenerator = $urlGenerator;
  98. $this->logger = $logger;
  99. $this->defaults = $defaults;
  100. $this->throttler = $throttler;
  101. $this->loginChain = $loginChain;
  102. $this->initialStateService = $initialStateService;
  103. }
  104. /**
  105. * @NoAdminRequired
  106. * @UseSession
  107. *
  108. * @return RedirectResponse
  109. */
  110. public function logout() {
  111. $loginToken = $this->request->getCookie('nc_token');
  112. if (!is_null($loginToken)) {
  113. $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
  114. }
  115. $this->userSession->logout();
  116. $response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
  117. 'core.login.showLoginForm',
  118. ['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
  119. ));
  120. $this->session->set('clearingExecutionContexts', '1');
  121. $this->session->close();
  122. $response->addHeader('Clear-Site-Data', '"cache", "storage", "executionContexts"');
  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. $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. }