LoginController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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\Token\IToken;
  35. use OC\Authentication\TwoFactorAuth\Manager;
  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\Authentication\TwoFactorAuth\IProvider;
  46. use OCP\Defaults;
  47. use OCP\IConfig;
  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 OC\Hooks\PublicEmitter;
  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 Manager */
  73. private $twoFactorManager;
  74. /** @var Defaults */
  75. private $defaults;
  76. /** @var Throttler */
  77. private $throttler;
  78. /**
  79. * @param string $appName
  80. * @param IRequest $request
  81. * @param IUserManager $userManager
  82. * @param IConfig $config
  83. * @param ISession $session
  84. * @param IUserSession $userSession
  85. * @param IURLGenerator $urlGenerator
  86. * @param ILogger $logger
  87. * @param Manager $twoFactorManager
  88. * @param Defaults $defaults
  89. * @param Throttler $throttler
  90. */
  91. public function __construct($appName,
  92. IRequest $request,
  93. IUserManager $userManager,
  94. IConfig $config,
  95. ISession $session,
  96. IUserSession $userSession,
  97. IURLGenerator $urlGenerator,
  98. ILogger $logger,
  99. Manager $twoFactorManager,
  100. Defaults $defaults,
  101. Throttler $throttler) {
  102. parent::__construct($appName, $request);
  103. $this->userManager = $userManager;
  104. $this->config = $config;
  105. $this->session = $session;
  106. $this->userSession = $userSession;
  107. $this->urlGenerator = $urlGenerator;
  108. $this->logger = $logger;
  109. $this->twoFactorManager = $twoFactorManager;
  110. $this->defaults = $defaults;
  111. $this->throttler = $throttler;
  112. }
  113. /**
  114. * @NoAdminRequired
  115. * @UseSession
  116. *
  117. * @return RedirectResponse
  118. */
  119. public function logout() {
  120. $loginToken = $this->request->getCookie('nc_token');
  121. if (!is_null($loginToken)) {
  122. $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
  123. }
  124. $this->userSession->logout();
  125. $response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
  126. 'core.login.showLoginForm',
  127. ['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
  128. ));
  129. $this->session->set('clearingExecutionContexts', '1');
  130. $this->session->close();
  131. $response->addHeader('Clear-Site-Data', '"cache", "storage", "executionContexts"');
  132. return $response;
  133. }
  134. /**
  135. * @PublicPage
  136. * @NoCSRFRequired
  137. * @UseSession
  138. *
  139. * @param string $user
  140. * @param string $redirect_url
  141. *
  142. * @return TemplateResponse|RedirectResponse
  143. */
  144. public function showLoginForm(string $user = null, string $redirect_url = null): Http\Response {
  145. if ($this->userSession->isLoggedIn()) {
  146. return new RedirectResponse(OC_Util::getDefaultPageUrl());
  147. }
  148. $parameters = array();
  149. $loginMessages = $this->session->get('loginMessages');
  150. $errors = [];
  151. $messages = [];
  152. if (is_array($loginMessages)) {
  153. list($errors, $messages) = $loginMessages;
  154. }
  155. $this->session->remove('loginMessages');
  156. foreach ($errors as $value) {
  157. $parameters[$value] = true;
  158. }
  159. $parameters['messages'] = $messages;
  160. if ($user !== null && $user !== '') {
  161. $parameters['loginName'] = $user;
  162. $parameters['user_autofocus'] = false;
  163. } else {
  164. $parameters['loginName'] = '';
  165. $parameters['user_autofocus'] = true;
  166. }
  167. $autocomplete = $this->config->getSystemValue('login_form_autocomplete', true);
  168. if ($autocomplete){
  169. $parameters['login_form_autocomplete'] = 'on';
  170. } else {
  171. $parameters['login_form_autocomplete'] = 'off';
  172. }
  173. if (!empty($redirect_url)) {
  174. $parameters['redirect_url'] = $redirect_url;
  175. }
  176. $parameters = $this->setPasswordResetParameters($user, $parameters);
  177. $parameters['alt_login'] = OC_App::getAlternativeLogIns();
  178. if ($user !== null && $user !== '') {
  179. $parameters['loginName'] = $user;
  180. $parameters['user_autofocus'] = false;
  181. } else {
  182. $parameters['loginName'] = '';
  183. $parameters['user_autofocus'] = true;
  184. }
  185. $parameters['throttle_delay'] = $this->throttler->getDelay($this->request->getRemoteAddress());
  186. // OpenGraph Support: http://ogp.me/
  187. Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  188. Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
  189. Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  190. Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
  191. Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
  192. Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
  193. return new TemplateResponse(
  194. $this->appName, 'login', $parameters, 'guest'
  195. );
  196. }
  197. /**
  198. * Sets the password reset params.
  199. *
  200. * Users may not change their passwords if:
  201. * - The account is disabled
  202. * - The backend doesn't support password resets
  203. * - The password reset function is disabled
  204. *
  205. * @param string $user
  206. * @param array $parameters
  207. * @return array
  208. */
  209. private function setPasswordResetParameters(
  210. string $user = null, array $parameters): array {
  211. if ($user !== null && $user !== '') {
  212. $userObj = $this->userManager->get($user);
  213. } else {
  214. $userObj = null;
  215. }
  216. $parameters['resetPasswordLink'] = $this->config
  217. ->getSystemValue('lost_password_link', '');
  218. if ($parameters['resetPasswordLink'] === 'disabled') {
  219. $parameters['canResetPassword'] = false;
  220. } else if (!$parameters['resetPasswordLink'] && $userObj !== null) {
  221. $parameters['canResetPassword'] = $userObj->canChangePassword();
  222. } else if ($userObj !== null && $userObj->isEnabled() === false) {
  223. $parameters['canResetPassword'] = false;
  224. } else {
  225. $parameters['canResetPassword'] = true;
  226. }
  227. return $parameters;
  228. }
  229. /**
  230. * @param string $redirectUrl
  231. * @return RedirectResponse
  232. */
  233. private function generateRedirect($redirectUrl) {
  234. if (!is_null($redirectUrl) && $this->userSession->isLoggedIn()) {
  235. $location = $this->urlGenerator->getAbsoluteURL(urldecode($redirectUrl));
  236. // Deny the redirect if the URL contains a @
  237. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  238. if (strpos($location, '@') === false) {
  239. return new RedirectResponse($location);
  240. }
  241. }
  242. return new RedirectResponse(OC_Util::getDefaultPageUrl());
  243. }
  244. /**
  245. * @PublicPage
  246. * @UseSession
  247. * @NoCSRFRequired
  248. * @BruteForceProtection(action=login)
  249. *
  250. * @param string $user
  251. * @param string $password
  252. * @param string $redirect_url
  253. * @param boolean $remember_login
  254. * @param string $timezone
  255. * @param string $timezone_offset
  256. * @return RedirectResponse
  257. */
  258. public function tryLogin($user, $password, $redirect_url, $remember_login = true, $timezone = '', $timezone_offset = '') {
  259. if(!is_string($user)) {
  260. throw new \InvalidArgumentException('Username must be string');
  261. }
  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. if ($this->userManager instanceof PublicEmitter) {
  269. $this->userManager->emit('\OC\User', 'preLogin', array($user, $password));
  270. }
  271. $originalUser = $user;
  272. $userObj = $this->userManager->get($user);
  273. if ($userObj !== null && $userObj->isEnabled() === false) {
  274. $this->logger->warning('Login failed: \''. $user . '\' disabled' .
  275. ' (Remote IP: \''. $this->request->getRemoteAddress(). '\')',
  276. ['app' => 'core']);
  277. return $this->createLoginFailedResponse($user, $originalUser,
  278. $redirect_url, self::LOGIN_MSG_USERDISABLED);
  279. }
  280. // TODO: Add all the insane error handling
  281. /* @var $loginResult IUser */
  282. $loginResult = $this->userManager->checkPasswordNoLogging($user, $password);
  283. if ($loginResult === false) {
  284. $users = $this->userManager->getByEmail($user);
  285. // we only allow login by email if unique
  286. if (count($users) === 1) {
  287. $previousUser = $user;
  288. $user = $users[0]->getUID();
  289. if($user !== $previousUser) {
  290. $loginResult = $this->userManager->checkPassword($user, $password);
  291. }
  292. }
  293. }
  294. if ($loginResult === false) {
  295. $this->logger->warning('Login failed: \''. $user .
  296. '\' (Remote IP: \''. $this->request->getRemoteAddress(). '\')',
  297. ['app' => 'core']);
  298. return $this->createLoginFailedResponse($user, $originalUser,
  299. $redirect_url, self::LOGIN_MSG_INVALIDPASSWORD);
  300. }
  301. // TODO: remove password checks from above and let the user session handle failures
  302. // requires https://github.com/owncloud/core/pull/24616
  303. $this->userSession->completeLogin($loginResult, ['loginName' => $user, 'password' => $password]);
  304. $tokenType = IToken::REMEMBER;
  305. if ((int)$this->config->getSystemValue('remember_login_cookie_lifetime', 60*60*24*15) === 0) {
  306. $remember_login = false;
  307. $tokenType = IToken::DO_NOT_REMEMBER;
  308. }
  309. $this->userSession->createSessionToken($this->request, $loginResult->getUID(), $user, $password, $tokenType);
  310. $this->userSession->updateTokens($loginResult->getUID(), $password);
  311. // User has successfully logged in, now remove the password reset link, when it is available
  312. $this->config->deleteUserValue($loginResult->getUID(), 'core', 'lostpassword');
  313. $this->session->set('last-password-confirm', $loginResult->getLastLogin());
  314. if ($timezone_offset !== '') {
  315. $this->config->setUserValue($loginResult->getUID(), 'core', 'timezone', $timezone);
  316. $this->session->set('timezone', $timezone_offset);
  317. }
  318. if ($this->twoFactorManager->isTwoFactorAuthenticated($loginResult)) {
  319. $this->twoFactorManager->prepareTwoFactorLogin($loginResult, $remember_login);
  320. $providers = $this->twoFactorManager->getProviderSet($loginResult)->getPrimaryProviders();
  321. if (count($providers) === 1) {
  322. // Single provider, hence we can redirect to that provider's challenge page directly
  323. /* @var $provider IProvider */
  324. $provider = array_pop($providers);
  325. $url = 'core.TwoFactorChallenge.showChallenge';
  326. $urlParams = [
  327. 'challengeProviderId' => $provider->getId(),
  328. ];
  329. } else {
  330. $url = 'core.TwoFactorChallenge.selectChallenge';
  331. $urlParams = [];
  332. }
  333. if (!is_null($redirect_url)) {
  334. $urlParams['redirect_url'] = $redirect_url;
  335. }
  336. return new RedirectResponse($this->urlGenerator->linkToRoute($url, $urlParams));
  337. }
  338. if ($remember_login) {
  339. $this->userSession->createRememberMeToken($loginResult);
  340. }
  341. return $this->generateRedirect($redirect_url);
  342. }
  343. /**
  344. * Creates a login failed response.
  345. *
  346. * @param string $user
  347. * @param string $originalUser
  348. * @param string $redirect_url
  349. * @param string $loginMessage
  350. * @return RedirectResponse
  351. */
  352. private function createLoginFailedResponse(
  353. $user, $originalUser, $redirect_url, string $loginMessage) {
  354. // Read current user and append if possible we need to
  355. // return the unmodified user otherwise we will leak the login name
  356. $args = !is_null($user) ? ['user' => $originalUser] : [];
  357. if (!is_null($redirect_url)) {
  358. $args['redirect_url'] = $redirect_url;
  359. }
  360. $response = new RedirectResponse(
  361. $this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
  362. );
  363. $response->throttle(['user' => substr($user, 0, 64)]);
  364. $this->session->set('loginMessages', [
  365. [$loginMessage], []
  366. ]);
  367. return $response;
  368. }
  369. /**
  370. * @NoAdminRequired
  371. * @UseSession
  372. * @BruteForceProtection(action=sudo)
  373. *
  374. * @license GNU AGPL version 3 or any later version
  375. *
  376. * @param string $password
  377. * @return DataResponse
  378. */
  379. public function confirmPassword($password) {
  380. $loginName = $this->userSession->getLoginName();
  381. $loginResult = $this->userManager->checkPassword($loginName, $password);
  382. if ($loginResult === false) {
  383. $response = new DataResponse([], Http::STATUS_FORBIDDEN);
  384. $response->throttle();
  385. return $response;
  386. }
  387. $confirmTimestamp = time();
  388. $this->session->set('last-password-confirm', $confirmTimestamp);
  389. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  390. }
  391. }