OC_User.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Aldo "xoen" Giambelluca <xoen@xoen.org>
  6. * @author Andreas Fischer <bantu@owncloud.com>
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bartek Przybylski <bart.p.pl@gmail.com>
  9. * @author Björn Schießle <bjoern@schiessle.org>
  10. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  11. * @author Georg Ehrke <oc.list@georgehrke.com>
  12. * @author Jakob Sack <mail@jakobsack.de>
  13. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  14. * @author Lukas Reschke <lukas@statuscode.ch>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author shkdee <louis.traynard@m4x.org>
  20. * @author Thomas Müller <thomas.mueller@tmit.eu>
  21. * @author Vincent Petry <vincent@nextcloud.com>
  22. *
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. use OC\Authentication\Token\IProvider;
  39. use OC\User\LoginException;
  40. use OCP\Authentication\Exceptions\InvalidTokenException;
  41. use OCP\Authentication\Exceptions\WipeTokenException;
  42. use OCP\EventDispatcher\IEventDispatcher;
  43. use OCP\IGroupManager;
  44. use OCP\ISession;
  45. use OCP\IUser;
  46. use OCP\IUserManager;
  47. use OCP\Server;
  48. use OCP\Session\Exceptions\SessionNotAvailableException;
  49. use OCP\User\Events\BeforeUserLoggedInEvent;
  50. use OCP\User\Events\UserLoggedInEvent;
  51. use Psr\Log\LoggerInterface;
  52. /**
  53. * This class provides wrapper methods for user management. Multiple backends are
  54. * supported. User management operations are delegated to the configured backend for
  55. * execution.
  56. *
  57. * Note that &run is deprecated and won't work anymore.
  58. *
  59. * Hooks provided:
  60. * pre_createUser(&run, uid, password)
  61. * post_createUser(uid, password)
  62. * pre_deleteUser(&run, uid)
  63. * post_deleteUser(uid)
  64. * pre_setPassword(&run, uid, password, recoveryPassword)
  65. * post_setPassword(uid, password, recoveryPassword)
  66. * pre_login(&run, uid, password)
  67. * post_login(uid)
  68. * logout()
  69. */
  70. class OC_User {
  71. private static $_usedBackends = [];
  72. private static $_setupedBackends = [];
  73. // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
  74. private static $incognitoMode = false;
  75. /**
  76. * Adds the backend to the list of used backends
  77. *
  78. * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
  79. * @return bool
  80. *
  81. * Set the User Authentication Module
  82. * @suppress PhanDeprecatedFunction
  83. */
  84. public static function useBackend($backend = 'database') {
  85. if ($backend instanceof \OCP\UserInterface) {
  86. self::$_usedBackends[get_class($backend)] = $backend;
  87. \OC::$server->getUserManager()->registerBackend($backend);
  88. } else {
  89. // You'll never know what happens
  90. if (null === $backend or !is_string($backend)) {
  91. $backend = 'database';
  92. }
  93. // Load backend
  94. switch ($backend) {
  95. case 'database':
  96. case 'mysql':
  97. case 'sqlite':
  98. Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']);
  99. self::$_usedBackends[$backend] = new \OC\User\Database();
  100. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  101. break;
  102. case 'dummy':
  103. self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
  104. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  105. break;
  106. default:
  107. Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']);
  108. $className = 'OC_USER_' . strtoupper($backend);
  109. self::$_usedBackends[$backend] = new $className();
  110. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  111. break;
  112. }
  113. }
  114. return true;
  115. }
  116. /**
  117. * remove all used backends
  118. */
  119. public static function clearBackends() {
  120. self::$_usedBackends = [];
  121. \OC::$server->getUserManager()->clearBackends();
  122. }
  123. /**
  124. * setup the configured backends in config.php
  125. * @suppress PhanDeprecatedFunction
  126. */
  127. public static function setupBackends() {
  128. OC_App::loadApps(['prelogin']);
  129. $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
  130. if (isset($backends['default']) && !$backends['default']) {
  131. // clear default backends
  132. self::clearBackends();
  133. }
  134. foreach ($backends as $i => $config) {
  135. if (!is_array($config)) {
  136. continue;
  137. }
  138. $class = $config['class'];
  139. $arguments = $config['arguments'];
  140. if (class_exists($class)) {
  141. if (!in_array($i, self::$_setupedBackends)) {
  142. // make a reflection object
  143. $reflectionObj = new ReflectionClass($class);
  144. // use Reflection to create a new instance, using the $args
  145. $backend = $reflectionObj->newInstanceArgs($arguments);
  146. self::useBackend($backend);
  147. self::$_setupedBackends[] = $i;
  148. } else {
  149. Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']);
  150. }
  151. } else {
  152. Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']);
  153. }
  154. }
  155. }
  156. /**
  157. * Try to login a user, assuming authentication
  158. * has already happened (e.g. via Single Sign On).
  159. *
  160. * Log in a user and regenerate a new session.
  161. *
  162. * @param \OCP\Authentication\IApacheBackend $backend
  163. * @return bool
  164. */
  165. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  166. $uid = $backend->getCurrentUserId();
  167. $run = true;
  168. OC_Hook::emit("OC_User", "pre_login", ["run" => &$run, "uid" => $uid, 'backend' => $backend]);
  169. if ($uid) {
  170. if (self::getUser() !== $uid) {
  171. self::setUserId($uid);
  172. $userSession = \OC::$server->getUserSession();
  173. /** @var IEventDispatcher $dispatcher */
  174. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  175. if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) {
  176. $message = \OC::$server->getL10N('lib')->t('User disabled');
  177. throw new LoginException($message);
  178. }
  179. $userSession->setLoginName($uid);
  180. $request = OC::$server->getRequest();
  181. $password = null;
  182. if ($backend instanceof \OCP\Authentication\IProvideUserSecretBackend) {
  183. $password = $backend->getCurrentUserSecret();
  184. }
  185. /** @var IEventDispatcher $dispatcher */
  186. $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend));
  187. $userSession->createSessionToken($request, $uid, $uid, $password);
  188. $userSession->createRememberMeToken($userSession->getUser());
  189. if (empty($password)) {
  190. $tokenProvider = \OC::$server->get(IProvider::class);
  191. try {
  192. $token = $tokenProvider->getToken($userSession->getSession()->getId());
  193. $token->setScope([
  194. 'password-unconfirmable' => true,
  195. 'filesystem' => true,
  196. ]);
  197. $tokenProvider->updateToken($token);
  198. } catch (InvalidTokenException|WipeTokenException|SessionNotAvailableException) {
  199. // swallow the exceptions as we do not deal with them here
  200. // simply skip updating the token when is it missing
  201. }
  202. }
  203. // setup the filesystem
  204. OC_Util::setupFS($uid);
  205. // first call the post_login hooks, the login-process needs to be
  206. // completed before we can safely create the users folder.
  207. // For example encryption needs to initialize the users keys first
  208. // before we can create the user folder with the skeleton files
  209. OC_Hook::emit(
  210. 'OC_User',
  211. 'post_login',
  212. [
  213. 'uid' => $uid,
  214. 'password' => $password,
  215. 'isTokenLogin' => false,
  216. ]
  217. );
  218. $dispatcher->dispatchTyped(new UserLoggedInEvent(
  219. \OC::$server->get(IUserManager::class)->get($uid),
  220. $uid,
  221. null,
  222. false)
  223. );
  224. //trigger creation of user home and /files folder
  225. \OC::$server->getUserFolder($uid);
  226. }
  227. return true;
  228. }
  229. return false;
  230. }
  231. /**
  232. * Verify with Apache whether user is authenticated.
  233. *
  234. * @return boolean|null
  235. * true: authenticated
  236. * false: not authenticated
  237. * null: not handled / no backend available
  238. */
  239. public static function handleApacheAuth() {
  240. $backend = self::findFirstActiveUsedBackend();
  241. if ($backend) {
  242. OC_App::loadApps();
  243. //setup extra user backends
  244. self::setupBackends();
  245. \OC::$server->getUserSession()->unsetMagicInCookie();
  246. return self::loginWithApache($backend);
  247. }
  248. return null;
  249. }
  250. /**
  251. * Sets user id for session and triggers emit
  252. *
  253. * @param string $uid
  254. */
  255. public static function setUserId($uid) {
  256. $userSession = \OC::$server->getUserSession();
  257. $userManager = \OC::$server->getUserManager();
  258. if ($user = $userManager->get($uid)) {
  259. $userSession->setUser($user);
  260. } else {
  261. \OC::$server->getSession()->set('user_id', $uid);
  262. }
  263. }
  264. /**
  265. * Check if the user is logged in, considers also the HTTP basic credentials
  266. *
  267. * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
  268. * @return bool
  269. */
  270. public static function isLoggedIn() {
  271. return \OC::$server->getUserSession()->isLoggedIn();
  272. }
  273. /**
  274. * set incognito mode, e.g. if a user wants to open a public link
  275. *
  276. * @param bool $status
  277. */
  278. public static function setIncognitoMode($status) {
  279. self::$incognitoMode = $status;
  280. }
  281. /**
  282. * get incognito mode status
  283. *
  284. * @return bool
  285. */
  286. public static function isIncognitoMode() {
  287. return self::$incognitoMode;
  288. }
  289. /**
  290. * Returns the current logout URL valid for the currently logged-in user
  291. *
  292. * @param \OCP\IURLGenerator $urlGenerator
  293. * @return string
  294. */
  295. public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
  296. $backend = self::findFirstActiveUsedBackend();
  297. if ($backend) {
  298. return $backend->getLogoutUrl();
  299. }
  300. $user = \OC::$server->getUserSession()->getUser();
  301. if ($user instanceof IUser) {
  302. $backend = $user->getBackend();
  303. if ($backend instanceof \OCP\User\Backend\ICustomLogout) {
  304. return $backend->getLogoutUrl();
  305. }
  306. }
  307. $logoutUrl = $urlGenerator->linkToRoute('core.login.logout');
  308. $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister());
  309. return $logoutUrl;
  310. }
  311. /**
  312. * Check if the user is an admin user
  313. *
  314. * @param string $uid uid of the admin
  315. * @return bool
  316. */
  317. public static function isAdminUser($uid) {
  318. $user = Server::get(IUserManager::class)->get($uid);
  319. $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID());
  320. return $isAdmin && self::$incognitoMode === false;
  321. }
  322. /**
  323. * get the user id of the user currently logged in.
  324. *
  325. * @return string|false uid or false
  326. */
  327. public static function getUser() {
  328. $uid = Server::get(ISession::class)?->get('user_id');
  329. if (!is_null($uid) && self::$incognitoMode === false) {
  330. return $uid;
  331. } else {
  332. return false;
  333. }
  334. }
  335. /**
  336. * Set password
  337. *
  338. * @param string $uid The username
  339. * @param string $password The new password
  340. * @param string $recoveryPassword for the encryption app to reset encryption keys
  341. * @return bool
  342. *
  343. * Change the password of a user
  344. */
  345. public static function setPassword($uid, $password, $recoveryPassword = null) {
  346. $user = \OC::$server->getUserManager()->get($uid);
  347. if ($user) {
  348. return $user->setPassword($password, $recoveryPassword);
  349. } else {
  350. return false;
  351. }
  352. }
  353. /**
  354. * @param string $uid The username
  355. * @return string
  356. *
  357. * returns the path to the users home directory
  358. * @deprecated Use \OC::$server->getUserManager->getHome()
  359. */
  360. public static function getHome($uid) {
  361. $user = \OC::$server->getUserManager()->get($uid);
  362. if ($user) {
  363. return $user->getHome();
  364. } else {
  365. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  366. }
  367. }
  368. /**
  369. * Get a list of all users display name
  370. *
  371. * @param string $search
  372. * @param int $limit
  373. * @param int $offset
  374. * @return array associative array with all display names (value) and corresponding uids (key)
  375. *
  376. * Get a list of all display names and user ids.
  377. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  378. */
  379. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  380. $displayNames = [];
  381. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  382. foreach ($users as $user) {
  383. $displayNames[$user->getUID()] = $user->getDisplayName();
  384. }
  385. return $displayNames;
  386. }
  387. /**
  388. * Returns the first active backend from self::$_usedBackends.
  389. *
  390. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  391. */
  392. private static function findFirstActiveUsedBackend() {
  393. foreach (self::$_usedBackends as $backend) {
  394. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  395. if ($backend->isSessionActive()) {
  396. return $backend;
  397. }
  398. }
  399. }
  400. return null;
  401. }
  402. }