user.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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(
  249. 'core.login.logout',
  250. [
  251. 'requesttoken' => \OCP\Util::callRegister(),
  252. ]
  253. );
  254. return $logoutUrl;
  255. }
  256. /**
  257. * Check if the user is an admin user
  258. *
  259. * @param string $uid uid of the admin
  260. * @return bool
  261. */
  262. public static function isAdminUser($uid) {
  263. $group = \OC::$server->getGroupManager()->get('admin');
  264. $user = \OC::$server->getUserManager()->get($uid);
  265. if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
  266. return true;
  267. }
  268. return false;
  269. }
  270. /**
  271. * get the user id of the user currently logged in.
  272. *
  273. * @return string|bool uid or false
  274. */
  275. public static function getUser() {
  276. $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
  277. if (!is_null($uid) && self::$incognitoMode === false) {
  278. return $uid;
  279. } else {
  280. return false;
  281. }
  282. }
  283. /**
  284. * get the display name of the user currently logged in.
  285. *
  286. * @param string $uid
  287. * @return string|bool uid or false
  288. * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
  289. * get() of \OCP\IUserManager - \OC::$server->getUserManager()
  290. */
  291. public static function getDisplayName($uid = null) {
  292. if ($uid) {
  293. $user = \OC::$server->getUserManager()->get($uid);
  294. if ($user) {
  295. return $user->getDisplayName();
  296. } else {
  297. return $uid;
  298. }
  299. } else {
  300. $user = \OC::$server->getUserSession()->getUser();
  301. if ($user) {
  302. return $user->getDisplayName();
  303. } else {
  304. return false;
  305. }
  306. }
  307. }
  308. /**
  309. * Set password
  310. *
  311. * @param string $uid The username
  312. * @param string $password The new password
  313. * @param string $recoveryPassword for the encryption app to reset encryption keys
  314. * @return bool
  315. *
  316. * Change the password of a user
  317. */
  318. public static function setPassword($uid, $password, $recoveryPassword = null) {
  319. $user = \OC::$server->getUserManager()->get($uid);
  320. if ($user) {
  321. return $user->setPassword($password, $recoveryPassword);
  322. } else {
  323. return false;
  324. }
  325. }
  326. /**
  327. * @param string $uid The username
  328. * @return string
  329. *
  330. * returns the path to the users home directory
  331. * @deprecated Use \OC::$server->getUserManager->getHome()
  332. */
  333. public static function getHome($uid) {
  334. $user = \OC::$server->getUserManager()->get($uid);
  335. if ($user) {
  336. return $user->getHome();
  337. } else {
  338. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  339. }
  340. }
  341. /**
  342. * Get a list of all users display name
  343. *
  344. * @param string $search
  345. * @param int $limit
  346. * @param int $offset
  347. * @return array associative array with all display names (value) and corresponding uids (key)
  348. *
  349. * Get a list of all display names and user ids.
  350. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  351. */
  352. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  353. $displayNames = array();
  354. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  355. foreach ($users as $user) {
  356. $displayNames[$user->getUID()] = $user->getDisplayName();
  357. }
  358. return $displayNames;
  359. }
  360. /**
  361. * Returns the first active backend from self::$_usedBackends.
  362. *
  363. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  364. */
  365. private static function findFirstActiveUsedBackend() {
  366. foreach (self::$_usedBackends as $backend) {
  367. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  368. if ($backend->isSessionActive()) {
  369. return $backend;
  370. }
  371. }
  372. }
  373. return null;
  374. }
  375. }