1
0

OC_User.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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\IGroupManager;
  41. use OCP\ISession;
  42. use OCP\IUser;
  43. use OCP\IUserManager;
  44. use OCP\Server;
  45. use OCP\User\Events\BeforeUserLoggedInEvent;
  46. use OCP\User\Events\UserLoggedInEvent;
  47. use Psr\Log\LoggerInterface;
  48. /**
  49. * This class provides wrapper methods for user management. Multiple backends are
  50. * supported. User management operations are delegated to the configured backend for
  51. * execution.
  52. *
  53. * Note that &run is deprecated and won't work anymore.
  54. *
  55. * Hooks provided:
  56. * pre_createUser(&run, uid, password)
  57. * post_createUser(uid, password)
  58. * pre_deleteUser(&run, uid)
  59. * post_deleteUser(uid)
  60. * pre_setPassword(&run, uid, password, recoveryPassword)
  61. * post_setPassword(uid, password, recoveryPassword)
  62. * pre_login(&run, uid, password)
  63. * post_login(uid)
  64. * logout()
  65. */
  66. class OC_User {
  67. private static $_usedBackends = [];
  68. private static $_setupedBackends = [];
  69. // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
  70. private static $incognitoMode = false;
  71. /**
  72. * Adds the backend to the list of used backends
  73. *
  74. * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
  75. * @return bool
  76. *
  77. * Set the User Authentication Module
  78. * @suppress PhanDeprecatedFunction
  79. */
  80. public static function useBackend($backend = 'database') {
  81. if ($backend instanceof \OCP\UserInterface) {
  82. self::$_usedBackends[get_class($backend)] = $backend;
  83. \OC::$server->getUserManager()->registerBackend($backend);
  84. } else {
  85. // You'll never know what happens
  86. if ($backend === null or !is_string($backend)) {
  87. $backend = 'database';
  88. }
  89. // Load backend
  90. switch ($backend) {
  91. case 'database':
  92. case 'mysql':
  93. case 'sqlite':
  94. Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']);
  95. self::$_usedBackends[$backend] = new \OC\User\Database();
  96. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  97. break;
  98. case 'dummy':
  99. self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
  100. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  101. break;
  102. default:
  103. Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']);
  104. $className = 'OC_USER_' . strtoupper($backend);
  105. self::$_usedBackends[$backend] = new $className();
  106. \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
  107. break;
  108. }
  109. }
  110. return true;
  111. }
  112. /**
  113. * remove all used backends
  114. */
  115. public static function clearBackends() {
  116. self::$_usedBackends = [];
  117. \OC::$server->getUserManager()->clearBackends();
  118. }
  119. /**
  120. * setup the configured backends in config.php
  121. * @suppress PhanDeprecatedFunction
  122. */
  123. public static function setupBackends() {
  124. OC_App::loadApps(['prelogin']);
  125. $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
  126. if (isset($backends['default']) && !$backends['default']) {
  127. // clear default backends
  128. self::clearBackends();
  129. }
  130. foreach ($backends as $i => $config) {
  131. if (!is_array($config)) {
  132. continue;
  133. }
  134. $class = $config['class'];
  135. $arguments = $config['arguments'];
  136. if (class_exists($class)) {
  137. if (!in_array($i, self::$_setupedBackends)) {
  138. // make a reflection object
  139. $reflectionObj = new ReflectionClass($class);
  140. // use Reflection to create a new instance, using the $args
  141. $backend = $reflectionObj->newInstanceArgs($arguments);
  142. self::useBackend($backend);
  143. self::$_setupedBackends[] = $i;
  144. } else {
  145. Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']);
  146. }
  147. } else {
  148. Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']);
  149. }
  150. }
  151. }
  152. /**
  153. * Try to login a user, assuming authentication
  154. * has already happened (e.g. via Single Sign On).
  155. *
  156. * Log in a user and regenerate a new session.
  157. *
  158. * @param \OCP\Authentication\IApacheBackend $backend
  159. * @return bool
  160. */
  161. public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
  162. $uid = $backend->getCurrentUserId();
  163. $run = true;
  164. OC_Hook::emit("OC_User", "pre_login", ["run" => &$run, "uid" => $uid, 'backend' => $backend]);
  165. if ($uid) {
  166. if (self::getUser() !== $uid) {
  167. self::setUserId($uid);
  168. $userSession = \OC::$server->getUserSession();
  169. /** @var IEventDispatcher $dispatcher */
  170. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  171. if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) {
  172. $message = \OC::$server->getL10N('lib')->t('Account disabled');
  173. throw new LoginException($message);
  174. }
  175. $userSession->setLoginName($uid);
  176. $request = OC::$server->getRequest();
  177. $password = null;
  178. if ($backend instanceof \OCP\Authentication\IProvideUserSecretBackend) {
  179. $password = $backend->getCurrentUserSecret();
  180. }
  181. /** @var IEventDispatcher $dispatcher */
  182. $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend));
  183. $userSession->createSessionToken($request, $uid, $uid, $password);
  184. $userSession->createRememberMeToken($userSession->getUser());
  185. // setup the filesystem
  186. OC_Util::setupFS($uid);
  187. // first call the post_login hooks, the login-process needs to be
  188. // completed before we can safely create the users folder.
  189. // For example encryption needs to initialize the users keys first
  190. // before we can create the user folder with the skeleton files
  191. OC_Hook::emit(
  192. 'OC_User',
  193. 'post_login',
  194. [
  195. 'uid' => $uid,
  196. 'password' => $password,
  197. 'isTokenLogin' => false,
  198. ]
  199. );
  200. $dispatcher->dispatchTyped(new UserLoggedInEvent(
  201. \OC::$server->get(IUserManager::class)->get($uid),
  202. $uid,
  203. null,
  204. false)
  205. );
  206. //trigger creation of user home and /files folder
  207. \OC::$server->getUserFolder($uid);
  208. }
  209. return true;
  210. }
  211. return false;
  212. }
  213. /**
  214. * Verify with Apache whether user is authenticated.
  215. *
  216. * @return boolean|null
  217. * true: authenticated
  218. * false: not authenticated
  219. * null: not handled / no backend available
  220. */
  221. public static function handleApacheAuth() {
  222. $backend = self::findFirstActiveUsedBackend();
  223. if ($backend) {
  224. OC_App::loadApps();
  225. //setup extra user backends
  226. self::setupBackends();
  227. \OC::$server->getUserSession()->unsetMagicInCookie();
  228. return self::loginWithApache($backend);
  229. }
  230. return null;
  231. }
  232. /**
  233. * Sets user id for session and triggers emit
  234. *
  235. * @param string $uid
  236. */
  237. public static function setUserId($uid) {
  238. $userSession = \OC::$server->getUserSession();
  239. $userManager = \OC::$server->getUserManager();
  240. if ($user = $userManager->get($uid)) {
  241. $userSession->setUser($user);
  242. } else {
  243. \OC::$server->getSession()->set('user_id', $uid);
  244. }
  245. }
  246. /**
  247. * Check if the user is logged in, considers also the HTTP basic credentials
  248. *
  249. * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
  250. * @return bool
  251. */
  252. public static function isLoggedIn() {
  253. return \OC::$server->getUserSession()->isLoggedIn();
  254. }
  255. /**
  256. * set incognito mode, e.g. if a user wants to open a public link
  257. *
  258. * @param bool $status
  259. */
  260. public static function setIncognitoMode($status) {
  261. self::$incognitoMode = $status;
  262. }
  263. /**
  264. * get incognito mode status
  265. *
  266. * @return bool
  267. */
  268. public static function isIncognitoMode() {
  269. return self::$incognitoMode;
  270. }
  271. /**
  272. * Returns the current logout URL valid for the currently logged-in user
  273. *
  274. * @param \OCP\IURLGenerator $urlGenerator
  275. * @return string
  276. */
  277. public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
  278. $backend = self::findFirstActiveUsedBackend();
  279. if ($backend) {
  280. return $backend->getLogoutUrl();
  281. }
  282. $user = \OC::$server->getUserSession()->getUser();
  283. if ($user instanceof IUser) {
  284. $backend = $user->getBackend();
  285. if ($backend instanceof \OCP\User\Backend\ICustomLogout) {
  286. return $backend->getLogoutUrl();
  287. }
  288. }
  289. $logoutUrl = $urlGenerator->linkToRoute('core.login.logout');
  290. $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister());
  291. return $logoutUrl;
  292. }
  293. /**
  294. * Check if the user is an admin user
  295. *
  296. * @param string $uid uid of the admin
  297. * @return bool
  298. */
  299. public static function isAdminUser($uid) {
  300. $user = Server::get(IUserManager::class)->get($uid);
  301. $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID());
  302. return $isAdmin && self::$incognitoMode === false;
  303. }
  304. /**
  305. * get the user id of the user currently logged in.
  306. *
  307. * @return string|false uid or false
  308. */
  309. public static function getUser() {
  310. $uid = Server::get(ISession::class)?->get('user_id');
  311. if (!is_null($uid) && self::$incognitoMode === false) {
  312. return $uid;
  313. } else {
  314. return false;
  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. }