1
0

LoginController.php 14 KB

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