user.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Frank Karlitschek
  6. * @copyright 2012 Frank Karlitschek frank@owncloud.org
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * This class provides wrapper methods for user management. Multiple backends are
  24. * supported. User management operations are delegated to the configured backend for
  25. * execution.
  26. *
  27. * Hooks provided:
  28. * pre_createUser(&run, uid, password)
  29. * post_createUser(uid, password)
  30. * pre_deleteUser(&run, uid)
  31. * post_deleteUser(uid)
  32. * pre_setPassword(&run, uid, password, recoveryPassword)
  33. * post_setPassword(uid, password, recoveryPassword)
  34. * pre_login(&run, uid, password)
  35. * post_login(uid)
  36. * logout()
  37. */
  38. class OC_User {
  39. public static function getUserSession() {
  40. return OC::$server->getUserSession();
  41. }
  42. /**
  43. * @return \OC\User\Manager
  44. */
  45. public static function getManager() {
  46. return OC::$server->getUserManager();
  47. }
  48. private static $_backends = array();
  49. private static $_usedBackends = array();
  50. private static $_setupedBackends = array();
  51. // bool, stores if a user want to access a resource anonymously, e.g if he opens a public link
  52. private static $incognitoMode = false;
  53. /**
  54. * @brief registers backend
  55. * @param string $backend name of the backend
  56. * @deprecated Add classes by calling useBackend with a class instance instead
  57. * @return bool
  58. *
  59. * Makes a list of backends that can be used by other modules
  60. */
  61. public static function registerBackend($backend) {
  62. self::$_backends[] = $backend;
  63. return true;
  64. }
  65. /**
  66. * @brief gets available backends
  67. * @deprecated
  68. * @returns array of backends
  69. *
  70. * Returns the names of all backends.
  71. */
  72. public static function getBackends() {
  73. return self::$_backends;
  74. }
  75. /**
  76. * @brief gets used backends
  77. * @deprecated
  78. * @returns array of backends
  79. *
  80. * Returns the names of all used backends.
  81. */
  82. public static function getUsedBackends() {
  83. return array_keys(self::$_usedBackends);
  84. }
  85. /**
  86. * @brief Adds the backend to the list of used backends
  87. * @param string | OC_User_Backend $backend default: database The backend to use for user management
  88. * @return bool
  89. *
  90. * Set the User Authentication Module
  91. */
  92. public static function useBackend($backend = 'database') {
  93. if ($backend instanceof OC_User_Interface) {
  94. self::$_usedBackends[get_class($backend)] = $backend;
  95. self::getManager()->registerBackend($backend);
  96. } else {
  97. // You'll never know what happens
  98. if (null === $backend OR !is_string($backend)) {
  99. $backend = 'database';
  100. }
  101. // Load backend
  102. switch ($backend) {
  103. case 'database':
  104. case 'mysql':
  105. case 'sqlite':
  106. OC_Log::write('core', 'Adding user backend ' . $backend . '.', OC_Log::DEBUG);
  107. self::$_usedBackends[$backend] = new OC_User_Database();
  108. self::getManager()->registerBackend(self::$_usedBackends[$backend]);
  109. break;
  110. default:
  111. OC_Log::write('core', 'Adding default user backend ' . $backend . '.', OC_Log::DEBUG);
  112. $className = 'OC_USER_' . strToUpper($backend);
  113. self::$_usedBackends[$backend] = new $className();
  114. self::getManager()->registerBackend(self::$_usedBackends[$backend]);
  115. break;
  116. }
  117. }
  118. return true;
  119. }
  120. /**
  121. * remove all used backends
  122. */
  123. public static function clearBackends() {
  124. self::$_usedBackends = array();
  125. self::getManager()->clearBackends();
  126. }
  127. /**
  128. * setup the configured backends in config.php
  129. */
  130. public static function setupBackends() {
  131. OC_App::loadApps(array('prelogin'));
  132. $backends = OC_Config::getValue('user_backends', array());
  133. foreach ($backends as $i => $config) {
  134. $class = $config['class'];
  135. $arguments = $config['arguments'];
  136. if (class_exists($class)) {
  137. if (array_search($i, self::$_setupedBackends) === false) {
  138. // make a reflection object
  139. $reflectionObj = new ReflectionClass($class);
  140. // use Reflection to create a new instance, using the $args
  141. $backend = $reflectionObj->newInstanceArgs($arguments);
  142. self::useBackend($backend);
  143. self::$_setupedBackends[] = $i;
  144. } else {
  145. OC_Log::write('core', 'User backend ' . $class . ' already initialized.', OC_Log::DEBUG);
  146. }
  147. } else {
  148. OC_Log::write('core', 'User backend ' . $class . ' not found.', OC_Log::ERROR);
  149. }
  150. }
  151. }
  152. /**
  153. * @brief Create a new user
  154. * @param string $uid The username of the user to create
  155. * @param string $password The password of the new user
  156. * @throws Exception
  157. * @return bool true/false
  158. *
  159. * Creates a new user. Basic checking of username is done in OC_User
  160. * itself, not in its subclasses.
  161. *
  162. * Allowed characters in the username are: "a-z", "A-Z", "0-9" and "_.@-"
  163. */
  164. public static function createUser($uid, $password) {
  165. return self::getManager()->createUser($uid, $password);
  166. }
  167. /**
  168. * @brief delete a user
  169. * @param string $uid The username of the user to delete
  170. * @return bool
  171. *
  172. * Deletes a user
  173. */
  174. public static function deleteUser($uid) {
  175. $user = self::getManager()->get($uid);
  176. if ($user) {
  177. $result = $user->delete();
  178. // if delete was successful we clean-up the rest
  179. if ($result) {
  180. // We have to delete the user from all groups
  181. foreach (OC_Group::getUserGroups($uid) as $i) {
  182. OC_Group::removeFromGroup($uid, $i);
  183. }
  184. // Delete the user's keys in preferences
  185. OC_Preferences::deleteUser($uid);
  186. // Delete user files in /data/
  187. OC_Helper::rmdirr(\OC_User::getHome($uid));
  188. // Remove it from the Cache
  189. self::getManager()->delete($uid);
  190. }
  191. return true;
  192. } else {
  193. return false;
  194. }
  195. }
  196. /**
  197. * @brief Try to login a user
  198. * @param $uid The username of the user to log in
  199. * @param $password The password of the user
  200. * @return bool
  201. *
  202. * Log in a user and regenerate a new session - if the password is ok
  203. */
  204. public static function login($uid, $password) {
  205. return self::getUserSession()->login($uid, $password);
  206. }
  207. /**
  208. * @brief Try to login a user, assuming authentication
  209. * has already happened (e.g. via Single Sign On).
  210. *
  211. * Log in a user and regenerate a new session.
  212. *
  213. * @param \OCP\Authentication\IApacheBackend $backend
  214. * @return bool
  215. */
  216. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  217. $uid = $backend->getCurrentUserId();
  218. $run = true;
  219. OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $uid ));
  220. if($uid) {
  221. session_regenerate_id(true);
  222. self::setUserId($uid);
  223. self::setDisplayName($uid);
  224. OC_Hook::emit( "OC_User", "post_login", array( "uid" => $uid, 'password'=>'' ));
  225. return true;
  226. }
  227. return false;
  228. }
  229. /**
  230. * @brief Verify with Apache whether user is authenticated.
  231. *
  232. * @return boolean|null
  233. * true: authenticated
  234. * false: not authenticated
  235. * null: not handled / no backend available
  236. */
  237. public static function handleApacheAuth() {
  238. $backend = self::findFirstActiveUsedBackend();
  239. if ($backend) {
  240. OC_App::loadApps();
  241. //setup extra user backends
  242. self::setupBackends();
  243. self::unsetMagicInCookie();
  244. return self::loginWithApache($backend);
  245. }
  246. return null;
  247. }
  248. /**
  249. * @brief Sets user id for session and triggers emit
  250. */
  251. public static function setUserId($uid) {
  252. OC::$session->set('user_id', $uid);
  253. }
  254. /**
  255. * @brief Sets user display name for session
  256. */
  257. public static function setDisplayName($uid, $displayName = null) {
  258. if (is_null($displayName)) {
  259. $displayName = $uid;
  260. }
  261. $user = self::getManager()->get($uid);
  262. if ($user) {
  263. return $user->setDisplayName($displayName);
  264. } else {
  265. return false;
  266. }
  267. }
  268. /**
  269. * @brief Logs the current user out and kills all the session data
  270. *
  271. * Logout, destroys session
  272. */
  273. public static function logout() {
  274. self::getUserSession()->logout();
  275. }
  276. /**
  277. * @brief Check if the user is logged in
  278. * @returns bool
  279. *
  280. * Checks if the user is logged in
  281. */
  282. public static function isLoggedIn() {
  283. if (\OC::$session->get('user_id') && self::$incognitoMode === false) {
  284. OC_App::loadApps(array('authentication'));
  285. self::setupBackends();
  286. return self::userExists(\OC::$session->get('user_id'));
  287. }
  288. return false;
  289. }
  290. /**
  291. * @brief set incognito mode, e.g. if a user wants to open a public link
  292. * @param bool $status
  293. */
  294. public static function setIncognitoMode($status) {
  295. self::$incognitoMode = $status;
  296. }
  297. /**
  298. * Supplies an attribute to the logout hyperlink. The default behaviour
  299. * is to return an href with '?logout=true' appended. However, it can
  300. * supply any attribute(s) which are valid for <a>.
  301. *
  302. * @return string with one or more HTML attributes.
  303. */
  304. public static function getLogoutAttribute() {
  305. $backend = self::findFirstActiveUsedBackend();
  306. if ($backend) {
  307. return $backend->getLogoutAttribute();
  308. }
  309. return 'href="' . link_to('', 'index.php') . '?logout=true"';
  310. }
  311. /**
  312. * @brief Check if the user is an admin user
  313. * @param string $uid uid of the admin
  314. * @return bool
  315. */
  316. public static function isAdminUser($uid) {
  317. if (OC_Group::inGroup($uid, 'admin') && self::$incognitoMode === false) {
  318. return true;
  319. }
  320. return false;
  321. }
  322. /**
  323. * @brief get the user id of the user currently logged in.
  324. * @return string uid or false
  325. */
  326. public static function getUser() {
  327. $uid = OC::$session ? OC::$session->get('user_id') : null;
  328. if (!is_null($uid) && self::$incognitoMode === false) {
  329. return $uid;
  330. } else {
  331. return false;
  332. }
  333. }
  334. /**
  335. * @brief get the display name of the user currently logged in.
  336. * @param string $uid
  337. * @return string uid or false
  338. */
  339. public static function getDisplayName($uid = null) {
  340. if ($uid) {
  341. $user = self::getManager()->get($uid);
  342. if ($user) {
  343. return $user->getDisplayName();
  344. } else {
  345. return $uid;
  346. }
  347. } else {
  348. $user = self::getUserSession()->getUser();
  349. if ($user) {
  350. return $user->getDisplayName();
  351. } else {
  352. return false;
  353. }
  354. }
  355. }
  356. /**
  357. * @brief Autogenerate a password
  358. * @return string
  359. *
  360. * generates a password
  361. */
  362. public static function generatePassword() {
  363. return OC_Util::generateRandomBytes(30);
  364. }
  365. /**
  366. * @brief Set password
  367. * @param string $uid The username
  368. * @param string $password The new password
  369. * @param string $recoveryPassword for the encryption app to reset encryption keys
  370. * @return bool
  371. *
  372. * Change the password of a user
  373. */
  374. public static function setPassword($uid, $password, $recoveryPassword = null) {
  375. $user = self::getManager()->get($uid);
  376. if ($user) {
  377. return $user->setPassword($password, $recoveryPassword);
  378. } else {
  379. return false;
  380. }
  381. }
  382. /**
  383. * @brief Check whether user can change his avatar
  384. * @param string $uid The username
  385. * @return bool
  386. *
  387. * Check whether a specified user can change his avatar
  388. */
  389. public static function canUserChangeAvatar($uid) {
  390. $user = self::getManager()->get($uid);
  391. if ($user) {
  392. return $user->canChangeAvatar();
  393. } else {
  394. return false;
  395. }
  396. }
  397. /**
  398. * @brief Check whether user can change his password
  399. * @param string $uid The username
  400. * @return bool
  401. *
  402. * Check whether a specified user can change his password
  403. */
  404. public static function canUserChangePassword($uid) {
  405. $user = self::getManager()->get($uid);
  406. if ($user) {
  407. return $user->canChangePassword();
  408. } else {
  409. return false;
  410. }
  411. }
  412. /**
  413. * @brief Check whether user can change his display name
  414. * @param string $uid The username
  415. * @return bool
  416. *
  417. * Check whether a specified user can change his display name
  418. */
  419. public static function canUserChangeDisplayName($uid) {
  420. $user = self::getManager()->get($uid);
  421. if ($user) {
  422. return $user->canChangeDisplayName();
  423. } else {
  424. return false;
  425. }
  426. }
  427. /**
  428. * @brief Check if the password is correct
  429. * @param string $uid The username
  430. * @param string $password The password
  431. * @return mixed user id a string on success, false otherwise
  432. *
  433. * Check if the password is correct without logging in the user
  434. * returns the user id or false
  435. */
  436. public static function checkPassword($uid, $password) {
  437. $manager = self::getManager();
  438. $username = $manager->checkPassword($uid, $password);
  439. if ($username !== false) {
  440. return $username->getUID();
  441. }
  442. return false;
  443. }
  444. /**
  445. * @param string $uid The username
  446. * @return string
  447. *
  448. * returns the path to the users home directory
  449. */
  450. public static function getHome($uid) {
  451. $user = self::getManager()->get($uid);
  452. if ($user) {
  453. return $user->getHome();
  454. } else {
  455. return OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  456. }
  457. }
  458. /**
  459. * @brief Get a list of all users
  460. * @returns array with all uids
  461. *
  462. * Get a list of all users.
  463. */
  464. public static function getUsers($search = '', $limit = null, $offset = null) {
  465. $users = self::getManager()->search($search, $limit, $offset);
  466. $uids = array();
  467. foreach ($users as $user) {
  468. $uids[] = $user->getUID();
  469. }
  470. return $uids;
  471. }
  472. /**
  473. * @brief Get a list of all users display name
  474. * @param string $search
  475. * @param int $limit
  476. * @param int $offset
  477. * @return array associative array with all display names (value) and corresponding uids (key)
  478. *
  479. * Get a list of all display names and user ids.
  480. */
  481. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  482. $displayNames = array();
  483. $users = self::getManager()->searchDisplayName($search, $limit, $offset);
  484. foreach ($users as $user) {
  485. $displayNames[$user->getUID()] = $user->getDisplayName();
  486. }
  487. return $displayNames;
  488. }
  489. /**
  490. * @brief check if a user exists
  491. * @param string $uid the username
  492. * @return boolean
  493. */
  494. public static function userExists($uid) {
  495. return self::getManager()->userExists($uid);
  496. }
  497. /**
  498. * disables a user
  499. *
  500. * @param string $uid the user to disable
  501. */
  502. public static function disableUser($uid) {
  503. $user = self::getManager()->get($uid);
  504. if ($user) {
  505. $user->setEnabled(false);
  506. }
  507. }
  508. /**
  509. * enable a user
  510. *
  511. * @param string $uid
  512. */
  513. public static function enableUser($uid) {
  514. $user = self::getManager()->get($uid);
  515. if ($user) {
  516. $user->setEnabled(true);
  517. }
  518. }
  519. /**
  520. * checks if a user is enabled
  521. *
  522. * @param string $uid
  523. * @return bool
  524. */
  525. public static function isEnabled($uid) {
  526. $user = self::getManager()->get($uid);
  527. if ($user) {
  528. return $user->isEnabled();
  529. } else {
  530. return false;
  531. }
  532. }
  533. /**
  534. * @brief Set cookie value to use in next page load
  535. * @param string $username username to be set
  536. * @param string $token
  537. */
  538. public static function setMagicInCookie($username, $token) {
  539. self::getUserSession()->setMagicInCookie($username, $token);
  540. }
  541. /**
  542. * @brief Remove cookie for "remember username"
  543. */
  544. public static function unsetMagicInCookie() {
  545. self::getUserSession()->unsetMagicInCookie();
  546. }
  547. /**
  548. * @brief Returns the first active backend from self::$_usedBackends.
  549. * @return null if no backend active, otherwise OCP\Authentication\IApacheBackend
  550. */
  551. private static function findFirstActiveUsedBackend() {
  552. foreach (self::$_usedBackends as $backend) {
  553. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  554. if ($backend->isSessionActive()) {
  555. return $backend;
  556. }
  557. }
  558. }
  559. return null;
  560. }
  561. }