user.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 Bart Visscher <bartv@thisnet.nl>
  9. * @author Bartek Przybylski <bart.p.pl@gmail.com>
  10. * @author Björn Schießle <bjoern@schiessle.org>
  11. * @author Christoph Wurst <christoph@owncloud.com>
  12. * @author Georg Ehrke <oc.list@georgehrke.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. * @author Vincent Petry <pvince81@owncloud.com>
  24. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. use OCP\ILogger;
  41. /**
  42. * This class provides wrapper methods for user management. Multiple backends are
  43. * supported. User management operations are delegated to the configured backend for
  44. * execution.
  45. *
  46. * Note that &run is deprecated and won't work anymore.
  47. *
  48. * Hooks provided:
  49. * pre_createUser(&run, uid, password)
  50. * post_createUser(uid, password)
  51. * pre_deleteUser(&run, uid)
  52. * post_deleteUser(uid)
  53. * pre_setPassword(&run, uid, password, recoveryPassword)
  54. * post_setPassword(uid, password, recoveryPassword)
  55. * pre_login(&run, uid, password)
  56. * post_login(uid)
  57. * logout()
  58. */
  59. class OC_User {
  60. private static $_usedBackends = array();
  61. private static $_setupedBackends = array();
  62. // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
  63. private static $incognitoMode = false;
  64. /**
  65. * Adds the backend to the list of used backends
  66. *
  67. * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
  68. * @return bool
  69. *
  70. * Set the User Authentication Module
  71. * @suppress PhanDeprecatedFunction
  72. */
  73. public static function useBackend($backend = 'database') {
  74. if ($backend instanceof \OCP\UserInterface) {
  75. self::$_usedBackends[get_class($backend)] = $backend;
  76. \OC::$server->getUserManager()->registerBackend($backend);
  77. } else {
  78. // You'll never know what happens
  79. if (null === $backend OR !is_string($backend)) {
  80. $backend = 'database';
  81. }
  82. // Load backend
  83. switch ($backend) {
  84. case 'database':
  85. case 'mysql':
  86. case 'sqlite':
  87. \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
  88. self::$_usedBackends[$backend] = new \OC\User\Database();
  89. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  90. break;
  91. case 'dummy':
  92. self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
  93. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  94. break;
  95. default:
  96. \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
  97. $className = 'OC_USER_' . strtoupper($backend);
  98. self::$_usedBackends[$backend] = new $className();
  99. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  100. break;
  101. }
  102. }
  103. return true;
  104. }
  105. /**
  106. * remove all used backends
  107. */
  108. public static function clearBackends() {
  109. self::$_usedBackends = array();
  110. \OC::$server->getUserManager()->clearBackends();
  111. }
  112. /**
  113. * setup the configured backends in config.php
  114. * @suppress PhanDeprecatedFunction
  115. */
  116. public static function setupBackends() {
  117. OC_App::loadApps(['prelogin']);
  118. $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
  119. if (isset($backends['default']) && !$backends['default']) {
  120. // clear default backends
  121. self::clearBackends();
  122. }
  123. foreach ($backends as $i => $config) {
  124. if (!is_array($config)) {
  125. continue;
  126. }
  127. $class = $config['class'];
  128. $arguments = $config['arguments'];
  129. if (class_exists($class)) {
  130. if (array_search($i, self::$_setupedBackends) === false) {
  131. // make a reflection object
  132. $reflectionObj = new ReflectionClass($class);
  133. // use Reflection to create a new instance, using the $args
  134. $backend = $reflectionObj->newInstanceArgs($arguments);
  135. self::useBackend($backend);
  136. self::$_setupedBackends[] = $i;
  137. } else {
  138. \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
  139. }
  140. } else {
  141. \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
  142. }
  143. }
  144. }
  145. /**
  146. * Try to login a user, assuming authentication
  147. * has already happened (e.g. via Single Sign On).
  148. *
  149. * Log in a user and regenerate a new session.
  150. *
  151. * @param \OCP\Authentication\IApacheBackend $backend
  152. * @return bool
  153. */
  154. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  155. $uid = $backend->getCurrentUserId();
  156. $run = true;
  157. OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid, 'backend' => $backend));
  158. if ($uid) {
  159. if (self::getUser() !== $uid) {
  160. self::setUserId($uid);
  161. $userSession = \OC::$server->getUserSession();
  162. $userSession->setLoginName($uid);
  163. $request = OC::$server->getRequest();
  164. $userSession->createSessionToken($request, $uid, $uid);
  165. // setup the filesystem
  166. OC_Util::setupFS($uid);
  167. // first call the post_login hooks, the login-process needs to be
  168. // completed before we can safely create the users folder.
  169. // For example encryption needs to initialize the users keys first
  170. // before we can create the user folder with the skeleton files
  171. OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
  172. //trigger creation of user home and /files folder
  173. \OC::$server->getUserFolder($uid);
  174. }
  175. return true;
  176. }
  177. return false;
  178. }
  179. /**
  180. * Verify with Apache whether user is authenticated.
  181. *
  182. * @return boolean|null
  183. * true: authenticated
  184. * false: not authenticated
  185. * null: not handled / no backend available
  186. */
  187. public static function handleApacheAuth() {
  188. $backend = self::findFirstActiveUsedBackend();
  189. if ($backend) {
  190. OC_App::loadApps();
  191. //setup extra user backends
  192. self::setupBackends();
  193. \OC::$server->getUserSession()->unsetMagicInCookie();
  194. return self::loginWithApache($backend);
  195. }
  196. return null;
  197. }
  198. /**
  199. * Sets user id for session and triggers emit
  200. *
  201. * @param string $uid
  202. */
  203. public static function setUserId($uid) {
  204. $userSession = \OC::$server->getUserSession();
  205. $userManager = \OC::$server->getUserManager();
  206. if ($user = $userManager->get($uid)) {
  207. $userSession->setUser($user);
  208. } else {
  209. \OC::$server->getSession()->set('user_id', $uid);
  210. }
  211. }
  212. /**
  213. * Check if the user is logged in, considers also the HTTP basic credentials
  214. *
  215. * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
  216. * @return bool
  217. */
  218. public static function isLoggedIn() {
  219. return \OC::$server->getUserSession()->isLoggedIn();
  220. }
  221. /**
  222. * set incognito mode, e.g. if a user wants to open a public link
  223. *
  224. * @param bool $status
  225. */
  226. public static function setIncognitoMode($status) {
  227. self::$incognitoMode = $status;
  228. }
  229. /**
  230. * get incognito mode status
  231. *
  232. * @return bool
  233. */
  234. public static function isIncognitoMode() {
  235. return self::$incognitoMode;
  236. }
  237. /**
  238. * Returns the current logout URL valid for the currently logged-in user
  239. *
  240. * @param \OCP\IURLGenerator $urlGenerator
  241. * @return string
  242. */
  243. public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
  244. $backend = self::findFirstActiveUsedBackend();
  245. if ($backend) {
  246. return $backend->getLogoutUrl();
  247. }
  248. $logoutUrl = $urlGenerator->linkToRouteAbsolute('core.login.logout');
  249. $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister());
  250. return $logoutUrl;
  251. }
  252. /**
  253. * Check if the user is an admin user
  254. *
  255. * @param string $uid uid of the admin
  256. * @return bool
  257. */
  258. public static function isAdminUser($uid) {
  259. $group = \OC::$server->getGroupManager()->get('admin');
  260. $user = \OC::$server->getUserManager()->get($uid);
  261. if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
  262. return true;
  263. }
  264. return false;
  265. }
  266. /**
  267. * get the user id of the user currently logged in.
  268. *
  269. * @return string|bool uid or false
  270. */
  271. public static function getUser() {
  272. $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
  273. if (!is_null($uid) && self::$incognitoMode === false) {
  274. return $uid;
  275. } else {
  276. return false;
  277. }
  278. }
  279. /**
  280. * get the display name of the user currently logged in.
  281. *
  282. * @param string $uid
  283. * @return string|bool uid or false
  284. * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
  285. * get() of \OCP\IUserManager - \OC::$server->getUserManager()
  286. */
  287. public static function getDisplayName($uid = null) {
  288. if ($uid) {
  289. $user = \OC::$server->getUserManager()->get($uid);
  290. if ($user) {
  291. return $user->getDisplayName();
  292. } else {
  293. return $uid;
  294. }
  295. } else {
  296. $user = \OC::$server->getUserSession()->getUser();
  297. if ($user) {
  298. return $user->getDisplayName();
  299. } else {
  300. return false;
  301. }
  302. }
  303. }
  304. /**
  305. * Set password
  306. *
  307. * @param string $uid The username
  308. * @param string $password The new password
  309. * @param string $recoveryPassword for the encryption app to reset encryption keys
  310. * @return bool
  311. *
  312. * Change the password of a user
  313. */
  314. public static function setPassword($uid, $password, $recoveryPassword = null) {
  315. $user = \OC::$server->getUserManager()->get($uid);
  316. if ($user) {
  317. return $user->setPassword($password, $recoveryPassword);
  318. } else {
  319. return false;
  320. }
  321. }
  322. /**
  323. * @param string $uid The username
  324. * @return string
  325. *
  326. * returns the path to the users home directory
  327. * @deprecated Use \OC::$server->getUserManager->getHome()
  328. */
  329. public static function getHome($uid) {
  330. $user = \OC::$server->getUserManager()->get($uid);
  331. if ($user) {
  332. return $user->getHome();
  333. } else {
  334. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  335. }
  336. }
  337. /**
  338. * Get a list of all users display name
  339. *
  340. * @param string $search
  341. * @param int $limit
  342. * @param int $offset
  343. * @return array associative array with all display names (value) and corresponding uids (key)
  344. *
  345. * Get a list of all display names and user ids.
  346. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  347. */
  348. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  349. $displayNames = array();
  350. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  351. foreach ($users as $user) {
  352. $displayNames[$user->getUID()] = $user->getDisplayName();
  353. }
  354. return $displayNames;
  355. }
  356. /**
  357. * Returns the first active backend from self::$_usedBackends.
  358. *
  359. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  360. */
  361. private static function findFirstActiveUsedBackend() {
  362. foreach (self::$_usedBackends as $backend) {
  363. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  364. if ($backend->isSessionActive()) {
  365. return $backend;
  366. }
  367. }
  368. }
  369. return null;
  370. }
  371. }