OC_User.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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\User\LoginException;
  39. use OCP\EventDispatcher\IEventDispatcher;
  40. use OCP\ILogger;
  41. use OCP\IUserManager;
  42. use OCP\User\Events\BeforeUserLoggedInEvent;
  43. use OCP\User\Events\UserLoggedInEvent;
  44. /**
  45. * This class provides wrapper methods for user management. Multiple backends are
  46. * supported. User management operations are delegated to the configured backend for
  47. * execution.
  48. *
  49. * Note that &run is deprecated and won't work anymore.
  50. *
  51. * Hooks provided:
  52. * pre_createUser(&run, uid, password)
  53. * post_createUser(uid, password)
  54. * pre_deleteUser(&run, uid)
  55. * post_deleteUser(uid)
  56. * pre_setPassword(&run, uid, password, recoveryPassword)
  57. * post_setPassword(uid, password, recoveryPassword)
  58. * pre_login(&run, uid, password)
  59. * post_login(uid)
  60. * logout()
  61. */
  62. class OC_User {
  63. private static $_usedBackends = [];
  64. private static $_setupedBackends = [];
  65. // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
  66. private static $incognitoMode = false;
  67. /**
  68. * Adds the backend to the list of used backends
  69. *
  70. * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
  71. * @return bool
  72. *
  73. * Set the User Authentication Module
  74. * @suppress PhanDeprecatedFunction
  75. */
  76. public static function useBackend($backend = 'database') {
  77. if ($backend instanceof \OCP\UserInterface) {
  78. self::$_usedBackends[get_class($backend)] = $backend;
  79. \OC::$server->getUserManager()->registerBackend($backend);
  80. } else {
  81. // You'll never know what happens
  82. if (null === $backend or !is_string($backend)) {
  83. $backend = 'database';
  84. }
  85. // Load backend
  86. switch ($backend) {
  87. case 'database':
  88. case 'mysql':
  89. case 'sqlite':
  90. \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
  91. self::$_usedBackends[$backend] = new \OC\User\Database();
  92. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  93. break;
  94. case 'dummy':
  95. self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
  96. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  97. break;
  98. default:
  99. \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
  100. $className = 'OC_USER_' . strtoupper($backend);
  101. self::$_usedBackends[$backend] = new $className();
  102. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  103. break;
  104. }
  105. }
  106. return true;
  107. }
  108. /**
  109. * remove all used backends
  110. */
  111. public static function clearBackends() {
  112. self::$_usedBackends = [];
  113. \OC::$server->getUserManager()->clearBackends();
  114. }
  115. /**
  116. * setup the configured backends in config.php
  117. * @suppress PhanDeprecatedFunction
  118. */
  119. public static function setupBackends() {
  120. OC_App::loadApps(['prelogin']);
  121. $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
  122. if (isset($backends['default']) && !$backends['default']) {
  123. // clear default backends
  124. self::clearBackends();
  125. }
  126. foreach ($backends as $i => $config) {
  127. if (!is_array($config)) {
  128. continue;
  129. }
  130. $class = $config['class'];
  131. $arguments = $config['arguments'];
  132. if (class_exists($class)) {
  133. if (array_search($i, self::$_setupedBackends) === false) {
  134. // make a reflection object
  135. $reflectionObj = new ReflectionClass($class);
  136. // use Reflection to create a new instance, using the $args
  137. $backend = $reflectionObj->newInstanceArgs($arguments);
  138. self::useBackend($backend);
  139. self::$_setupedBackends[] = $i;
  140. } else {
  141. \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
  142. }
  143. } else {
  144. \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
  145. }
  146. }
  147. }
  148. /**
  149. * Try to login a user, assuming authentication
  150. * has already happened (e.g. via Single Sign On).
  151. *
  152. * Log in a user and regenerate a new session.
  153. *
  154. * @param \OCP\Authentication\IApacheBackend $backend
  155. * @return bool
  156. */
  157. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  158. $uid = $backend->getCurrentUserId();
  159. $run = true;
  160. OC_Hook::emit("OC_User", "pre_login", ["run" => &$run, "uid" => $uid, 'backend' => $backend]);
  161. if ($uid) {
  162. if (self::getUser() !== $uid) {
  163. self::setUserId($uid);
  164. $userSession = \OC::$server->getUserSession();
  165. /** @var IEventDispatcher $dispatcher */
  166. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  167. if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) {
  168. $message = \OC::$server->getL10N('lib')->t('User disabled');
  169. throw new LoginException($message);
  170. }
  171. $userSession->setLoginName($uid);
  172. $request = OC::$server->getRequest();
  173. $password = null;
  174. if ($backend instanceof \OCP\Authentication\IProvideUserSecretBackend) {
  175. $password = $backend->getCurrentUserSecret();
  176. }
  177. /** @var IEventDispatcher $dispatcher */
  178. $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend));
  179. $userSession->createSessionToken($request, $uid, $uid, $password);
  180. $userSession->createRememberMeToken($userSession->getUser());
  181. // setup the filesystem
  182. OC_Util::setupFS($uid);
  183. // first call the post_login hooks, the login-process needs to be
  184. // completed before we can safely create the users folder.
  185. // For example encryption needs to initialize the users keys first
  186. // before we can create the user folder with the skeleton files
  187. OC_Hook::emit(
  188. 'OC_User',
  189. 'post_login',
  190. [
  191. 'uid' => $uid,
  192. 'password' => $password,
  193. 'isTokenLogin' => false,
  194. ]
  195. );
  196. $dispatcher->dispatchTyped(new UserLoggedInEvent(
  197. \OC::$server->get(IUserManager::class)->get($uid),
  198. $uid,
  199. null,
  200. false)
  201. );
  202. //trigger creation of user home and /files folder
  203. \OC::$server->getUserFolder($uid);
  204. }
  205. return true;
  206. }
  207. return false;
  208. }
  209. /**
  210. * Verify with Apache whether user is authenticated.
  211. *
  212. * @return boolean|null
  213. * true: authenticated
  214. * false: not authenticated
  215. * null: not handled / no backend available
  216. */
  217. public static function handleApacheAuth() {
  218. $backend = self::findFirstActiveUsedBackend();
  219. if ($backend) {
  220. OC_App::loadApps();
  221. //setup extra user backends
  222. self::setupBackends();
  223. \OC::$server->getUserSession()->unsetMagicInCookie();
  224. return self::loginWithApache($backend);
  225. }
  226. return null;
  227. }
  228. /**
  229. * Sets user id for session and triggers emit
  230. *
  231. * @param string $uid
  232. */
  233. public static function setUserId($uid) {
  234. $userSession = \OC::$server->getUserSession();
  235. $userManager = \OC::$server->getUserManager();
  236. if ($user = $userManager->get($uid)) {
  237. $userSession->setUser($user);
  238. } else {
  239. \OC::$server->getSession()->set('user_id', $uid);
  240. }
  241. }
  242. /**
  243. * Check if the user is logged in, considers also the HTTP basic credentials
  244. *
  245. * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
  246. * @return bool
  247. */
  248. public static function isLoggedIn() {
  249. return \OC::$server->getUserSession()->isLoggedIn();
  250. }
  251. /**
  252. * set incognito mode, e.g. if a user wants to open a public link
  253. *
  254. * @param bool $status
  255. */
  256. public static function setIncognitoMode($status) {
  257. self::$incognitoMode = $status;
  258. }
  259. /**
  260. * get incognito mode status
  261. *
  262. * @return bool
  263. */
  264. public static function isIncognitoMode() {
  265. return self::$incognitoMode;
  266. }
  267. /**
  268. * Returns the current logout URL valid for the currently logged-in user
  269. *
  270. * @param \OCP\IURLGenerator $urlGenerator
  271. * @return string
  272. */
  273. public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
  274. $backend = self::findFirstActiveUsedBackend();
  275. if ($backend) {
  276. return $backend->getLogoutUrl();
  277. }
  278. $user = \OC::$server->getUserSession()->getUser();
  279. if ($user instanceof \OCP\IUser) {
  280. $backend = $user->getBackend();
  281. if ($backend instanceof \OCP\User\Backend\ICustomLogout) {
  282. return $backend->getLogoutUrl();
  283. }
  284. }
  285. $logoutUrl = $urlGenerator->linkToRoute('core.login.logout');
  286. $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister());
  287. return $logoutUrl;
  288. }
  289. /**
  290. * Check if the user is an admin user
  291. *
  292. * @param string $uid uid of the admin
  293. * @return bool
  294. */
  295. public static function isAdminUser($uid) {
  296. $group = \OC::$server->getGroupManager()->get('admin');
  297. $user = \OC::$server->getUserManager()->get($uid);
  298. if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
  299. return true;
  300. }
  301. return false;
  302. }
  303. /**
  304. * get the user id of the user currently logged in.
  305. *
  306. * @return string|false uid or false
  307. */
  308. public static function getUser() {
  309. $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
  310. if (!is_null($uid) && self::$incognitoMode === false) {
  311. return $uid;
  312. } else {
  313. return false;
  314. }
  315. }
  316. /**
  317. * Set password
  318. *
  319. * @param string $uid The username
  320. * @param string $password The new password
  321. * @param string $recoveryPassword for the encryption app to reset encryption keys
  322. * @return bool
  323. *
  324. * Change the password of a user
  325. */
  326. public static function setPassword($uid, $password, $recoveryPassword = null) {
  327. $user = \OC::$server->getUserManager()->get($uid);
  328. if ($user) {
  329. return $user->setPassword($password, $recoveryPassword);
  330. } else {
  331. return false;
  332. }
  333. }
  334. /**
  335. * @param string $uid The username
  336. * @return string
  337. *
  338. * returns the path to the users home directory
  339. * @deprecated Use \OC::$server->getUserManager->getHome()
  340. */
  341. public static function getHome($uid) {
  342. $user = \OC::$server->getUserManager()->get($uid);
  343. if ($user) {
  344. return $user->getHome();
  345. } else {
  346. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  347. }
  348. }
  349. /**
  350. * Get a list of all users display name
  351. *
  352. * @param string $search
  353. * @param int $limit
  354. * @param int $offset
  355. * @return array associative array with all display names (value) and corresponding uids (key)
  356. *
  357. * Get a list of all display names and user ids.
  358. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  359. */
  360. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  361. $displayNames = [];
  362. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  363. foreach ($users as $user) {
  364. $displayNames[$user->getUID()] = $user->getDisplayName();
  365. }
  366. return $displayNames;
  367. }
  368. /**
  369. * Returns the first active backend from self::$_usedBackends.
  370. *
  371. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  372. */
  373. private static function findFirstActiveUsedBackend() {
  374. foreach (self::$_usedBackends as $backend) {
  375. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  376. if ($backend->isSessionActive()) {
  377. return $backend;
  378. }
  379. }
  380. }
  381. return null;
  382. }
  383. }