Database.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\User;
  9. use OCP\AppFramework\Db\TTransactional;
  10. use OCP\Cache\CappedMemoryCache;
  11. use OCP\EventDispatcher\IEventDispatcher;
  12. use OCP\IDBConnection;
  13. use OCP\Security\Events\ValidatePasswordPolicyEvent;
  14. use OCP\Security\IHasher;
  15. use OCP\User\Backend\ABackend;
  16. use OCP\User\Backend\ICheckPasswordBackend;
  17. use OCP\User\Backend\ICountUsersBackend;
  18. use OCP\User\Backend\ICreateUserBackend;
  19. use OCP\User\Backend\IGetDisplayNameBackend;
  20. use OCP\User\Backend\IGetHomeBackend;
  21. use OCP\User\Backend\IGetRealUIDBackend;
  22. use OCP\User\Backend\ISearchKnownUsersBackend;
  23. use OCP\User\Backend\ISetDisplayNameBackend;
  24. use OCP\User\Backend\ISetPasswordBackend;
  25. /**
  26. * Class for user management in a SQL Database (e.g. MySQL, SQLite)
  27. */
  28. class Database extends ABackend implements
  29. ICreateUserBackend,
  30. ISetPasswordBackend,
  31. ISetDisplayNameBackend,
  32. IGetDisplayNameBackend,
  33. ICheckPasswordBackend,
  34. IGetHomeBackend,
  35. ICountUsersBackend,
  36. ISearchKnownUsersBackend,
  37. IGetRealUIDBackend {
  38. /** @var CappedMemoryCache */
  39. private $cache;
  40. /** @var IEventDispatcher */
  41. private $eventDispatcher;
  42. /** @var IDBConnection */
  43. private $dbConn;
  44. /** @var string */
  45. private $table;
  46. use TTransactional;
  47. /**
  48. * \OC\User\Database constructor.
  49. *
  50. * @param IEventDispatcher $eventDispatcher
  51. * @param string $table
  52. */
  53. public function __construct($eventDispatcher = null, $table = 'users') {
  54. $this->cache = new CappedMemoryCache();
  55. $this->table = $table;
  56. $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OCP\Server::get(IEventDispatcher::class);
  57. }
  58. /**
  59. * FIXME: This function should not be required!
  60. */
  61. private function fixDI() {
  62. if ($this->dbConn === null) {
  63. $this->dbConn = \OC::$server->getDatabaseConnection();
  64. }
  65. }
  66. /**
  67. * Create a new user
  68. *
  69. * @param string $uid The username of the user to create
  70. * @param string $password The password of the new user
  71. * @return bool
  72. *
  73. * Creates a new user. Basic checking of username is done in OC_User
  74. * itself, not in its subclasses.
  75. */
  76. public function createUser(string $uid, string $password): bool {
  77. $this->fixDI();
  78. if (!$this->userExists($uid)) {
  79. $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
  80. return $this->atomic(function () use ($uid, $password) {
  81. $qb = $this->dbConn->getQueryBuilder();
  82. $qb->insert($this->table)
  83. ->values([
  84. 'uid' => $qb->createNamedParameter($uid),
  85. 'password' => $qb->createNamedParameter(\OC::$server->get(IHasher::class)->hash($password)),
  86. 'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
  87. ]);
  88. $result = $qb->executeStatement();
  89. // Clear cache
  90. unset($this->cache[$uid]);
  91. // Repopulate the cache
  92. $this->loadUser($uid);
  93. return (bool) $result;
  94. }, $this->dbConn);
  95. }
  96. return false;
  97. }
  98. /**
  99. * delete a user
  100. *
  101. * @param string $uid The username of the user to delete
  102. * @return bool
  103. *
  104. * Deletes a user
  105. */
  106. public function deleteUser($uid) {
  107. $this->fixDI();
  108. // Delete user-group-relation
  109. $query = $this->dbConn->getQueryBuilder();
  110. $query->delete($this->table)
  111. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  112. $result = $query->execute();
  113. if (isset($this->cache[$uid])) {
  114. unset($this->cache[$uid]);
  115. }
  116. return $result ? true : false;
  117. }
  118. private function updatePassword(string $uid, string $passwordHash): bool {
  119. $query = $this->dbConn->getQueryBuilder();
  120. $query->update($this->table)
  121. ->set('password', $query->createNamedParameter($passwordHash))
  122. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  123. $result = $query->execute();
  124. return $result ? true : false;
  125. }
  126. /**
  127. * Set password
  128. *
  129. * @param string $uid The username
  130. * @param string $password The new password
  131. * @return bool
  132. *
  133. * Change the password of a user
  134. */
  135. public function setPassword(string $uid, string $password): bool {
  136. $this->fixDI();
  137. if ($this->userExists($uid)) {
  138. $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
  139. $hasher = \OC::$server->get(IHasher::class);
  140. $hashedPassword = $hasher->hash($password);
  141. $return = $this->updatePassword($uid, $hashedPassword);
  142. if ($return) {
  143. $this->cache[$uid]['password'] = $hashedPassword;
  144. }
  145. return $return;
  146. }
  147. return false;
  148. }
  149. /**
  150. * Set display name
  151. *
  152. * @param string $uid The username
  153. * @param string $displayName The new display name
  154. * @return bool
  155. *
  156. * @throws \InvalidArgumentException
  157. *
  158. * Change the display name of a user
  159. */
  160. public function setDisplayName(string $uid, string $displayName): bool {
  161. if (mb_strlen($displayName) > 64) {
  162. throw new \InvalidArgumentException('Invalid displayname');
  163. }
  164. $this->fixDI();
  165. if ($this->userExists($uid)) {
  166. $query = $this->dbConn->getQueryBuilder();
  167. $query->update($this->table)
  168. ->set('displayname', $query->createNamedParameter($displayName))
  169. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  170. $query->execute();
  171. $this->cache[$uid]['displayname'] = $displayName;
  172. return true;
  173. }
  174. return false;
  175. }
  176. /**
  177. * get display name of the user
  178. *
  179. * @param string $uid user ID of the user
  180. * @return string display name
  181. */
  182. public function getDisplayName($uid): string {
  183. $uid = (string)$uid;
  184. $this->loadUser($uid);
  185. return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
  186. }
  187. /**
  188. * Get a list of all display names and user ids.
  189. *
  190. * @param string $search
  191. * @param int|null $limit
  192. * @param int|null $offset
  193. * @return array an array of all displayNames (value) and the corresponding uids (key)
  194. */
  195. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  196. $limit = $this->fixLimit($limit);
  197. $this->fixDI();
  198. $query = $this->dbConn->getQueryBuilder();
  199. $query->select('uid', 'displayname')
  200. ->from($this->table, 'u')
  201. ->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
  202. $query->expr()->eq('userid', 'uid'),
  203. $query->expr()->eq('appid', $query->expr()->literal('settings')),
  204. $query->expr()->eq('configkey', $query->expr()->literal('email')))
  205. )
  206. // sqlite doesn't like re-using a single named parameter here
  207. ->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  208. ->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  209. ->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  210. ->orderBy($query->func()->lower('displayname'), 'ASC')
  211. ->addOrderBy('uid_lower', 'ASC')
  212. ->setMaxResults($limit)
  213. ->setFirstResult($offset);
  214. $result = $query->executeQuery();
  215. $displayNames = [];
  216. while ($row = $result->fetch()) {
  217. $displayNames[(string)$row['uid']] = (string)$row['displayname'];
  218. }
  219. return $displayNames;
  220. }
  221. /**
  222. * @param string $searcher
  223. * @param string $pattern
  224. * @param int|null $limit
  225. * @param int|null $offset
  226. * @return array
  227. * @since 21.0.1
  228. */
  229. public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array {
  230. $limit = $this->fixLimit($limit);
  231. $this->fixDI();
  232. $query = $this->dbConn->getQueryBuilder();
  233. $query->select('u.uid', 'u.displayname')
  234. ->from($this->table, 'u')
  235. ->leftJoin('u', 'known_users', 'k', $query->expr()->andX(
  236. $query->expr()->eq('k.known_user', 'u.uid'),
  237. $query->expr()->eq('k.known_to', $query->createNamedParameter($searcher))
  238. ))
  239. ->where($query->expr()->eq('k.known_to', $query->createNamedParameter($searcher)))
  240. ->andWhere($query->expr()->orX(
  241. $query->expr()->iLike('u.uid', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($pattern) . '%')),
  242. $query->expr()->iLike('u.displayname', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($pattern) . '%'))
  243. ))
  244. ->orderBy('u.displayname', 'ASC')
  245. ->addOrderBy('u.uid_lower', 'ASC')
  246. ->setMaxResults($limit)
  247. ->setFirstResult($offset);
  248. $result = $query->execute();
  249. $displayNames = [];
  250. while ($row = $result->fetch()) {
  251. $displayNames[(string)$row['uid']] = (string)$row['displayname'];
  252. }
  253. return $displayNames;
  254. }
  255. /**
  256. * Check if the password is correct
  257. *
  258. * @param string $loginName The loginname
  259. * @param string $password The password
  260. * @return string
  261. *
  262. * Check if the password is correct without logging in the user
  263. * returns the user id or false
  264. */
  265. public function checkPassword(string $loginName, string $password) {
  266. $found = $this->loadUser($loginName);
  267. if ($found && is_array($this->cache[$loginName])) {
  268. $storedHash = $this->cache[$loginName]['password'];
  269. $newHash = '';
  270. if (\OC::$server->get(IHasher::class)->verify($password, $storedHash, $newHash)) {
  271. if (!empty($newHash)) {
  272. $this->updatePassword($loginName, $newHash);
  273. }
  274. return (string)$this->cache[$loginName]['uid'];
  275. }
  276. }
  277. return false;
  278. }
  279. /**
  280. * Load an user in the cache
  281. *
  282. * @param string $uid the username
  283. * @return boolean true if user was found, false otherwise
  284. */
  285. private function loadUser($uid) {
  286. $this->fixDI();
  287. $uid = (string)$uid;
  288. if (!isset($this->cache[$uid])) {
  289. //guests $uid could be NULL or ''
  290. if ($uid === '') {
  291. $this->cache[$uid] = false;
  292. return true;
  293. }
  294. $qb = $this->dbConn->getQueryBuilder();
  295. $qb->select('uid', 'displayname', 'password')
  296. ->from($this->table)
  297. ->where(
  298. $qb->expr()->eq(
  299. 'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
  300. )
  301. );
  302. $result = $qb->execute();
  303. $row = $result->fetch();
  304. $result->closeCursor();
  305. // "uid" is primary key, so there can only be a single result
  306. if ($row !== false) {
  307. $this->cache[$uid] = [
  308. 'uid' => (string)$row['uid'],
  309. 'displayname' => (string)$row['displayname'],
  310. 'password' => (string)$row['password'],
  311. ];
  312. } else {
  313. $this->cache[$uid] = false;
  314. return false;
  315. }
  316. }
  317. return true;
  318. }
  319. /**
  320. * Get a list of all users
  321. *
  322. * @param string $search
  323. * @param null|int $limit
  324. * @param null|int $offset
  325. * @return string[] an array of all uids
  326. */
  327. public function getUsers($search = '', $limit = null, $offset = null) {
  328. $limit = $this->fixLimit($limit);
  329. $users = $this->getDisplayNames($search, $limit, $offset);
  330. $userIds = array_map(function ($uid) {
  331. return (string)$uid;
  332. }, array_keys($users));
  333. sort($userIds, SORT_STRING | SORT_FLAG_CASE);
  334. return $userIds;
  335. }
  336. /**
  337. * check if a user exists
  338. *
  339. * @param string $uid the username
  340. * @return boolean
  341. */
  342. public function userExists($uid) {
  343. $this->loadUser($uid);
  344. return $this->cache[$uid] !== false;
  345. }
  346. /**
  347. * get the user's home directory
  348. *
  349. * @param string $uid the username
  350. * @return string|false
  351. */
  352. public function getHome(string $uid) {
  353. if ($this->userExists($uid)) {
  354. return \OC::$server->getConfig()->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
  355. }
  356. return false;
  357. }
  358. /**
  359. * @return bool
  360. */
  361. public function hasUserListings() {
  362. return true;
  363. }
  364. /**
  365. * counts the users in the database
  366. *
  367. * @return int|false
  368. */
  369. public function countUsers() {
  370. $this->fixDI();
  371. $query = $this->dbConn->getQueryBuilder();
  372. $query->select($query->func()->count('uid'))
  373. ->from($this->table);
  374. $result = $query->executeQuery();
  375. return $result->fetchOne();
  376. }
  377. /**
  378. * returns the username for the given login name in the correct casing
  379. *
  380. * @param string $loginName
  381. * @return string|false
  382. */
  383. public function loginName2UserName($loginName) {
  384. if ($this->userExists($loginName)) {
  385. return $this->cache[$loginName]['uid'];
  386. }
  387. return false;
  388. }
  389. /**
  390. * Backend name to be shown in user management
  391. *
  392. * @return string the name of the backend to be shown
  393. */
  394. public function getBackendName() {
  395. return 'Database';
  396. }
  397. public static function preLoginNameUsedAsUserName($param) {
  398. if (!isset($param['uid'])) {
  399. throw new \Exception('key uid is expected to be set in $param');
  400. }
  401. $backends = \OC::$server->getUserManager()->getBackends();
  402. foreach ($backends as $backend) {
  403. if ($backend instanceof Database) {
  404. /** @var \OC\User\Database $backend */
  405. $uid = $backend->loginName2UserName($param['uid']);
  406. if ($uid !== false) {
  407. $param['uid'] = $uid;
  408. return;
  409. }
  410. }
  411. }
  412. }
  413. public function getRealUID(string $uid): string {
  414. if (!$this->userExists($uid)) {
  415. throw new \RuntimeException($uid . ' does not exist');
  416. }
  417. return $this->cache[$uid]['uid'];
  418. }
  419. private function fixLimit($limit) {
  420. if (is_int($limit) && $limit >= 0) {
  421. return $limit;
  422. }
  423. return null;
  424. }
  425. }