user.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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 Florian Preinstorfer <nblock@archlinux.us>
  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 $_backends = array();
  65. private static $_usedBackends = array();
  66. private static $_setupedBackends = array();
  67. // bool, stores if a user want to access a resource anonymously, e.g if he opens a public link
  68. private static $incognitoMode = false;
  69. /**
  70. * Adds the backend to the list of used backends
  71. *
  72. * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
  73. * @return bool
  74. *
  75. * Set the User Authentication Module
  76. */
  77. public static function useBackend($backend = 'database') {
  78. if ($backend instanceof \OCP\UserInterface) {
  79. self::$_usedBackends[get_class($backend)] = $backend;
  80. \OC::$server->getUserManager()->registerBackend($backend);
  81. } else {
  82. // You'll never know what happens
  83. if (null === $backend OR !is_string($backend)) {
  84. $backend = 'database';
  85. }
  86. // Load backend
  87. switch ($backend) {
  88. case 'database':
  89. case 'mysql':
  90. case 'sqlite':
  91. \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
  92. self::$_usedBackends[$backend] = new OC_User_Database();
  93. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  94. break;
  95. case 'dummy':
  96. self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
  97. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  98. break;
  99. default:
  100. \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
  101. $className = 'OC_USER_' . strToUpper($backend);
  102. self::$_usedBackends[$backend] = new $className();
  103. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  104. break;
  105. }
  106. }
  107. return true;
  108. }
  109. /**
  110. * remove all used backends
  111. */
  112. public static function clearBackends() {
  113. self::$_usedBackends = array();
  114. \OC::$server->getUserManager()->clearBackends();
  115. }
  116. /**
  117. * setup the configured backends in config.php
  118. */
  119. public static function setupBackends() {
  120. OC_App::loadApps(array('prelogin'));
  121. $backends = \OC::$server->getSystemConfig()->getValue('user_backends', array());
  122. foreach ($backends as $i => $config) {
  123. $class = $config['class'];
  124. $arguments = $config['arguments'];
  125. if (class_exists($class)) {
  126. if (array_search($i, self::$_setupedBackends) === false) {
  127. // make a reflection object
  128. $reflectionObj = new ReflectionClass($class);
  129. // use Reflection to create a new instance, using the $args
  130. $backend = $reflectionObj->newInstanceArgs($arguments);
  131. self::useBackend($backend);
  132. self::$_setupedBackends[] = $i;
  133. } else {
  134. \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
  135. }
  136. } else {
  137. \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
  138. }
  139. }
  140. }
  141. /**
  142. * Try to login a user
  143. *
  144. * @param string $loginname The login name of the user to log in
  145. * @param string $password The password of the user
  146. * @return boolean|null
  147. *
  148. * Log in a user and regenerate a new session - if the password is ok
  149. */
  150. public static function login($loginname, $password) {
  151. $result = self::getUserSession()->login($loginname, $password);
  152. if ($result) {
  153. // Refresh the token
  154. \OC::$server->getCsrfTokenManager()->refreshToken();
  155. //we need to pass the user name, which may differ from login name
  156. $user = self::getUserSession()->getUser()->getUID();
  157. OC_Util::setupFS($user);
  158. //trigger creation of user home and /files folder
  159. \OC::$server->getUserFolder($user);
  160. }
  161. return $result;
  162. }
  163. /**
  164. * Try to login a user using the magic cookie (remember login)
  165. *
  166. * @param string $uid The username of the user to log in
  167. * @param string $token
  168. * @return bool
  169. */
  170. public static function loginWithCookie($uid, $token) {
  171. return self::getUserSession()->loginWithCookie($uid, $token);
  172. }
  173. /**
  174. * Try to login a user, assuming authentication
  175. * has already happened (e.g. via Single Sign On).
  176. *
  177. * Log in a user and regenerate a new session.
  178. *
  179. * @param \OCP\Authentication\IApacheBackend $backend
  180. * @return bool
  181. */
  182. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  183. $uid = $backend->getCurrentUserId();
  184. $run = true;
  185. OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
  186. if ($uid) {
  187. if (self::getUser() !== $uid) {
  188. self::setUserId($uid);
  189. self::setDisplayName($uid);
  190. self::getUserSession()->setLoginName($uid);
  191. // setup the filesystem
  192. OC_Util::setupFS($uid);
  193. // first call the post_login hooks, the login-process needs to be
  194. // completed before we can safely create the users folder.
  195. // For example encryption needs to initialize the users keys first
  196. // before we can create the user folder with the skeleton files
  197. OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
  198. //trigger creation of user home and /files folder
  199. \OC::$server->getUserFolder($uid);
  200. }
  201. return true;
  202. }
  203. return false;
  204. }
  205. /**
  206. * Verify with Apache whether user is authenticated.
  207. *
  208. * @return boolean|null
  209. * true: authenticated
  210. * false: not authenticated
  211. * null: not handled / no backend available
  212. */
  213. public static function handleApacheAuth() {
  214. $backend = self::findFirstActiveUsedBackend();
  215. if ($backend) {
  216. OC_App::loadApps();
  217. //setup extra user backends
  218. self::setupBackends();
  219. self::unsetMagicInCookie();
  220. return self::loginWithApache($backend);
  221. }
  222. return null;
  223. }
  224. /**
  225. * Sets user id for session and triggers emit
  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. * Logs the current user out and kills all the session data
  256. *
  257. * Logout, destroys session
  258. */
  259. public static function logout() {
  260. self::getUserSession()->logout();
  261. }
  262. /**
  263. * Tries to login the user with HTTP Basic Authentication
  264. */
  265. public static function tryBasicAuthLogin() {
  266. if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
  267. $result = \OC_User::login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
  268. if($result === true) {
  269. /**
  270. * Add DAV authenticated. This should in an ideal world not be
  271. * necessary but the iOS App reads cookies from anywhere instead
  272. * only the DAV endpoint.
  273. * This makes sure that the cookies will be valid for the whole scope
  274. * @see https://github.com/owncloud/core/issues/22893
  275. */
  276. \OC::$server->getSession()->set(
  277. \OCA\DAV\Connector\Sabre\Auth::DAV_AUTHENTICATED,
  278. \OC::$server->getUserSession()->getUser()->getUID()
  279. );
  280. }
  281. }
  282. }
  283. /**
  284. * Check if the user is logged in, considers also the HTTP basic credentials
  285. *
  286. * @return bool
  287. */
  288. public static function isLoggedIn() {
  289. if (\OC::$server->getSession()->get('user_id') !== null && self::$incognitoMode === false) {
  290. return self::userExists(\OC::$server->getSession()->get('user_id'));
  291. }
  292. return false;
  293. }
  294. /**
  295. * set incognito mode, e.g. if a user wants to open a public link
  296. *
  297. * @param bool $status
  298. */
  299. public static function setIncognitoMode($status) {
  300. self::$incognitoMode = $status;
  301. }
  302. /**
  303. * get incognito mode status
  304. *
  305. * @return bool
  306. */
  307. public static function isIncognitoMode() {
  308. return self::$incognitoMode;
  309. }
  310. /**
  311. * Supplies an attribute to the logout hyperlink. The default behaviour
  312. * is to return an href with '?logout=true' appended. However, it can
  313. * supply any attribute(s) which are valid for <a>.
  314. *
  315. * @return string with one or more HTML attributes.
  316. */
  317. public static function getLogoutAttribute() {
  318. $backend = self::findFirstActiveUsedBackend();
  319. if ($backend) {
  320. return $backend->getLogoutAttribute();
  321. }
  322. return 'href="' . link_to('', 'index.php') . '?logout=true&amp;requesttoken=' . urlencode(\OCP\Util::callRegister()) . '"';
  323. }
  324. /**
  325. * Check if the user is an admin user
  326. *
  327. * @param string $uid uid of the admin
  328. * @return bool
  329. */
  330. public static function isAdminUser($uid) {
  331. if (OC_Group::inGroup($uid, 'admin') && self::$incognitoMode === false) {
  332. return true;
  333. }
  334. return false;
  335. }
  336. /**
  337. * get the user id of the user currently logged in.
  338. *
  339. * @return string|bool uid or false
  340. */
  341. public static function getUser() {
  342. $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
  343. if (!is_null($uid) && self::$incognitoMode === false) {
  344. return $uid;
  345. } else {
  346. return false;
  347. }
  348. }
  349. /**
  350. * get the display name of the user currently logged in.
  351. *
  352. * @param string $uid
  353. * @return string uid or false
  354. */
  355. public static function getDisplayName($uid = null) {
  356. if ($uid) {
  357. $user = \OC::$server->getUserManager()->get($uid);
  358. if ($user) {
  359. return $user->getDisplayName();
  360. } else {
  361. return $uid;
  362. }
  363. } else {
  364. $user = self::getUserSession()->getUser();
  365. if ($user) {
  366. return $user->getDisplayName();
  367. } else {
  368. return false;
  369. }
  370. }
  371. }
  372. /**
  373. * Autogenerate a password
  374. *
  375. * @return string
  376. *
  377. * generates a password
  378. */
  379. public static function generatePassword() {
  380. return \OC::$server->getSecureRandom()->generate(30);
  381. }
  382. /**
  383. * Set password
  384. *
  385. * @param string $uid The username
  386. * @param string $password The new password
  387. * @param string $recoveryPassword for the encryption app to reset encryption keys
  388. * @return bool
  389. *
  390. * Change the password of a user
  391. */
  392. public static function setPassword($uid, $password, $recoveryPassword = null) {
  393. $user = \OC::$server->getUserManager()->get($uid);
  394. if ($user) {
  395. return $user->setPassword($password, $recoveryPassword);
  396. } else {
  397. return false;
  398. }
  399. }
  400. /**
  401. * Check whether user can change his avatar
  402. *
  403. * @param string $uid The username
  404. * @return bool
  405. *
  406. * Check whether a specified user can change his avatar
  407. */
  408. public static function canUserChangeAvatar($uid) {
  409. $user = \OC::$server->getUserManager()->get($uid);
  410. if ($user) {
  411. return $user->canChangeAvatar();
  412. } else {
  413. return false;
  414. }
  415. }
  416. /**
  417. * Check whether user can change his password
  418. *
  419. * @param string $uid The username
  420. * @return bool
  421. *
  422. * Check whether a specified user can change his password
  423. */
  424. public static function canUserChangePassword($uid) {
  425. $user = \OC::$server->getUserManager()->get($uid);
  426. if ($user) {
  427. return $user->canChangePassword();
  428. } else {
  429. return false;
  430. }
  431. }
  432. /**
  433. * Check whether user can change his display name
  434. *
  435. * @param string $uid The username
  436. * @return bool
  437. *
  438. * Check whether a specified user can change his display name
  439. */
  440. public static function canUserChangeDisplayName($uid) {
  441. $user = \OC::$server->getUserManager()->get($uid);
  442. if ($user) {
  443. return $user->canChangeDisplayName();
  444. } else {
  445. return false;
  446. }
  447. }
  448. /**
  449. * Check if the password is correct
  450. *
  451. * @param string $uid The username
  452. * @param string $password The password
  453. * @return string|false user id a string on success, false otherwise
  454. *
  455. * Check if the password is correct without logging in the user
  456. * returns the user id or false
  457. */
  458. public static function checkPassword($uid, $password) {
  459. $manager = \OC::$server->getUserManager();
  460. $username = $manager->checkPassword($uid, $password);
  461. if ($username !== false) {
  462. return $username->getUID();
  463. }
  464. return false;
  465. }
  466. /**
  467. * @param string $uid The username
  468. * @return string
  469. *
  470. * returns the path to the users home directory
  471. * @deprecated Use \OC::$server->getUserManager->getHome()
  472. */
  473. public static function getHome($uid) {
  474. $user = \OC::$server->getUserManager()->get($uid);
  475. if ($user) {
  476. return $user->getHome();
  477. } else {
  478. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  479. }
  480. }
  481. /**
  482. * Get a list of all users
  483. *
  484. * @return array an array of all uids
  485. *
  486. * Get a list of all users.
  487. * @param string $search
  488. * @param integer $limit
  489. * @param integer $offset
  490. */
  491. public static function getUsers($search = '', $limit = null, $offset = null) {
  492. $users = \OC::$server->getUserManager()->search($search, $limit, $offset);
  493. $uids = array();
  494. foreach ($users as $user) {
  495. $uids[] = $user->getUID();
  496. }
  497. return $uids;
  498. }
  499. /**
  500. * Get a list of all users display name
  501. *
  502. * @param string $search
  503. * @param int $limit
  504. * @param int $offset
  505. * @return array associative array with all display names (value) and corresponding uids (key)
  506. *
  507. * Get a list of all display names and user ids.
  508. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  509. */
  510. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  511. $displayNames = array();
  512. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  513. foreach ($users as $user) {
  514. $displayNames[$user->getUID()] = $user->getDisplayName();
  515. }
  516. return $displayNames;
  517. }
  518. /**
  519. * check if a user exists
  520. *
  521. * @param string $uid the username
  522. * @return boolean
  523. */
  524. public static function userExists($uid) {
  525. return \OC::$server->getUserManager()->userExists($uid);
  526. }
  527. /**
  528. * disables a user
  529. *
  530. * @param string $uid the user to disable
  531. */
  532. public static function disableUser($uid) {
  533. $user = \OC::$server->getUserManager()->get($uid);
  534. if ($user) {
  535. $user->setEnabled(false);
  536. }
  537. }
  538. /**
  539. * enable a user
  540. *
  541. * @param string $uid
  542. */
  543. public static function enableUser($uid) {
  544. $user = \OC::$server->getUserManager()->get($uid);
  545. if ($user) {
  546. $user->setEnabled(true);
  547. }
  548. }
  549. /**
  550. * checks if a user is enabled
  551. *
  552. * @param string $uid
  553. * @return bool
  554. */
  555. public static function isEnabled($uid) {
  556. $user = \OC::$server->getUserManager()->get($uid);
  557. if ($user) {
  558. return $user->isEnabled();
  559. } else {
  560. return false;
  561. }
  562. }
  563. /**
  564. * Set cookie value to use in next page load
  565. *
  566. * @param string $username username to be set
  567. * @param string $token
  568. */
  569. public static function setMagicInCookie($username, $token) {
  570. self::getUserSession()->setMagicInCookie($username, $token);
  571. }
  572. /**
  573. * Remove cookie for "remember username"
  574. */
  575. public static function unsetMagicInCookie() {
  576. self::getUserSession()->unsetMagicInCookie();
  577. }
  578. /**
  579. * Returns the first active backend from self::$_usedBackends.
  580. *
  581. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  582. */
  583. private static function findFirstActiveUsedBackend() {
  584. foreach (self::$_usedBackends as $backend) {
  585. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  586. if ($backend->isSessionActive()) {
  587. return $backend;
  588. }
  589. }
  590. }
  591. return null;
  592. }
  593. }