You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LoginController.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@owncloud.com>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Thomas Müller <thomas.mueller@tmit.eu>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Core\Controller;
  27. use OC\Authentication\TwoFactorAuth\Manager;
  28. use OC\Security\Bruteforce\Throttler;
  29. use OC\User\Session;
  30. use OC_App;
  31. use OC_Util;
  32. use OCP\AppFramework\Controller;
  33. use OCP\AppFramework\Http;
  34. use OCP\AppFramework\Http\DataResponse;
  35. use OCP\AppFramework\Http\RedirectResponse;
  36. use OCP\AppFramework\Http\TemplateResponse;
  37. use OCP\Authentication\TwoFactorAuth\IProvider;
  38. use OCP\IConfig;
  39. use OCP\IRequest;
  40. use OCP\ISession;
  41. use OCP\IURLGenerator;
  42. use OCP\IUser;
  43. use OCP\IUserManager;
  44. use OCP\IUserSession;
  45. class LoginController extends Controller {
  46. /** @var IUserManager */
  47. private $userManager;
  48. /** @var IConfig */
  49. private $config;
  50. /** @var ISession */
  51. private $session;
  52. /** @var IUserSession|Session */
  53. private $userSession;
  54. /** @var IURLGenerator */
  55. private $urlGenerator;
  56. /** @var Manager */
  57. private $twoFactorManager;
  58. /** @var Throttler */
  59. private $throttler;
  60. /**
  61. * @param string $appName
  62. * @param IRequest $request
  63. * @param IUserManager $userManager
  64. * @param IConfig $config
  65. * @param ISession $session
  66. * @param IUserSession $userSession
  67. * @param IURLGenerator $urlGenerator
  68. * @param Manager $twoFactorManager
  69. * @param Throttler $throttler
  70. */
  71. function __construct($appName,
  72. IRequest $request,
  73. IUserManager $userManager,
  74. IConfig $config,
  75. ISession $session,
  76. IUserSession $userSession,
  77. IURLGenerator $urlGenerator,
  78. Manager $twoFactorManager,
  79. Throttler $throttler) {
  80. parent::__construct($appName, $request);
  81. $this->userManager = $userManager;
  82. $this->config = $config;
  83. $this->session = $session;
  84. $this->userSession = $userSession;
  85. $this->urlGenerator = $urlGenerator;
  86. $this->twoFactorManager = $twoFactorManager;
  87. $this->throttler = $throttler;
  88. }
  89. /**
  90. * @NoAdminRequired
  91. * @UseSession
  92. *
  93. * @return RedirectResponse
  94. */
  95. public function logout() {
  96. $loginToken = $this->request->getCookie('oc_token');
  97. if (!is_null($loginToken)) {
  98. $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
  99. }
  100. $this->userSession->logout();
  101. return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
  102. }
  103. /**
  104. * @PublicPage
  105. * @NoCSRFRequired
  106. * @UseSession
  107. *
  108. * @param string $user
  109. * @param string $redirect_url
  110. * @param string $remember_login
  111. *
  112. * @return TemplateResponse|RedirectResponse
  113. */
  114. public function showLoginForm($user, $redirect_url, $remember_login) {
  115. if ($this->userSession->isLoggedIn()) {
  116. return new RedirectResponse(OC_Util::getDefaultPageUrl());
  117. }
  118. $parameters = array();
  119. $loginMessages = $this->session->get('loginMessages');
  120. $errors = [];
  121. $messages = [];
  122. if (is_array($loginMessages)) {
  123. list($errors, $messages) = $loginMessages;
  124. }
  125. $this->session->remove('loginMessages');
  126. foreach ($errors as $value) {
  127. $parameters[$value] = true;
  128. }
  129. $parameters['messages'] = $messages;
  130. if (!is_null($user) && $user !== '') {
  131. $parameters['loginName'] = $user;
  132. $parameters['user_autofocus'] = false;
  133. } else {
  134. $parameters['loginName'] = '';
  135. $parameters['user_autofocus'] = true;
  136. }
  137. if (!empty($redirect_url)) {
  138. $parameters['redirect_url'] = $redirect_url;
  139. }
  140. $parameters['canResetPassword'] = true;
  141. $parameters['resetPasswordLink'] = $this->config->getSystemValue('lost_password_link', '');
  142. if (!$parameters['resetPasswordLink']) {
  143. if (!is_null($user) && $user !== '') {
  144. $userObj = $this->userManager->get($user);
  145. if ($userObj instanceof IUser) {
  146. $parameters['canResetPassword'] = $userObj->canChangePassword();
  147. }
  148. }
  149. }
  150. $parameters['alt_login'] = OC_App::getAlternativeLogIns();
  151. $parameters['rememberLoginAllowed'] = OC_Util::rememberLoginAllowed();
  152. $parameters['rememberLoginState'] = !empty($remember_login) ? $remember_login : 0;
  153. if (!is_null($user) && $user !== '') {
  154. $parameters['loginName'] = $user;
  155. $parameters['user_autofocus'] = false;
  156. } else {
  157. $parameters['loginName'] = '';
  158. $parameters['user_autofocus'] = true;
  159. }
  160. return new TemplateResponse(
  161. $this->appName, 'login', $parameters, 'guest'
  162. );
  163. }
  164. /**
  165. * @param string $redirectUrl
  166. * @return RedirectResponse
  167. */
  168. private function generateRedirect($redirectUrl) {
  169. if (!is_null($redirectUrl) && $this->userSession->isLoggedIn()) {
  170. $location = $this->urlGenerator->getAbsoluteURL(urldecode($redirectUrl));
  171. // Deny the redirect if the URL contains a @
  172. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  173. if (strpos($location, '@') === false) {
  174. return new RedirectResponse($location);
  175. }
  176. }
  177. return new RedirectResponse(OC_Util::getDefaultPageUrl());
  178. }
  179. /**
  180. * @PublicPage
  181. * @UseSession
  182. * @NoCSRFRequired
  183. *
  184. * @param string $user
  185. * @param string $password
  186. * @param string $redirect_url
  187. * @param boolean $remember_login
  188. * @param string $timezone
  189. * @param string $timezone_offset
  190. * @return RedirectResponse
  191. */
  192. public function tryLogin($user, $password, $redirect_url, $remember_login = false, $timezone = '', $timezone_offset = '') {
  193. $currentDelay = $this->throttler->getDelay($this->request->getRemoteAddress());
  194. $this->throttler->sleepDelay($this->request->getRemoteAddress());
  195. // If the user is already logged in and the CSRF check does not pass then
  196. // simply redirect the user to the correct page as required. This is the
  197. // case when an user has already logged-in, in another tab.
  198. if(!$this->request->passesCSRFCheck()) {
  199. return $this->generateRedirect($redirect_url);
  200. }
  201. $originalUser = $user;
  202. // TODO: Add all the insane error handling
  203. /* @var $loginResult IUser */
  204. $loginResult = $this->userManager->checkPassword($user, $password);
  205. if ($loginResult === false) {
  206. $users = $this->userManager->getByEmail($user);
  207. // we only allow login by email if unique
  208. if (count($users) === 1) {
  209. $user = $users[0]->getUID();
  210. $loginResult = $this->userManager->checkPassword($user, $password);
  211. }
  212. }
  213. if ($loginResult === false) {
  214. $this->throttler->registerAttempt('login', $this->request->getRemoteAddress(), ['user' => $originalUser]);
  215. if($currentDelay === 0) {
  216. $this->throttler->sleepDelay($this->request->getRemoteAddress());
  217. }
  218. $this->session->set('loginMessages', [
  219. ['invalidpassword'], []
  220. ]);
  221. // Read current user and append if possible - we need to return the unmodified user otherwise we will leak the login name
  222. $args = !is_null($user) ? ['user' => $originalUser] : [];
  223. return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
  224. }
  225. // TODO: remove password checks from above and let the user session handle failures
  226. // requires https://github.com/owncloud/core/pull/24616
  227. $this->userSession->login($user, $password);
  228. $this->userSession->createSessionToken($this->request, $loginResult->getUID(), $user, $password, (int)$remember_login);
  229. // User has successfully logged in, now remove the password reset link, when it is available
  230. $this->config->deleteUserValue($loginResult->getUID(), 'core', 'lostpassword');
  231. $this->session->set('last-password-confirm', $loginResult->getLastLogin());
  232. if ($timezone_offset !== '') {
  233. $this->config->setUserValue($loginResult->getUID(), 'core', 'timezone', $timezone);
  234. $this->session->set('timezone', $timezone_offset);
  235. }
  236. if ($this->twoFactorManager->isTwoFactorAuthenticated($loginResult)) {
  237. $this->twoFactorManager->prepareTwoFactorLogin($loginResult, $remember_login);
  238. $providers = $this->twoFactorManager->getProviders($loginResult);
  239. if (count($providers) === 1) {
  240. // Single provider, hence we can redirect to that provider's challenge page directly
  241. /* @var $provider IProvider */
  242. $provider = array_pop($providers);
  243. $url = 'core.TwoFactorChallenge.showChallenge';
  244. $urlParams = [
  245. 'challengeProviderId' => $provider->getId(),
  246. ];
  247. } else {
  248. $url = 'core.TwoFactorChallenge.selectChallenge';
  249. $urlParams = [];
  250. }
  251. if (!is_null($redirect_url)) {
  252. $urlParams['redirect_url'] = $redirect_url;
  253. }
  254. return new RedirectResponse($this->urlGenerator->linkToRoute($url, $urlParams));
  255. }
  256. if ($remember_login) {
  257. $this->userSession->createRememberMeToken($loginResult);
  258. }
  259. return $this->generateRedirect($redirect_url);
  260. }
  261. /**
  262. * @NoAdminRequired
  263. * @UseSession
  264. *
  265. * @license GNU AGPL version 3 or any later version
  266. *
  267. * @param string $password
  268. * @return DataResponse
  269. */
  270. public function confirmPassword($password) {
  271. $currentDelay = $this->throttler->getDelay($this->request->getRemoteAddress());
  272. $this->throttler->sleepDelay($this->request->getRemoteAddress());
  273. $user = $this->userSession->getUser();
  274. if (!$user instanceof IUser) {
  275. return new DataResponse([], Http::STATUS_UNAUTHORIZED);
  276. }
  277. $loginResult = $this->userManager->checkPassword($user->getUID(), $password);
  278. if ($loginResult === false) {
  279. $this->throttler->registerAttempt('sudo', $this->request->getRemoteAddress(), ['user' => $user->getUID()]);
  280. if ($currentDelay === 0) {
  281. $this->throttler->sleepDelay($this->request->getRemoteAddress());
  282. }
  283. return new DataResponse([], Http::STATUS_FORBIDDEN);
  284. }
  285. $confirmTimestamp = time();
  286. $this->session->set('last-password-confirm', $confirmTimestamp);
  287. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  288. }
  289. }