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