user.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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 Bart Visscher <bartv@thisnet.nl>
  10. * @author Björn Schießle <bjoern@schiessle.org>
  11. * @author Christoph Wurst <christoph@owncloud.com>
  12. * @author Georg Ehrke <georg@owncloud.com>
  13. * @author Jakob Sack <mail@jakobsack.de>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Morris Jobke <hey@morrisjobke.de>
  17. * @author Robin Appelman <robin@icewind.nl>
  18. * @author Robin McCorkell <robin@mccorkell.me.uk>
  19. * @author Roeland Jago Douma <roeland@famdouma.nl>
  20. * @author shkdee <louis.traynard@m4x.org>
  21. * @author Thomas Müller <thomas.mueller@tmit.eu>
  22. * @author Tom Needham <tom@owncloud.com>
  23. *
  24. * @license AGPL-3.0
  25. *
  26. * This code is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License, version 3,
  28. * as published by the Free Software Foundation.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License, version 3,
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>
  37. *
  38. */
  39. /**
  40. * This class provides wrapper methods for user management. Multiple backends are
  41. * supported. User management operations are delegated to the configured backend for
  42. * execution.
  43. *
  44. * Note that &run is deprecated and won't work anymore.
  45. *
  46. * Hooks provided:
  47. * pre_createUser(&run, uid, password)
  48. * post_createUser(uid, password)
  49. * pre_deleteUser(&run, uid)
  50. * post_deleteUser(uid)
  51. * pre_setPassword(&run, uid, password, recoveryPassword)
  52. * post_setPassword(uid, password, recoveryPassword)
  53. * pre_login(&run, uid, password)
  54. * post_login(uid)
  55. * logout()
  56. */
  57. class OC_User {
  58. /**
  59. * @return \OC\User\Session
  60. */
  61. public static function getUserSession() {
  62. return OC::$server->getUserSession();
  63. }
  64. private static $_usedBackends = array();
  65. private static $_setupedBackends = array();
  66. // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
  67. private static $incognitoMode = false;
  68. /**
  69. * Adds the backend to the list of used backends
  70. *
  71. * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
  72. * @return bool
  73. *
  74. * Set the User Authentication Module
  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 . '.', \OCP\Util::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 . '.', \OCP\Util::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 = array();
  113. \OC::$server->getUserManager()->clearBackends();
  114. }
  115. /**
  116. * setup the configured backends in config.php
  117. */
  118. public static function setupBackends() {
  119. OC_App::loadApps(['prelogin']);
  120. $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
  121. if (isset($backends['default']) && !$backends['default']) {
  122. // clear default backends
  123. self::clearBackends();
  124. }
  125. foreach ($backends as $i => $config) {
  126. if (!is_array($config)) {
  127. continue;
  128. }
  129. $class = $config['class'];
  130. $arguments = $config['arguments'];
  131. if (class_exists($class)) {
  132. if (array_search($i, self::$_setupedBackends) === false) {
  133. // make a reflection object
  134. $reflectionObj = new ReflectionClass($class);
  135. // use Reflection to create a new instance, using the $args
  136. $backend = $reflectionObj->newInstanceArgs($arguments);
  137. self::useBackend($backend);
  138. self::$_setupedBackends[] = $i;
  139. } else {
  140. \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
  141. }
  142. } else {
  143. \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
  144. }
  145. }
  146. }
  147. /**
  148. * Try to login a user using the magic cookie (remember login)
  149. *
  150. * @deprecated use \OCP\IUserSession::loginWithCookie()
  151. * @param string $uid The username of the user to log in
  152. * @param string $token
  153. * @param string $oldSessionId
  154. * @return bool
  155. */
  156. public static function loginWithCookie($uid, $token, $oldSessionId) {
  157. return self::getUserSession()->loginWithCookie($uid, $token, $oldSessionId);
  158. }
  159. /**
  160. * Try to login a user, assuming authentication
  161. * has already happened (e.g. via Single Sign On).
  162. *
  163. * Log in a user and regenerate a new session.
  164. *
  165. * @param \OCP\Authentication\IApacheBackend $backend
  166. * @return bool
  167. */
  168. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  169. $uid = $backend->getCurrentUserId();
  170. $run = true;
  171. OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
  172. if ($uid) {
  173. if (self::getUser() !== $uid) {
  174. self::setUserId($uid);
  175. $setUidAsDisplayName = true;
  176. if($backend instanceof \OCP\UserInterface
  177. && $backend->implementsActions(OC_User_Backend::GET_DISPLAYNAME)) {
  178. $backendDisplayName = $backend->getDisplayName($uid);
  179. if(is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
  180. $setUidAsDisplayName = false;
  181. }
  182. }
  183. if($setUidAsDisplayName) {
  184. self::setDisplayName($uid);
  185. }
  186. self::getUserSession()->setLoginName($uid);
  187. $request = OC::$server->getRequest();
  188. self::getUserSession()->createSessionToken($request, $uid, $uid);
  189. // setup the filesystem
  190. OC_Util::setupFS($uid);
  191. // first call the post_login hooks, the login-process needs to be
  192. // completed before we can safely create the users folder.
  193. // For example encryption needs to initialize the users keys first
  194. // before we can create the user folder with the skeleton files
  195. OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
  196. //trigger creation of user home and /files folder
  197. \OC::$server->getUserFolder($uid);
  198. }
  199. return true;
  200. }
  201. return false;
  202. }
  203. /**
  204. * Verify with Apache whether user is authenticated.
  205. *
  206. * @return boolean|null
  207. * true: authenticated
  208. * false: not authenticated
  209. * null: not handled / no backend available
  210. */
  211. public static function handleApacheAuth() {
  212. $backend = self::findFirstActiveUsedBackend();
  213. if ($backend) {
  214. OC_App::loadApps();
  215. //setup extra user backends
  216. self::setupBackends();
  217. self::unsetMagicInCookie();
  218. return self::loginWithApache($backend);
  219. }
  220. return null;
  221. }
  222. /**
  223. * Sets user id for session and triggers emit
  224. *
  225. * @param string $uid
  226. */
  227. public static function setUserId($uid) {
  228. $userSession = \OC::$server->getUserSession();
  229. $userManager = \OC::$server->getUserManager();
  230. if ($user = $userManager->get($uid)) {
  231. $userSession->setUser($user);
  232. } else {
  233. \OC::$server->getSession()->set('user_id', $uid);
  234. }
  235. }
  236. /**
  237. * Sets user display name for session
  238. *
  239. * @param string $uid
  240. * @param string $displayName
  241. * @return bool Whether the display name could get set
  242. */
  243. public static function setDisplayName($uid, $displayName = null) {
  244. if (is_null($displayName)) {
  245. $displayName = $uid;
  246. }
  247. $user = \OC::$server->getUserManager()->get($uid);
  248. if ($user) {
  249. return $user->setDisplayName($displayName);
  250. } else {
  251. return false;
  252. }
  253. }
  254. /**
  255. * Check if the user is logged in, considers also the HTTP basic credentials
  256. *
  257. * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
  258. * @return bool
  259. */
  260. public static function isLoggedIn() {
  261. return \OC::$server->getUserSession()->isLoggedIn();
  262. }
  263. /**
  264. * set incognito mode, e.g. if a user wants to open a public link
  265. *
  266. * @param bool $status
  267. */
  268. public static function setIncognitoMode($status) {
  269. self::$incognitoMode = $status;
  270. }
  271. /**
  272. * get incognito mode status
  273. *
  274. * @return bool
  275. */
  276. public static function isIncognitoMode() {
  277. return self::$incognitoMode;
  278. }
  279. /**
  280. * Supplies an attribute to the logout hyperlink. The default behaviour
  281. * is to return an href with '?logout=true' appended. However, it can
  282. * supply any attribute(s) which are valid for <a>.
  283. *
  284. * @return string with one or more HTML attributes.
  285. */
  286. public static function getLogoutAttribute() {
  287. $backend = self::findFirstActiveUsedBackend();
  288. if ($backend) {
  289. return $backend->getLogoutAttribute();
  290. }
  291. $logoutUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute(
  292. 'core.login.logout',
  293. [
  294. 'requesttoken' => \OCP\Util::callRegister(),
  295. ]
  296. );
  297. return 'href="'.$logoutUrl.'"';
  298. }
  299. /**
  300. * Check if the user is an admin user
  301. *
  302. * @param string $uid uid of the admin
  303. * @return bool
  304. */
  305. public static function isAdminUser($uid) {
  306. $group = \OC::$server->getGroupManager()->get('admin');
  307. $user = \OC::$server->getUserManager()->get($uid);
  308. if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
  309. return true;
  310. }
  311. return false;
  312. }
  313. /**
  314. * get the user id of the user currently logged in.
  315. *
  316. * @return string|bool uid or false
  317. */
  318. public static function getUser() {
  319. $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
  320. if (!is_null($uid) && self::$incognitoMode === false) {
  321. return $uid;
  322. } else {
  323. return false;
  324. }
  325. }
  326. /**
  327. * get the display name of the user currently logged in.
  328. *
  329. * @param string $uid
  330. * @return string uid or false
  331. */
  332. public static function getDisplayName($uid = null) {
  333. if ($uid) {
  334. $user = \OC::$server->getUserManager()->get($uid);
  335. if ($user) {
  336. return $user->getDisplayName();
  337. } else {
  338. return $uid;
  339. }
  340. } else {
  341. $user = self::getUserSession()->getUser();
  342. if ($user) {
  343. return $user->getDisplayName();
  344. } else {
  345. return false;
  346. }
  347. }
  348. }
  349. /**
  350. * Autogenerate a password
  351. *
  352. * @return string
  353. *
  354. * generates a password
  355. */
  356. public static function generatePassword() {
  357. return \OC::$server->getSecureRandom()->generate(30);
  358. }
  359. /**
  360. * Set password
  361. *
  362. * @param string $uid The username
  363. * @param string $password The new password
  364. * @param string $recoveryPassword for the encryption app to reset encryption keys
  365. * @return bool
  366. *
  367. * Change the password of a user
  368. */
  369. public static function setPassword($uid, $password, $recoveryPassword = null) {
  370. $user = \OC::$server->getUserManager()->get($uid);
  371. if ($user) {
  372. return $user->setPassword($password, $recoveryPassword);
  373. } else {
  374. return false;
  375. }
  376. }
  377. /**
  378. * Check whether user can change his avatar
  379. *
  380. * @param string $uid The username
  381. * @return bool
  382. *
  383. * Check whether a specified user can change his avatar
  384. */
  385. public static function canUserChangeAvatar($uid) {
  386. $user = \OC::$server->getUserManager()->get($uid);
  387. if ($user) {
  388. return $user->canChangeAvatar();
  389. } else {
  390. return false;
  391. }
  392. }
  393. /**
  394. * Check whether user can change his password
  395. *
  396. * @param string $uid The username
  397. * @return bool
  398. *
  399. * Check whether a specified user can change his password
  400. */
  401. public static function canUserChangePassword($uid) {
  402. $user = \OC::$server->getUserManager()->get($uid);
  403. if ($user) {
  404. return $user->canChangePassword();
  405. } else {
  406. return false;
  407. }
  408. }
  409. /**
  410. * Check whether user can change his display name
  411. *
  412. * @param string $uid The username
  413. * @return bool
  414. *
  415. * Check whether a specified user can change his display name
  416. */
  417. public static function canUserChangeDisplayName($uid) {
  418. $user = \OC::$server->getUserManager()->get($uid);
  419. if ($user) {
  420. return $user->canChangeDisplayName();
  421. } else {
  422. return false;
  423. }
  424. }
  425. /**
  426. * Check if the password is correct
  427. *
  428. * @param string $uid The username
  429. * @param string $password The password
  430. * @return string|false user id a string on success, false otherwise
  431. *
  432. * Check if the password is correct without logging in the user
  433. * returns the user id or false
  434. */
  435. public static function checkPassword($uid, $password) {
  436. $manager = \OC::$server->getUserManager();
  437. $username = $manager->checkPassword($uid, $password);
  438. if ($username !== false) {
  439. return $username->getUID();
  440. }
  441. return false;
  442. }
  443. /**
  444. * @param string $uid The username
  445. * @return string
  446. *
  447. * returns the path to the users home directory
  448. * @deprecated Use \OC::$server->getUserManager->getHome()
  449. */
  450. public static function getHome($uid) {
  451. $user = \OC::$server->getUserManager()->get($uid);
  452. if ($user) {
  453. return $user->getHome();
  454. } else {
  455. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  456. }
  457. }
  458. /**
  459. * Get a list of all users
  460. *
  461. * @return array an array of all uids
  462. *
  463. * Get a list of all users.
  464. * @param string $search
  465. * @param integer $limit
  466. * @param integer $offset
  467. */
  468. public static function getUsers($search = '', $limit = null, $offset = null) {
  469. $users = \OC::$server->getUserManager()->search($search, $limit, $offset);
  470. $uids = array();
  471. foreach ($users as $user) {
  472. $uids[] = $user->getUID();
  473. }
  474. return $uids;
  475. }
  476. /**
  477. * Get a list of all users display name
  478. *
  479. * @param string $search
  480. * @param int $limit
  481. * @param int $offset
  482. * @return array associative array with all display names (value) and corresponding uids (key)
  483. *
  484. * Get a list of all display names and user ids.
  485. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  486. */
  487. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  488. $displayNames = array();
  489. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  490. foreach ($users as $user) {
  491. $displayNames[$user->getUID()] = $user->getDisplayName();
  492. }
  493. return $displayNames;
  494. }
  495. /**
  496. * check if a user exists
  497. *
  498. * @param string $uid the username
  499. * @return boolean
  500. */
  501. public static function userExists($uid) {
  502. return \OC::$server->getUserManager()->userExists($uid);
  503. }
  504. /**
  505. * disables a user
  506. *
  507. * @param string $uid the user to disable
  508. */
  509. public static function disableUser($uid) {
  510. $user = \OC::$server->getUserManager()->get($uid);
  511. if ($user) {
  512. $user->setEnabled(false);
  513. }
  514. }
  515. /**
  516. * enable a user
  517. *
  518. * @param string $uid
  519. */
  520. public static function enableUser($uid) {
  521. $user = \OC::$server->getUserManager()->get($uid);
  522. if ($user) {
  523. $user->setEnabled(true);
  524. }
  525. }
  526. /**
  527. * checks if a user is enabled
  528. *
  529. * @param string $uid
  530. * @return bool
  531. */
  532. public static function isEnabled($uid) {
  533. $user = \OC::$server->getUserManager()->get($uid);
  534. if ($user) {
  535. return $user->isEnabled();
  536. } else {
  537. return false;
  538. }
  539. }
  540. /**
  541. * Set cookie value to use in next page load
  542. *
  543. * @param string $username username to be set
  544. * @param string $token
  545. */
  546. public static function setMagicInCookie($username, $token) {
  547. self::getUserSession()->setMagicInCookie($username, $token);
  548. }
  549. /**
  550. * Remove cookie for "remember username"
  551. */
  552. public static function unsetMagicInCookie() {
  553. self::getUserSession()->unsetMagicInCookie();
  554. }
  555. /**
  556. * Returns the first active backend from self::$_usedBackends.
  557. *
  558. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  559. */
  560. private static function findFirstActiveUsedBackend() {
  561. foreach (self::$_usedBackends as $backend) {
  562. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  563. if ($backend->isSessionActive()) {
  564. return $backend;
  565. }
  566. }
  567. }
  568. return null;
  569. }
  570. }