user.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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(
  172. 'OC_User',
  173. 'post_login',
  174. [
  175. 'uid' => $uid,
  176. 'password' => '',
  177. 'isTokenLogin' => false,
  178. ]
  179. );
  180. //trigger creation of user home and /files folder
  181. \OC::$server->getUserFolder($uid);
  182. }
  183. return true;
  184. }
  185. return false;
  186. }
  187. /**
  188. * Verify with Apache whether user is authenticated.
  189. *
  190. * @return boolean|null
  191. * true: authenticated
  192. * false: not authenticated
  193. * null: not handled / no backend available
  194. */
  195. public static function handleApacheAuth() {
  196. $backend = self::findFirstActiveUsedBackend();
  197. if ($backend) {
  198. OC_App::loadApps();
  199. //setup extra user backends
  200. self::setupBackends();
  201. \OC::$server->getUserSession()->unsetMagicInCookie();
  202. return self::loginWithApache($backend);
  203. }
  204. return null;
  205. }
  206. /**
  207. * Sets user id for session and triggers emit
  208. *
  209. * @param string $uid
  210. */
  211. public static function setUserId($uid) {
  212. $userSession = \OC::$server->getUserSession();
  213. $userManager = \OC::$server->getUserManager();
  214. if ($user = $userManager->get($uid)) {
  215. $userSession->setUser($user);
  216. } else {
  217. \OC::$server->getSession()->set('user_id', $uid);
  218. }
  219. }
  220. /**
  221. * Check if the user is logged in, considers also the HTTP basic credentials
  222. *
  223. * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
  224. * @return bool
  225. */
  226. public static function isLoggedIn() {
  227. return \OC::$server->getUserSession()->isLoggedIn();
  228. }
  229. /**
  230. * set incognito mode, e.g. if a user wants to open a public link
  231. *
  232. * @param bool $status
  233. */
  234. public static function setIncognitoMode($status) {
  235. self::$incognitoMode = $status;
  236. }
  237. /**
  238. * get incognito mode status
  239. *
  240. * @return bool
  241. */
  242. public static function isIncognitoMode() {
  243. return self::$incognitoMode;
  244. }
  245. /**
  246. * Returns the current logout URL valid for the currently logged-in user
  247. *
  248. * @param \OCP\IURLGenerator $urlGenerator
  249. * @return string
  250. */
  251. public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
  252. $backend = self::findFirstActiveUsedBackend();
  253. if ($backend) {
  254. return $backend->getLogoutUrl();
  255. }
  256. $logoutUrl = $urlGenerator->linkToRoute('core.login.logout');
  257. $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister());
  258. return $logoutUrl;
  259. }
  260. /**
  261. * Check if the user is an admin user
  262. *
  263. * @param string $uid uid of the admin
  264. * @return bool
  265. */
  266. public static function isAdminUser($uid) {
  267. $group = \OC::$server->getGroupManager()->get('admin');
  268. $user = \OC::$server->getUserManager()->get($uid);
  269. if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
  270. return true;
  271. }
  272. return false;
  273. }
  274. /**
  275. * get the user id of the user currently logged in.
  276. *
  277. * @return string|bool uid or false
  278. */
  279. public static function getUser() {
  280. $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
  281. if (!is_null($uid) && self::$incognitoMode === false) {
  282. return $uid;
  283. } else {
  284. return false;
  285. }
  286. }
  287. /**
  288. * get the display name of the user currently logged in.
  289. *
  290. * @param string $uid
  291. * @return string|bool uid or false
  292. * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
  293. * get() of \OCP\IUserManager - \OC::$server->getUserManager()
  294. */
  295. public static function getDisplayName($uid = null) {
  296. if ($uid) {
  297. $user = \OC::$server->getUserManager()->get($uid);
  298. if ($user) {
  299. return $user->getDisplayName();
  300. } else {
  301. return $uid;
  302. }
  303. } else {
  304. $user = \OC::$server->getUserSession()->getUser();
  305. if ($user) {
  306. return $user->getDisplayName();
  307. } else {
  308. return false;
  309. }
  310. }
  311. }
  312. /**
  313. * Set password
  314. *
  315. * @param string $uid The username
  316. * @param string $password The new password
  317. * @param string $recoveryPassword for the encryption app to reset encryption keys
  318. * @return bool
  319. *
  320. * Change the password of a user
  321. */
  322. public static function setPassword($uid, $password, $recoveryPassword = null) {
  323. $user = \OC::$server->getUserManager()->get($uid);
  324. if ($user) {
  325. return $user->setPassword($password, $recoveryPassword);
  326. } else {
  327. return false;
  328. }
  329. }
  330. /**
  331. * @param string $uid The username
  332. * @return string
  333. *
  334. * returns the path to the users home directory
  335. * @deprecated Use \OC::$server->getUserManager->getHome()
  336. */
  337. public static function getHome($uid) {
  338. $user = \OC::$server->getUserManager()->get($uid);
  339. if ($user) {
  340. return $user->getHome();
  341. } else {
  342. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  343. }
  344. }
  345. /**
  346. * Get a list of all users display name
  347. *
  348. * @param string $search
  349. * @param int $limit
  350. * @param int $offset
  351. * @return array associative array with all display names (value) and corresponding uids (key)
  352. *
  353. * Get a list of all display names and user ids.
  354. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  355. */
  356. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  357. $displayNames = array();
  358. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  359. foreach ($users as $user) {
  360. $displayNames[$user->getUID()] = $user->getDisplayName();
  361. }
  362. return $displayNames;
  363. }
  364. /**
  365. * Returns the first active backend from self::$_usedBackends.
  366. *
  367. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  368. */
  369. private static function findFirstActiveUsedBackend() {
  370. foreach (self::$_usedBackends as $backend) {
  371. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  372. if ($backend->isSessionActive()) {
  373. return $backend;
  374. }
  375. }
  376. }
  377. return null;
  378. }
  379. }