user.php 16 KB

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