You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

417 lines
12 KiB

3 years ago
  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 <pvince81@owncloud.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 OCP\ILogger;
  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. private static $_usedBackends = [];
  59. private static $_setupedBackends = [];
  60. // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
  61. private static $incognitoMode = false;
  62. /**
  63. * Adds the backend to the list of used backends
  64. *
  65. * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
  66. * @return bool
  67. *
  68. * Set the User Authentication Module
  69. * @suppress PhanDeprecatedFunction
  70. */
  71. public static function useBackend($backend = 'database') {
  72. if ($backend instanceof \OCP\UserInterface) {
  73. self::$_usedBackends[get_class($backend)] = $backend;
  74. \OC::$server->getUserManager()->registerBackend($backend);
  75. } else {
  76. // You'll never know what happens
  77. if (null === $backend or !is_string($backend)) {
  78. $backend = 'database';
  79. }
  80. // Load backend
  81. switch ($backend) {
  82. case 'database':
  83. case 'mysql':
  84. case 'sqlite':
  85. \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
  86. self::$_usedBackends[$backend] = new \OC\User\Database();
  87. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  88. break;
  89. case 'dummy':
  90. self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
  91. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  92. break;
  93. default:
  94. \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
  95. $className = 'OC_USER_' . strtoupper($backend);
  96. self::$_usedBackends[$backend] = new $className();
  97. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  98. break;
  99. }
  100. }
  101. return true;
  102. }
  103. /**
  104. * remove all used backends
  105. */
  106. public static function clearBackends() {
  107. self::$_usedBackends = [];
  108. \OC::$server->getUserManager()->clearBackends();
  109. }
  110. /**
  111. * setup the configured backends in config.php
  112. * @suppress PhanDeprecatedFunction
  113. */
  114. public static function setupBackends() {
  115. OC_App::loadApps(['prelogin']);
  116. $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
  117. if (isset($backends['default']) && !$backends['default']) {
  118. // clear default backends
  119. self::clearBackends();
  120. }
  121. foreach ($backends as $i => $config) {
  122. if (!is_array($config)) {
  123. continue;
  124. }
  125. $class = $config['class'];
  126. $arguments = $config['arguments'];
  127. if (class_exists($class)) {
  128. if (array_search($i, self::$_setupedBackends) === false) {
  129. // make a reflection object
  130. $reflectionObj = new ReflectionClass($class);
  131. // use Reflection to create a new instance, using the $args
  132. $backend = $reflectionObj->newInstanceArgs($arguments);
  133. self::useBackend($backend);
  134. self::$_setupedBackends[] = $i;
  135. } else {
  136. \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
  137. }
  138. } else {
  139. \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
  140. }
  141. }
  142. }
  143. /**
  144. * Try to login a user, assuming authentication
  145. * has already happened (e.g. via Single Sign On).
  146. *
  147. * Log in a user and regenerate a new session.
  148. *
  149. * @param \OCP\Authentication\IApacheBackend $backend
  150. * @return bool
  151. */
  152. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  153. $uid = $backend->getCurrentUserId();
  154. $run = true;
  155. OC_Hook::emit("OC_User", "pre_login", ["run" => &$run, "uid" => $uid, 'backend' => $backend]);
  156. if ($uid) {
  157. if (self::getUser() !== $uid) {
  158. self::setUserId($uid);
  159. $userSession = \OC::$server->getUserSession();
  160. $userSession->setLoginName($uid);
  161. $request = OC::$server->getRequest();
  162. $userSession->createSessionToken($request, $uid, $uid);
  163. // setup the filesystem
  164. OC_Util::setupFS($uid);
  165. // first call the post_login hooks, the login-process needs to be
  166. // completed before we can safely create the users folder.
  167. // For example encryption needs to initialize the users keys first
  168. // before we can create the user folder with the skeleton files
  169. OC_Hook::emit(
  170. 'OC_User',
  171. 'post_login',
  172. [
  173. 'uid' => $uid,
  174. 'password' => '',
  175. 'isTokenLogin' => false,
  176. ]
  177. );
  178. //trigger creation of user home and /files folder
  179. \OC::$server->getUserFolder($uid);
  180. }
  181. return true;
  182. }
  183. return false;
  184. }
  185. /**
  186. * Verify with Apache whether user is authenticated.
  187. *
  188. * @return boolean|null
  189. * true: authenticated
  190. * false: not authenticated
  191. * null: not handled / no backend available
  192. */
  193. public static function handleApacheAuth() {
  194. $backend = self::findFirstActiveUsedBackend();
  195. if ($backend) {
  196. OC_App::loadApps();
  197. //setup extra user backends
  198. self::setupBackends();
  199. \OC::$server->getUserSession()->unsetMagicInCookie();
  200. return self::loginWithApache($backend);
  201. }
  202. return null;
  203. }
  204. /**
  205. * Sets user id for session and triggers emit
  206. *
  207. * @param string $uid
  208. */
  209. public static function setUserId($uid) {
  210. $userSession = \OC::$server->getUserSession();
  211. $userManager = \OC::$server->getUserManager();
  212. if ($user = $userManager->get($uid)) {
  213. $userSession->setUser($user);
  214. } else {
  215. \OC::$server->getSession()->set('user_id', $uid);
  216. }
  217. }
  218. /**
  219. * Check if the user is logged in, considers also the HTTP basic credentials
  220. *
  221. * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
  222. * @return bool
  223. */
  224. public static function isLoggedIn() {
  225. return \OC::$server->getUserSession()->isLoggedIn();
  226. }
  227. /**
  228. * set incognito mode, e.g. if a user wants to open a public link
  229. *
  230. * @param bool $status
  231. */
  232. public static function setIncognitoMode($status) {
  233. self::$incognitoMode = $status;
  234. }
  235. /**
  236. * get incognito mode status
  237. *
  238. * @return bool
  239. */
  240. public static function isIncognitoMode() {
  241. return self::$incognitoMode;
  242. }
  243. /**
  244. * Returns the current logout URL valid for the currently logged-in user
  245. *
  246. * @param \OCP\IURLGenerator $urlGenerator
  247. * @return string
  248. */
  249. public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
  250. $backend = self::findFirstActiveUsedBackend();
  251. if ($backend) {
  252. return $backend->getLogoutUrl();
  253. }
  254. $user = \OC::$server->getUserSession()->getUser();
  255. if ($user instanceof \OCP\IUser) {
  256. $backend = $user->getBackend();
  257. if ($backend instanceof \OCP\User\Backend\ICustomLogout) {
  258. return $backend->getLogoutUrl();
  259. }
  260. }
  261. $logoutUrl = $urlGenerator->linkToRoute('core.login.logout');
  262. $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister());
  263. return $logoutUrl;
  264. }
  265. /**
  266. * Check if the user is an admin user
  267. *
  268. * @param string $uid uid of the admin
  269. * @return bool
  270. */
  271. public static function isAdminUser($uid) {
  272. $group = \OC::$server->getGroupManager()->get('admin');
  273. $user = \OC::$server->getUserManager()->get($uid);
  274. if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
  275. return true;
  276. }
  277. return false;
  278. }
  279. /**
  280. * get the user id of the user currently logged in.
  281. *
  282. * @return string|bool uid or false
  283. */
  284. public static function getUser() {
  285. $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
  286. if (!is_null($uid) && self::$incognitoMode === false) {
  287. return $uid;
  288. } else {
  289. return false;
  290. }
  291. }
  292. /**
  293. * get the display name of the user currently logged in.
  294. *
  295. * @param string $uid
  296. * @return string|bool uid or false
  297. * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
  298. * get() of \OCP\IUserManager - \OC::$server->getUserManager()
  299. */
  300. public static function getDisplayName($uid = null) {
  301. if ($uid) {
  302. $user = \OC::$server->getUserManager()->get($uid);
  303. if ($user) {
  304. return $user->getDisplayName();
  305. } else {
  306. return $uid;
  307. }
  308. } else {
  309. $user = \OC::$server->getUserSession()->getUser();
  310. if ($user) {
  311. return $user->getDisplayName();
  312. } else {
  313. return false;
  314. }
  315. }
  316. }
  317. /**
  318. * Set password
  319. *
  320. * @param string $uid The username
  321. * @param string $password The new password
  322. * @param string $recoveryPassword for the encryption app to reset encryption keys
  323. * @return bool
  324. *
  325. * Change the password of a user
  326. */
  327. public static function setPassword($uid, $password, $recoveryPassword = null) {
  328. $user = \OC::$server->getUserManager()->get($uid);
  329. if ($user) {
  330. return $user->setPassword($password, $recoveryPassword);
  331. } else {
  332. return false;
  333. }
  334. }
  335. /**
  336. * @param string $uid The username
  337. * @return string
  338. *
  339. * returns the path to the users home directory
  340. * @deprecated Use \OC::$server->getUserManager->getHome()
  341. */
  342. public static function getHome($uid) {
  343. $user = \OC::$server->getUserManager()->get($uid);
  344. if ($user) {
  345. return $user->getHome();
  346. } else {
  347. return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
  348. }
  349. }
  350. /**
  351. * Get a list of all users display name
  352. *
  353. * @param string $search
  354. * @param int $limit
  355. * @param int $offset
  356. * @return array associative array with all display names (value) and corresponding uids (key)
  357. *
  358. * Get a list of all display names and user ids.
  359. * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
  360. */
  361. public static function getDisplayNames($search = '', $limit = null, $offset = null) {
  362. $displayNames = [];
  363. $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
  364. foreach ($users as $user) {
  365. $displayNames[$user->getUID()] = $user->getDisplayName();
  366. }
  367. return $displayNames;
  368. }
  369. /**
  370. * Returns the first active backend from self::$_usedBackends.
  371. *
  372. * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
  373. */
  374. private static function findFirstActiveUsedBackend() {
  375. foreach (self::$_usedBackends as $backend) {
  376. if ($backend instanceof OCP\Authentication\IApacheBackend) {
  377. if ($backend->isSessionActive()) {
  378. return $backend;
  379. }
  380. }
  381. }
  382. return null;
  383. }
  384. }