1
0

Database.php 14 KB

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