1
0

LoginController.php 13 KB

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