user.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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(array('prelogin'));
  120. $backends = \OC::$server->getSystemConfig()->getValue('user_backends', array());
  121. foreach ($backends as $i => $config) {
  122. $class = $config['class'];
  123. $arguments = $config['arguments'];
  124. if (class_exists($class)) {
  125. if (array_search($i, self::$_setupedBackends) === false) {
  126. // make a reflection object
  127. $reflectionObj = new ReflectionClass($class);
  128. // use Reflection to create a new instance, using the $args
  129. $backend = $reflectionObj->newInstanceArgs($arguments);
  130. self::useBackend($backend);
  131. self::$_setupedBackends[] = $i;
  132. } else {
  133. \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
  134. }
  135. } else {
  136. \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
  137. }
  138. }
  139. }
  140. /**
  141. * Try to login a user using the magic cookie (remember login)
  142. *
  143. * @deprecated use \OCP\IUserSession::loginWithCookie()
  144. * @param string $uid The username of the user to log in
  145. * @param string $token
  146. * @return bool
  147. */
  148. public static function loginWithCookie($uid, $token) {
  149. return self::getUserSession()->loginWithCookie($uid, $token);
  150. }
  151. /**
  152. * Try to login a user, assuming authentication
  153. * has already happened (e.g. via Single Sign On).
  154. *
  155. * Log in a user and regenerate a new session.
  156. *
  157. * @param \OCP\Authentication\IApacheBackend $backend
  158. * @return bool
  159. */
  160. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  161. $uid = $backend->getCurrentUserId();
  162. $run = true;
  163. OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
  164. if ($uid) {
  165. if (self::getUser() !== $uid) {
  166. self::setUserId($uid);
  167. self::setDisplayName($uid);
  168. self::getUserSession()->setLoginName($uid);
  169. $request = OC::$server->getRequest();
  170. self::getUserSession()->createSessionToken($request, $uid, $uid);
  171. // setup the filesystem
  172. OC_Util::setupFS($uid);
  173. // first call the post_login hooks, the login-process needs to be
  174. // completed before we can safely create the users folder.
  175. // For example encryption needs to initialize the users keys first
  176. // before we can create the user folder with the skeleton files
  177. OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
  178. //trigger creation of user home and /files folder
  179. \OC::$server->getUserFolder($uid);
  180. }
  181. return true;
  182. }
  183. return false;
  184. }
  185. /**
  186. * Verify with Apache whether user is authenticated.
  187. *
  188. * @return boolean|null
  189. * true: authenticated
  190. * false: not authenticated
  191. * null: not handled / no backend available
  192. */
  193. public static function handleApacheAuth() {
  194. $backend = self::findFirstActiveUsedBackend();
  195. if ($backend) {
  196. OC_App::loadApps();
  197. //setup extra user backends
  198. self::setupBackends();
  199. self::unsetMagicInCookie();
  200. return self::loginWithApache($backend);
  201. }
  202. return null;
  203. }
  204. /**
  205. * Sets user id for session and triggers emit
  206. *
  207. * @param string $uid
  208. */
  209. public static function setUserId($uid) {
  210. $userSession = \OC::$server->getUserSession();
  211. $userManager = \OC::$server->getUserManager();
  212. if ($user = $userManager->get($uid)) {
  213. $userSession->setUser($user);
  214. } else {
  215. \OC::$server->getSession()->set('user_id', $uid);
  216. }
  217. }
  218. /**
  219. * Sets user display name for session
  220. *
  221. * @param string $uid
  222. * @param string $displayName
  223. * @return bool Whether the display name could get set
  224. */
  225. public static function setDisplayName($uid, $displayName = null) {
  226. if (is_null($displayName)) {
  227. $displayName = $uid;
  228. }
  229. $user = \OC::$server->getUserManager()->get($uid);
  230. if ($user) {
  231. return $user->setDisplayName($displayName);
  232. } else {
  233. return false;
  234. }
  235. }
  236. /**
  237. * Check if the user is logged in, considers also the HTTP basic credentials
  238. *
  239. * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
  240. * @return bool
  241. */
  242. public static function isLoggedIn() {
  243. return \OC::$server->getUserSession()->isLoggedIn();
  244. }
  245. /**
  246. * set incognito mode, e.g. if a user wants to open a public link
  247. *
  248. * @param bool $status
  249. */
  250. public static function setIncognitoMode($status) {
  251. self::$incognitoMode = $status;
  252. }
  253. /**
  254. * get incognito mode status
  255. *
  256. * @return bool
  257. */
  258. public static function isIncognitoMode() {
  259. return self::$incognitoMode;
  260. }
  261. /**
  262. * Supplies an attribute to the logout hyperlink. The default behaviour
  263. * is to return an href with '?logout=true' appended. However, it can
  264. * supply any attribute(s) which are valid for <a>.
  265. *
  266. * @return string with one or more HTML attributes.
  267. */
  268. public static function getLogoutAttribute() {
  269. $backend = self::findFirstActiveUsedBackend();
  270. if ($backend) {
  271. return $backend->getLogoutAttribute();
  272. }
  273. $logoutUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute(
  274. 'core.login.logout',
  275. [
  276. 'requesttoken' => \OCP\Util::callRegister(),
  277. ]
  278. );
  279. return 'href="'.$logoutUrl.'"';
  280. }
  281. /**
  282. * Check if the user is an admin user
  283. *
  284. * @param string $uid uid of the admin
  285. * @return bool
  286. */
  287. public static function isAdminUser($uid) {
  288. if (OC_Group::inGroup($uid, 'admin') && self::$incognitoMode === false) {
  289. return true;
  290. }
  291. return false;
  292. }
  293. /**
  294. * get the user id of the user currently logged in.
  295. *
  296. * @return string|bool uid or false
  297. */
  298. public static function getUser() {
  299. $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
  300. if (!is_null($uid) && self::$incognitoMode === false) {
  301. return $uid;
  302. } else {
  303. return false;
  304. }
  305. }
  306. /**
  307. * get the display name of the user currently logged in.
  308. *
  309. * @param string $uid
  310. * @return string uid or false
  311. */
  312. public static function getDisplayName($uid = null) {
  313. if ($uid) {
  314. $user = \OC::$server->getUserManager()->get($uid);
  315. if ($user) {
  316. return $user->getDisplayName();
  317. } else {
  318. return $uid;
  319. }
  320. } else {
  321. $user = self::getUserSession()->getUser();
  322. if ($user) {
  323. return $user->getDisplayName();
  324. } else {
  325. return false;
  326. }
  327. }
  328. }
  329. /**
  330. * Autogenerate a password
  331. *
  332. * @return string
  333. *
  334. * generates a password
  335. */
  336. public static function generatePassword() {
  337. return \OC::$server->getSecureRandom()->generate(30);
  338. }
  339. /**
  340. * Set password
  341. *
  342. * @param string $uid The username
  343. * @param string $password The new password
  344. * @param string $recoveryPassword for the encryption app to reset encryption keys
  345. * @return bool
  346. *
  347. * Change the password of a user
  348. */
  349. public static function setPassword($uid, $password, $recoveryPassword = null) {
  350. $user = \OC::$server->getUserManager()->get($uid);
  351. if ($user) {
  352. return $user->setPassword($password, $recoveryPassword);
  353. } else {
  354. return false;
  355. }
  356. }
  357. /**
  358. * Check whether user can change his avatar
  359. *
  360. * @param string $uid The username
  361. * @return bool
  362. *
  363. * Check whether a specified user can change his avatar
  364. */
  365. public static function canUserChangeAvatar($uid) {
  366. $user = \OC::$server->getUserManager()->get($uid);
  367. if ($user) {
  368. return $user->canChangeAvatar();
  369. } else {
  370. return false;
  371. }
  372. }
  373. /**
  374. * Check whether user can change his password
  375. *
  376. * @param string $uid The username
  377. * @return bool
  378. *
  379. * Check whether a specified user can change his password
  380. */
  381. public static function canUserChangePassword($uid) {
  382. $user = \OC::$server->getUserManager()->get($uid);
  383. if ($user) {
  384. return $user->canChangePassword();
  385. } else {
  386. return false;
  387. }
  388. }
  389. /**
  390. * Check whether user can change his display name
  391. *
  392. * @param string $uid The username
  393. * @return bool
  394. *
  395. * Check whether a specified user can change his display name
  396. */
  397. public static function canUserChangeDisplayName($uid) {
  398. $user = \OC::$server->getUserManager()->get($uid);
  399. if ($user) {
  400. return $user->canChangeDisplayName();
  401. } else {
  402. return false;
  403. }
  404. }
  405. /**
  406. * Check if the password is correct
  407. *
  408. * @param string $uid The username
  409. * @param string $password The password
  410. * @return string|false user id a string on success, false otherwise
  411. *
  412. * Check if the password is correct without logging in the user
  413. * returns the user id or false
  414. */
  415. public static function checkPassword($uid, $password) {
  416. $manager = \OC::$server->getUserManager();
  417. $username = $manager->checkPassword($uid, $password);
  418. if ($username !== false) {
  419. return $username->getUID();
  420. }
  421. return false;
  422. }
  423. /**
  424. * @param string $uid The username
  425. * @return string
  426. *
  427. * returns the path to the users home directory
  428. * @deprecated Use \OC::$server->getUserManager->getHome()
  429. */
  430. public static function getHome($uid) {
  431. $user = \OC::$server->getUserManager()->get($uid);
  432. if ($user) {
  433. return $user->getHome();
  434. } else {
  435. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  436. }
  437. }
  438. /**
  439. * Get a list of all users
  440. *
  441. * @return array an array of all uids
  442. *
  443. * Get a list of all users.
  444. * @param string $search
  445. * @param integer $limit
  446. * @param integer $offset
  447. */
  448. public static function getUsers($search = '', $limit = null, $offset = null) {
  449. $users = \OC::$server->getUserManager()->search($search, $limit, $offset);
  450. $uids = array();
  451. foreach ($users as $user) {
  452. $uids[] = $user->getUID();
  453. }
  454. return $uids;
  455. }
  456. /**
  457. * Get a list of all users display name
  458. *
  459. * @param string $search
  460. * @param int $limit
  461. * @param int $offset
  462. * @return array associative array with all display names (value) and corresponding uids (key)
  463. *
  464. * Get a list of all display names and user ids.
  465. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  466. */
  467. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  468. $displayNames = array();
  469. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  470. foreach ($users as $user) {
  471. $displayNames[$user->getUID()] = $user->getDisplayName();
  472. }
  473. return $displayNames;
  474. }
  475. /**
  476. * check if a user exists
  477. *
  478. * @param string $uid the username
  479. * @return boolean
  480. */
  481. public static function userExists($uid) {
  482. return \OC::$server->getUserManager()->userExists($uid);
  483. }
  484. /**
  485. * disables a user
  486. *
  487. * @param string $uid the user to disable
  488. */
  489. public static function disableUser($uid) {
  490. $user = \OC::$server->getUserManager()->get($uid);
  491. if ($user) {
  492. $user->setEnabled(false);
  493. }
  494. }
  495. /**
  496. * enable a user
  497. *
  498. * @param string $uid
  499. */
  500. public static function enableUser($uid) {
  501. $user = \OC::$server->getUserManager()->get($uid);
  502. if ($user) {
  503. $user->setEnabled(true);
  504. }
  505. }
  506. /**
  507. * checks if a user is enabled
  508. *
  509. * @param string $uid
  510. * @return bool
  511. */
  512. public static function isEnabled($uid) {
  513. $user = \OC::$server->getUserManager()->get($uid);
  514. if ($user) {
  515. return $user->isEnabled();
  516. } else {
  517. return false;
  518. }
  519. }
  520. /**
  521. * Set cookie value to use in next page load
  522. *
  523. * @param string $username username to be set
  524. * @param string $token
  525. */
  526. public static function setMagicInCookie($username, $token) {
  527. self::getUserSession()->setMagicInCookie($username, $token);
  528. }
  529. /**
  530. * Remove cookie for "remember username"
  531. */
  532. public static function unsetMagicInCookie() {
  533. self::getUserSession()->unsetMagicInCookie();
  534. }
  535. /**
  536. * Returns the first active backend from self::$_usedBackends.
  537. *
  538. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  539. */
  540. private static function findFirstActiveUsedBackend() {
  541. foreach (self::$_usedBackends as $backend) {
  542. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  543. if ($backend->isSessionActive()) {
  544. return $backend;
  545. }
  546. }
  547. }
  548. return null;
  549. }
  550. }