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.

Session.php 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017, Sandro Lutz <sandro.lutz@temparus.ch>
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Sandro Lutz <sandro.lutz@temparus.ch>
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  9. * @author Christoph Wurst <christoph@owncloud.com>
  10. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Robin Appelman <robin@icewind.nl>
  14. * @author Robin McCorkell <robin@mccorkell.me.uk>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. * @author Vincent Petry <pvince81@owncloud.com>
  17. * @author Felix Rupp <kontakt@felixrupp.com>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OC\User;
  35. use OC;
  36. use OC\Authentication\Exceptions\InvalidTokenException;
  37. use OC\Authentication\Exceptions\PasswordlessTokenException;
  38. use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
  39. use OC\Authentication\Token\IProvider;
  40. use OC\Authentication\Token\IToken;
  41. use OC\Hooks\Emitter;
  42. use OC_User;
  43. use OC_Util;
  44. use OCA\DAV\Connector\Sabre\Auth;
  45. use OCP\AppFramework\Utility\ITimeFactory;
  46. use OCP\IConfig;
  47. use OCP\IRequest;
  48. use OCP\ISession;
  49. use OCP\IUser;
  50. use OCP\IUserManager;
  51. use OCP\IUserSession;
  52. use OCP\Security\ISecureRandom;
  53. use OCP\Session\Exceptions\SessionNotAvailableException;
  54. use OCP\Util;
  55. use Symfony\Component\EventDispatcher\GenericEvent;
  56. /**
  57. * Class Session
  58. *
  59. * Hooks available in scope \OC\User:
  60. * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  61. * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  62. * - preDelete(\OC\User\User $user)
  63. * - postDelete(\OC\User\User $user)
  64. * - preCreateUser(string $uid, string $password)
  65. * - postCreateUser(\OC\User\User $user)
  66. * - preLogin(string $user, string $password)
  67. * - postLogin(\OC\User\User $user, string $password)
  68. * - preRememberedLogin(string $uid)
  69. * - postRememberedLogin(\OC\User\User $user)
  70. * - logout()
  71. * - postLogout()
  72. *
  73. * @package OC\User
  74. */
  75. class Session implements IUserSession, Emitter {
  76. /** @var IUserManager $manager */
  77. private $manager;
  78. /** @var ISession $session */
  79. private $session;
  80. /** @var ITimeFactory */
  81. private $timeFacory;
  82. /** @var IProvider */
  83. private $tokenProvider;
  84. /** @var IConfig */
  85. private $config;
  86. /** @var User $activeUser */
  87. protected $activeUser;
  88. /** @var ISecureRandom */
  89. private $random;
  90. /**
  91. * @param IUserManager $manager
  92. * @param ISession $session
  93. * @param ITimeFactory $timeFacory
  94. * @param IProvider $tokenProvider
  95. * @param IConfig $config
  96. * @param ISecureRandom $random
  97. */
  98. public function __construct(IUserManager $manager,
  99. ISession $session,
  100. ITimeFactory $timeFacory,
  101. $tokenProvider,
  102. IConfig $config,
  103. ISecureRandom $random) {
  104. $this->manager = $manager;
  105. $this->session = $session;
  106. $this->timeFacory = $timeFacory;
  107. $this->tokenProvider = $tokenProvider;
  108. $this->config = $config;
  109. $this->random = $random;
  110. }
  111. /**
  112. * @param IProvider $provider
  113. */
  114. public function setTokenProvider(IProvider $provider) {
  115. $this->tokenProvider = $provider;
  116. }
  117. /**
  118. * @param string $scope
  119. * @param string $method
  120. * @param callable $callback
  121. */
  122. public function listen($scope, $method, callable $callback) {
  123. $this->manager->listen($scope, $method, $callback);
  124. }
  125. /**
  126. * @param string $scope optional
  127. * @param string $method optional
  128. * @param callable $callback optional
  129. */
  130. public function removeListener($scope = null, $method = null, callable $callback = null) {
  131. $this->manager->removeListener($scope, $method, $callback);
  132. }
  133. /**
  134. * get the manager object
  135. *
  136. * @return Manager
  137. */
  138. public function getManager() {
  139. return $this->manager;
  140. }
  141. /**
  142. * get the session object
  143. *
  144. * @return ISession
  145. */
  146. public function getSession() {
  147. return $this->session;
  148. }
  149. /**
  150. * set the session object
  151. *
  152. * @param ISession $session
  153. */
  154. public function setSession(ISession $session) {
  155. if ($this->session instanceof ISession) {
  156. $this->session->close();
  157. }
  158. $this->session = $session;
  159. $this->activeUser = null;
  160. }
  161. /**
  162. * set the currently active user
  163. *
  164. * @param IUser|null $user
  165. */
  166. public function setUser($user) {
  167. if (is_null($user)) {
  168. $this->session->remove('user_id');
  169. } else {
  170. $this->session->set('user_id', $user->getUID());
  171. }
  172. $this->activeUser = $user;
  173. }
  174. /**
  175. * get the current active user
  176. *
  177. * @return IUser|null Current user, otherwise null
  178. */
  179. public function getUser() {
  180. // FIXME: This is a quick'n dirty work-around for the incognito mode as
  181. // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
  182. if (OC_User::isIncognitoMode()) {
  183. return null;
  184. }
  185. if (is_null($this->activeUser)) {
  186. $uid = $this->session->get('user_id');
  187. if (is_null($uid)) {
  188. return null;
  189. }
  190. $this->activeUser = $this->manager->get($uid);
  191. if (is_null($this->activeUser)) {
  192. return null;
  193. }
  194. $this->validateSession();
  195. }
  196. return $this->activeUser;
  197. }
  198. /**
  199. * Validate whether the current session is valid
  200. *
  201. * - For token-authenticated clients, the token validity is checked
  202. * - For browsers, the session token validity is checked
  203. */
  204. protected function validateSession() {
  205. $token = null;
  206. $appPassword = $this->session->get('app_password');
  207. if (is_null($appPassword)) {
  208. try {
  209. $token = $this->session->getId();
  210. } catch (SessionNotAvailableException $ex) {
  211. return;
  212. }
  213. } else {
  214. $token = $appPassword;
  215. }
  216. if (!$this->validateToken($token)) {
  217. // Session was invalidated
  218. $this->logout();
  219. }
  220. }
  221. /**
  222. * Checks whether the user is logged in
  223. *
  224. * @return bool if logged in
  225. */
  226. public function isLoggedIn() {
  227. $user = $this->getUser();
  228. if (is_null($user)) {
  229. return false;
  230. }
  231. return $user->isEnabled();
  232. }
  233. /**
  234. * set the login name
  235. *
  236. * @param string|null $loginName for the logged in user
  237. */
  238. public function setLoginName($loginName) {
  239. if (is_null($loginName)) {
  240. $this->session->remove('loginname');
  241. } else {
  242. $this->session->set('loginname', $loginName);
  243. }
  244. }
  245. /**
  246. * get the login name of the current user
  247. *
  248. * @return string
  249. */
  250. public function getLoginName() {
  251. if ($this->activeUser) {
  252. return $this->session->get('loginname');
  253. } else {
  254. $uid = $this->session->get('user_id');
  255. if ($uid) {
  256. $this->activeUser = $this->manager->get($uid);
  257. return $this->session->get('loginname');
  258. } else {
  259. return null;
  260. }
  261. }
  262. }
  263. /**
  264. * set the token id
  265. *
  266. * @param int|null $token that was used to log in
  267. */
  268. protected function setToken($token) {
  269. if ($token === null) {
  270. $this->session->remove('token-id');
  271. } else {
  272. $this->session->set('token-id', $token);
  273. }
  274. }
  275. /**
  276. * try to log in with the provided credentials
  277. *
  278. * @param string $uid
  279. * @param string $password
  280. * @return boolean|null
  281. * @throws LoginException
  282. */
  283. public function login($uid, $password) {
  284. $this->session->regenerateId();
  285. if ($this->validateToken($password, $uid)) {
  286. return $this->loginWithToken($password);
  287. }
  288. return $this->loginWithPassword($uid, $password);
  289. }
  290. /**
  291. * Tries to log in a client
  292. *
  293. * Checks token auth enforced
  294. * Checks 2FA enabled
  295. *
  296. * @param string $user
  297. * @param string $password
  298. * @param IRequest $request
  299. * @param OC\Security\Bruteforce\Throttler $throttler
  300. * @throws LoginException
  301. * @throws PasswordLoginForbiddenException
  302. * @return boolean
  303. */
  304. public function logClientIn($user,
  305. $password,
  306. IRequest $request,
  307. OC\Security\Bruteforce\Throttler $throttler) {
  308. $currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
  309. if ($this->manager instanceof PublicEmitter) {
  310. $this->manager->emit('\OC\User', 'preLogin', array($user, $password));
  311. }
  312. $isTokenPassword = $this->isTokenPassword($password);
  313. if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
  314. throw new PasswordLoginForbiddenException();
  315. }
  316. if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
  317. throw new PasswordLoginForbiddenException();
  318. }
  319. if (!$this->login($user, $password) ) {
  320. $users = $this->manager->getByEmail($user);
  321. if (count($users) === 1) {
  322. return $this->login($users[0]->getUID(), $password);
  323. }
  324. $throttler->registerAttempt('login', $request->getRemoteAddress(), ['uid' => $user]);
  325. if($currentDelay === 0) {
  326. $throttler->sleepDelay($request->getRemoteAddress(), 'login');
  327. }
  328. return false;
  329. }
  330. if ($isTokenPassword) {
  331. $this->session->set('app_password', $password);
  332. } else if($this->supportsCookies($request)) {
  333. // Password login, but cookies supported -> create (browser) session token
  334. $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
  335. }
  336. return true;
  337. }
  338. protected function supportsCookies(IRequest $request) {
  339. if (!is_null($request->getCookie('cookie_test'))) {
  340. return true;
  341. }
  342. setcookie('cookie_test', 'test', $this->timeFacory->getTime() + 3600);
  343. return false;
  344. }
  345. private function isTokenAuthEnforced() {
  346. return $this->config->getSystemValue('token_auth_enforced', false);
  347. }
  348. protected function isTwoFactorEnforced($username) {
  349. Util::emitHook(
  350. '\OCA\Files_Sharing\API\Server2Server',
  351. 'preLoginNameUsedAsUserName',
  352. array('uid' => &$username)
  353. );
  354. $user = $this->manager->get($username);
  355. if (is_null($user)) {
  356. $users = $this->manager->getByEmail($username);
  357. if (empty($users)) {
  358. return false;
  359. }
  360. if (count($users) !== 1) {
  361. return true;
  362. }
  363. $user = $users[0];
  364. }
  365. // DI not possible due to cyclic dependencies :'-/
  366. return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
  367. }
  368. /**
  369. * Check if the given 'password' is actually a device token
  370. *
  371. * @param string $password
  372. * @return boolean
  373. */
  374. public function isTokenPassword($password) {
  375. try {
  376. $this->tokenProvider->getToken($password);
  377. return true;
  378. } catch (InvalidTokenException $ex) {
  379. return false;
  380. }
  381. }
  382. protected function prepareUserLogin($firstTimeLogin) {
  383. // TODO: mock/inject/use non-static
  384. // Refresh the token
  385. \OC::$server->getCsrfTokenManager()->refreshToken();
  386. //we need to pass the user name, which may differ from login name
  387. $user = $this->getUser()->getUID();
  388. OC_Util::setupFS($user);
  389. if ($firstTimeLogin) {
  390. // TODO: lock necessary?
  391. //trigger creation of user home and /files folder
  392. $userFolder = \OC::$server->getUserFolder($user);
  393. // copy skeleton
  394. \OC_Util::copySkeleton($user, $userFolder);
  395. // trigger any other initialization
  396. \OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
  397. }
  398. }
  399. /**
  400. * Tries to login the user with HTTP Basic Authentication
  401. *
  402. * @todo do not allow basic auth if the user is 2FA enforced
  403. * @param IRequest $request
  404. * @param OC\Security\Bruteforce\Throttler $throttler
  405. * @return boolean if the login was successful
  406. */
  407. public function tryBasicAuthLogin(IRequest $request,
  408. OC\Security\Bruteforce\Throttler $throttler) {
  409. if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
  410. try {
  411. if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
  412. /**
  413. * Add DAV authenticated. This should in an ideal world not be
  414. * necessary but the iOS App reads cookies from anywhere instead
  415. * only the DAV endpoint.
  416. * This makes sure that the cookies will be valid for the whole scope
  417. * @see https://github.com/owncloud/core/issues/22893
  418. */
  419. $this->session->set(
  420. Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
  421. );
  422. // Set the last-password-confirm session to make the sudo mode work
  423. $this->session->set('last-password-confirm', $this->timeFacory->getTime());
  424. return true;
  425. }
  426. } catch (PasswordLoginForbiddenException $ex) {
  427. // Nothing to do
  428. }
  429. }
  430. return false;
  431. }
  432. /**
  433. * Log an user in via login name and password
  434. *
  435. * @param string $uid
  436. * @param string $password
  437. * @return boolean
  438. * @throws LoginException if an app canceld the login process or the user is not enabled
  439. */
  440. private function loginWithPassword($uid, $password) {
  441. $user = $this->manager->checkPassword($uid, $password);
  442. if ($user === false) {
  443. // Password check failed
  444. return false;
  445. }
  446. if ($user->isEnabled()) {
  447. $this->setUser($user);
  448. $this->setLoginName($uid);
  449. $this->setToken(null);
  450. $firstTimeLogin = $user->updateLastLoginTimestamp();
  451. $this->manager->emit('\OC\User', 'postLogin', [$user, $password]);
  452. if ($this->isLoggedIn()) {
  453. $this->prepareUserLogin($firstTimeLogin);
  454. return true;
  455. } else {
  456. // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
  457. $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
  458. throw new LoginException($message);
  459. }
  460. } else {
  461. // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
  462. $message = \OC::$server->getL10N('lib')->t('User disabled');
  463. throw new LoginException($message);
  464. }
  465. }
  466. /**
  467. * Log an user in with a given token (id)
  468. *
  469. * @param string $token
  470. * @return boolean
  471. * @throws LoginException if an app canceled the login process or the user is not enabled
  472. */
  473. private function loginWithToken($token) {
  474. try {
  475. $dbToken = $this->tokenProvider->getToken($token);
  476. } catch (InvalidTokenException $ex) {
  477. return false;
  478. }
  479. $uid = $dbToken->getUID();
  480. // When logging in with token, the password must be decrypted first before passing to login hook
  481. $password = '';
  482. try {
  483. $password = $this->tokenProvider->getPassword($dbToken, $token);
  484. } catch (PasswordlessTokenException $ex) {
  485. // Ignore and use empty string instead
  486. }
  487. $user = $this->manager->get($uid);
  488. if (is_null($user)) {
  489. // user does not exist
  490. return false;
  491. }
  492. if (!$user->isEnabled()) {
  493. // disabled users can not log in
  494. // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
  495. $message = \OC::$server->getL10N('lib')->t('User disabled');
  496. throw new LoginException($message);
  497. }
  498. //login
  499. $this->setUser($user);
  500. $this->setLoginName($dbToken->getLoginName());
  501. $this->setToken($dbToken->getId());
  502. \OC::$server->getLockdownManager()->setToken($dbToken);
  503. $this->manager->emit('\OC\User', 'postLogin', array($user, $password));
  504. if ($this->isLoggedIn()) {
  505. $this->prepareUserLogin(false); // token login cant be the first
  506. } else {
  507. // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
  508. $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
  509. throw new LoginException($message);
  510. }
  511. return true;
  512. }
  513. /**
  514. * Create a new session token for the given user credentials
  515. *
  516. * @param IRequest $request
  517. * @param string $uid user UID
  518. * @param string $loginName login name
  519. * @param string $password
  520. * @param int $remember
  521. * @return boolean
  522. */
  523. public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
  524. if (is_null($this->manager->get($uid))) {
  525. // User does not exist
  526. return false;
  527. }
  528. $name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
  529. try {
  530. $sessionId = $this->session->getId();
  531. $pwd = $this->getPassword($password);
  532. $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
  533. return true;
  534. } catch (SessionNotAvailableException $ex) {
  535. // This can happen with OCC, where a memory session is used
  536. // if a memory session is used, we shouldn't create a session token anyway
  537. return false;
  538. }
  539. }
  540. /**
  541. * Checks if the given password is a token.
  542. * If yes, the password is extracted from the token.
  543. * If no, the same password is returned.
  544. *
  545. * @param string $password either the login password or a device token
  546. * @return string|null the password or null if none was set in the token
  547. */
  548. private function getPassword($password) {
  549. if (is_null($password)) {
  550. // This is surely no token ;-)
  551. return null;
  552. }
  553. try {
  554. $token = $this->tokenProvider->getToken($password);
  555. try {
  556. return $this->tokenProvider->getPassword($token, $password);
  557. } catch (PasswordlessTokenException $ex) {
  558. return null;
  559. }
  560. } catch (InvalidTokenException $ex) {
  561. return $password;
  562. }
  563. }
  564. /**
  565. * @param IToken $dbToken
  566. * @param string $token
  567. * @return boolean
  568. */
  569. private function checkTokenCredentials(IToken $dbToken, $token) {
  570. // Check whether login credentials are still valid and the user was not disabled
  571. // This check is performed each 5 minutes
  572. $lastCheck = $dbToken->getLastCheck() ? : 0;
  573. $now = $this->timeFacory->getTime();
  574. if ($lastCheck > ($now - 60 * 5)) {
  575. // Checked performed recently, nothing to do now
  576. return true;
  577. }
  578. try {
  579. $pwd = $this->tokenProvider->getPassword($dbToken, $token);
  580. } catch (InvalidTokenException $ex) {
  581. // An invalid token password was used -> log user out
  582. return false;
  583. } catch (PasswordlessTokenException $ex) {
  584. // Token has no password
  585. if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
  586. $this->tokenProvider->invalidateToken($token);
  587. return false;
  588. }
  589. $dbToken->setLastCheck($now);
  590. return true;
  591. }
  592. if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false
  593. || (!is_null($this->activeUser) && !$this->activeUser->isEnabled())) {
  594. $this->tokenProvider->invalidateToken($token);
  595. // Password has changed or user was disabled -> log user out
  596. return false;
  597. }
  598. $dbToken->setLastCheck($now);
  599. return true;
  600. }
  601. /**
  602. * Check if the given token exists and performs password/user-enabled checks
  603. *
  604. * Invalidates the token if checks fail
  605. *
  606. * @param string $token
  607. * @param string $user login name
  608. * @return boolean
  609. */
  610. private function validateToken($token, $user = null) {
  611. try {
  612. $dbToken = $this->tokenProvider->getToken($token);
  613. } catch (InvalidTokenException $ex) {
  614. return false;
  615. }
  616. // Check if login names match
  617. if (!is_null($user) && $dbToken->getLoginName() !== $user) {
  618. // TODO: this makes it imposssible to use different login names on browser and client
  619. // e.g. login by e-mail 'user@example.com' on browser for generating the token will not
  620. // allow to use the client token with the login name 'user'.
  621. return false;
  622. }
  623. if (!$this->checkTokenCredentials($dbToken, $token)) {
  624. return false;
  625. }
  626. $this->tokenProvider->updateTokenActivity($dbToken);
  627. return true;
  628. }
  629. /**
  630. * Tries to login the user with auth token header
  631. *
  632. * @param IRequest $request
  633. * @todo check remember me cookie
  634. * @return boolean
  635. */
  636. public function tryTokenLogin(IRequest $request) {
  637. $authHeader = $request->getHeader('Authorization');
  638. if (strpos($authHeader, 'token ') === false) {
  639. // No auth header, let's try session id
  640. try {
  641. $token = $this->session->getId();
  642. } catch (SessionNotAvailableException $ex) {
  643. return false;
  644. }
  645. } else {
  646. $token = substr($authHeader, 6);
  647. }
  648. if (!$this->loginWithToken($token)) {
  649. return false;
  650. }
  651. if(!$this->validateToken($token)) {
  652. return false;
  653. }
  654. return true;
  655. }
  656. /**
  657. * perform login using the magic cookie (remember login)
  658. *
  659. * @param string $uid the username
  660. * @param string $currentToken
  661. * @param string $oldSessionId
  662. * @return bool
  663. */
  664. public function loginWithCookie($uid, $currentToken, $oldSessionId) {
  665. $this->session->regenerateId();
  666. $this->manager->emit('\OC\User', 'preRememberedLogin', array($uid));
  667. $user = $this->manager->get($uid);
  668. if (is_null($user)) {
  669. // user does not exist
  670. return false;
  671. }
  672. // get stored tokens
  673. $tokens = $this->config->getUserKeys($uid, 'login_token');
  674. // test cookies token against stored tokens
  675. if (!in_array($currentToken, $tokens, true)) {
  676. return false;
  677. }
  678. // replace successfully used token with a new one
  679. $this->config->deleteUserValue($uid, 'login_token', $currentToken);
  680. $newToken = $this->random->generate(32);
  681. $this->config->setUserValue($uid, 'login_token', $newToken, $this->timeFacory->getTime());
  682. try {
  683. $sessionId = $this->session->getId();
  684. $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
  685. } catch (SessionNotAvailableException $ex) {
  686. return false;
  687. } catch (InvalidTokenException $ex) {
  688. \OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
  689. return false;
  690. }
  691. $this->setMagicInCookie($user->getUID(), $newToken);
  692. $token = $this->tokenProvider->getToken($sessionId);
  693. //login
  694. $this->setUser($user);
  695. $this->setLoginName($token->getLoginName());
  696. $this->setToken($token->getId());
  697. $user->updateLastLoginTimestamp();
  698. $this->manager->emit('\OC\User', 'postRememberedLogin', [$user]);
  699. return true;
  700. }
  701. /**
  702. * @param IUser $user
  703. */
  704. public function createRememberMeToken(IUser $user) {
  705. $token = $this->random->generate(32);
  706. $this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFacory->getTime());
  707. $this->setMagicInCookie($user->getUID(), $token);
  708. }
  709. /**
  710. * logout the user from the session
  711. */
  712. public function logout() {
  713. $this->manager->emit('\OC\User', 'logout');
  714. $user = $this->getUser();
  715. if (!is_null($user)) {
  716. try {
  717. $this->tokenProvider->invalidateToken($this->session->getId());
  718. } catch (SessionNotAvailableException $ex) {
  719. }
  720. }
  721. $this->setUser(null);
  722. $this->setLoginName(null);
  723. $this->setToken(null);
  724. $this->unsetMagicInCookie();
  725. $this->session->clear();
  726. $this->manager->emit('\OC\User', 'postLogout');
  727. }
  728. /**
  729. * Set cookie value to use in next page load
  730. *
  731. * @param string $username username to be set
  732. * @param string $token
  733. */
  734. public function setMagicInCookie($username, $token) {
  735. $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
  736. $webRoot = \OC::$WEBROOT;
  737. if ($webRoot === '') {
  738. $webRoot = '/';
  739. }
  740. $expires = $this->timeFacory->getTime() + $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  741. setcookie('nc_username', $username, $expires, $webRoot, '', $secureCookie, true);
  742. setcookie('nc_token', $token, $expires, $webRoot, '', $secureCookie, true);
  743. try {
  744. setcookie('nc_session_id', $this->session->getId(), $expires, $webRoot, '', $secureCookie, true);
  745. } catch (SessionNotAvailableException $ex) {
  746. // ignore
  747. }
  748. }
  749. /**
  750. * Remove cookie for "remember username"
  751. */
  752. public function unsetMagicInCookie() {
  753. //TODO: DI for cookies and IRequest
  754. $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
  755. unset($_COOKIE['nc_username']); //TODO: DI
  756. unset($_COOKIE['nc_token']);
  757. unset($_COOKIE['nc_session_id']);
  758. setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  759. setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  760. setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  761. // old cookies might be stored under /webroot/ instead of /webroot
  762. // and Firefox doesn't like it!
  763. setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  764. setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  765. setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  766. }
  767. /**
  768. * Update password of the browser session token if there is one
  769. *
  770. * @param string $password
  771. */
  772. public function updateSessionTokenPassword($password) {
  773. try {
  774. $sessionId = $this->session->getId();
  775. $token = $this->tokenProvider->getToken($sessionId);
  776. $this->tokenProvider->setPassword($token, $sessionId, $password);
  777. } catch (SessionNotAvailableException $ex) {
  778. // Nothing to do
  779. } catch (InvalidTokenException $ex) {
  780. // Nothing to do
  781. }
  782. }
  783. }