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.

Database.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author adrien <adrien.waksberg@believedigital.com>
  7. * @author Aldo "xoen" Giambelluca <xoen@xoen.org>
  8. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  9. * @author Bart Visscher <bartv@thisnet.nl>
  10. * @author Bjoern Schiessle <bjoern@schiessle.org>
  11. * @author Björn Schießle <bjoern@schiessle.org>
  12. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  13. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  14. * @author fabian <fabian@web2.0-apps.de>
  15. * @author Georg Ehrke <oc.list@georgehrke.com>
  16. * @author Jakob Sack <mail@jakobsack.de>
  17. * @author Joas Schilling <coding@schilljs.com>
  18. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  19. * @author Loki3000 <github@labcms.ru>
  20. * @author Lukas Reschke <lukas@statuscode.ch>
  21. * @author Morris Jobke <hey@morrisjobke.de>
  22. * @author nishiki <nishiki@yaegashi.fr>
  23. * @author Robin Appelman <robin@icewind.nl>
  24. * @author Robin McCorkell <robin@mccorkell.me.uk>
  25. * @author Roeland Jago Douma <roeland@famdouma.nl>
  26. * @author Thomas Müller <thomas.mueller@tmit.eu>
  27. * @author Vincent Petry <vincent@nextcloud.com>
  28. *
  29. * @license AGPL-3.0
  30. *
  31. * This code is free software: you can redistribute it and/or modify
  32. * it under the terms of the GNU Affero General Public License, version 3,
  33. * as published by the Free Software Foundation.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU Affero General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Affero General Public License, version 3,
  41. * along with this program. If not, see <http://www.gnu.org/licenses/>
  42. *
  43. */
  44. namespace OC\User;
  45. use OCP\Cache\CappedMemoryCache;
  46. use OCP\EventDispatcher\IEventDispatcher;
  47. use OCP\IDBConnection;
  48. use OCP\Security\Events\ValidatePasswordPolicyEvent;
  49. use OCP\User\Backend\ABackend;
  50. use OCP\User\Backend\ICheckPasswordBackend;
  51. use OCP\User\Backend\ICountUsersBackend;
  52. use OCP\User\Backend\ICreateUserBackend;
  53. use OCP\User\Backend\IGetDisplayNameBackend;
  54. use OCP\User\Backend\IGetHomeBackend;
  55. use OCP\User\Backend\IGetRealUIDBackend;
  56. use OCP\User\Backend\ISearchKnownUsersBackend;
  57. use OCP\User\Backend\ISetDisplayNameBackend;
  58. use OCP\User\Backend\ISetPasswordBackend;
  59. /**
  60. * Class for user management in a SQL Database (e.g. MySQL, SQLite)
  61. */
  62. class Database extends ABackend implements
  63. ICreateUserBackend,
  64. ISetPasswordBackend,
  65. ISetDisplayNameBackend,
  66. IGetDisplayNameBackend,
  67. ICheckPasswordBackend,
  68. IGetHomeBackend,
  69. ICountUsersBackend,
  70. ISearchKnownUsersBackend,
  71. IGetRealUIDBackend {
  72. /** @var CappedMemoryCache */
  73. private $cache;
  74. /** @var IEventDispatcher */
  75. private $eventDispatcher;
  76. /** @var IDBConnection */
  77. private $dbConn;
  78. /** @var string */
  79. private $table;
  80. /**
  81. * \OC\User\Database constructor.
  82. *
  83. * @param IEventDispatcher $eventDispatcher
  84. * @param string $table
  85. */
  86. public function __construct($eventDispatcher = null, $table = 'users') {
  87. $this->cache = new CappedMemoryCache();
  88. $this->table = $table;
  89. $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->query(IEventDispatcher::class);
  90. }
  91. /**
  92. * FIXME: This function should not be required!
  93. */
  94. private function fixDI() {
  95. if ($this->dbConn === null) {
  96. $this->dbConn = \OC::$server->getDatabaseConnection();
  97. }
  98. }
  99. /**
  100. * Create a new user
  101. *
  102. * @param string $uid The username of the user to create
  103. * @param string $password The password of the new user
  104. * @return bool
  105. *
  106. * Creates a new user. Basic checking of username is done in OC_User
  107. * itself, not in its subclasses.
  108. */
  109. public function createUser(string $uid, string $password): bool {
  110. $this->fixDI();
  111. if (!$this->userExists($uid)) {
  112. $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
  113. $qb = $this->dbConn->getQueryBuilder();
  114. $qb->insert($this->table)
  115. ->values([
  116. 'uid' => $qb->createNamedParameter($uid),
  117. 'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
  118. 'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
  119. ]);
  120. $result = $qb->execute();
  121. // Clear cache
  122. unset($this->cache[$uid]);
  123. return $result ? true : false;
  124. }
  125. return false;
  126. }
  127. /**
  128. * delete a user
  129. *
  130. * @param string $uid The username of the user to delete
  131. * @return bool
  132. *
  133. * Deletes a user
  134. */
  135. public function deleteUser($uid) {
  136. $this->fixDI();
  137. // Delete user-group-relation
  138. $query = $this->dbConn->getQueryBuilder();
  139. $query->delete($this->table)
  140. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  141. $result = $query->execute();
  142. if (isset($this->cache[$uid])) {
  143. unset($this->cache[$uid]);
  144. }
  145. return $result ? true : false;
  146. }
  147. private function updatePassword(string $uid, string $passwordHash): bool {
  148. $query = $this->dbConn->getQueryBuilder();
  149. $query->update($this->table)
  150. ->set('password', $query->createNamedParameter($passwordHash))
  151. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  152. $result = $query->execute();
  153. return $result ? true : false;
  154. }
  155. /**
  156. * Set password
  157. *
  158. * @param string $uid The username
  159. * @param string $password The new password
  160. * @return bool
  161. *
  162. * Change the password of a user
  163. */
  164. public function setPassword(string $uid, string $password): bool {
  165. $this->fixDI();
  166. if ($this->userExists($uid)) {
  167. $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
  168. $hasher = \OC::$server->getHasher();
  169. $hashedPassword = $hasher->hash($password);
  170. $return = $this->updatePassword($uid, $hashedPassword);
  171. if ($return) {
  172. $this->cache[$uid]['password'] = $hashedPassword;
  173. }
  174. return $return;
  175. }
  176. return false;
  177. }
  178. /**
  179. * Set display name
  180. *
  181. * @param string $uid The username
  182. * @param string $displayName The new display name
  183. * @return bool
  184. *
  185. * @throws \InvalidArgumentException
  186. *
  187. * Change the display name of a user
  188. */
  189. public function setDisplayName(string $uid, string $displayName): bool {
  190. if (mb_strlen($displayName) > 64) {
  191. throw new \InvalidArgumentException('Invalid displayname');
  192. }
  193. $this->fixDI();
  194. if ($this->userExists($uid)) {
  195. $query = $this->dbConn->getQueryBuilder();
  196. $query->update($this->table)
  197. ->set('displayname', $query->createNamedParameter($displayName))
  198. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  199. $query->execute();
  200. $this->cache[$uid]['displayname'] = $displayName;
  201. return true;
  202. }
  203. return false;
  204. }
  205. /**
  206. * get display name of the user
  207. *
  208. * @param string $uid user ID of the user
  209. * @return string display name
  210. */
  211. public function getDisplayName($uid): string {
  212. $uid = (string)$uid;
  213. $this->loadUser($uid);
  214. return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
  215. }
  216. /**
  217. * Get a list of all display names and user ids.
  218. *
  219. * @param string $search
  220. * @param int|null $limit
  221. * @param int|null $offset
  222. * @return array an array of all displayNames (value) and the corresponding uids (key)
  223. */
  224. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  225. $limit = $this->fixLimit($limit);
  226. $this->fixDI();
  227. $query = $this->dbConn->getQueryBuilder();
  228. $query->select('uid', 'displayname')
  229. ->from($this->table, 'u')
  230. ->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
  231. $query->expr()->eq('userid', 'uid'),
  232. $query->expr()->eq('appid', $query->expr()->literal('settings')),
  233. $query->expr()->eq('configkey', $query->expr()->literal('email')))
  234. )
  235. // sqlite doesn't like re-using a single named parameter here
  236. ->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  237. ->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  238. ->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  239. ->orderBy($query->func()->lower('displayname'), 'ASC')
  240. ->addOrderBy('uid_lower', 'ASC')
  241. ->setMaxResults($limit)
  242. ->setFirstResult($offset);
  243. $result = $query->executeQuery();
  244. $displayNames = [];
  245. while ($row = $result->fetch()) {
  246. $displayNames[(string)$row['uid']] = (string)$row['displayname'];
  247. }
  248. return $displayNames;
  249. }
  250. /**
  251. * @param string $searcher
  252. * @param string $pattern
  253. * @param int|null $limit
  254. * @param int|null $offset
  255. * @return array
  256. * @since 21.0.1
  257. */
  258. public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array {
  259. $limit = $this->fixLimit($limit);
  260. $this->fixDI();
  261. $query = $this->dbConn->getQueryBuilder();
  262. $query->select('u.uid', 'u.displayname')
  263. ->from($this->table, 'u')
  264. ->leftJoin('u', 'known_users', 'k', $query->expr()->andX(
  265. $query->expr()->eq('k.known_user', 'u.uid'),
  266. $query->expr()->eq('k.known_to', $query->createNamedParameter($searcher))
  267. ))
  268. ->where($query->expr()->eq('k.known_to', $query->createNamedParameter($searcher)))
  269. ->andWhere($query->expr()->orX(
  270. $query->expr()->iLike('u.uid', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($pattern) . '%')),
  271. $query->expr()->iLike('u.displayname', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($pattern) . '%'))
  272. ))
  273. ->orderBy('u.displayname', 'ASC')
  274. ->addOrderBy('u.uid_lower', 'ASC')
  275. ->setMaxResults($limit)
  276. ->setFirstResult($offset);
  277. $result = $query->execute();
  278. $displayNames = [];
  279. while ($row = $result->fetch()) {
  280. $displayNames[(string)$row['uid']] = (string)$row['displayname'];
  281. }
  282. return $displayNames;
  283. }
  284. /**
  285. * Check if the password is correct
  286. *
  287. * @param string $loginName The loginname
  288. * @param string $password The password
  289. * @return string
  290. *
  291. * Check if the password is correct without logging in the user
  292. * returns the user id or false
  293. */
  294. public function checkPassword(string $loginName, string $password) {
  295. $found = $this->loadUser($loginName);
  296. if ($found && is_array($this->cache[$loginName])) {
  297. $storedHash = $this->cache[$loginName]['password'];
  298. $newHash = '';
  299. if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
  300. if (!empty($newHash)) {
  301. $this->updatePassword($loginName, $newHash);
  302. }
  303. return (string)$this->cache[$loginName]['uid'];
  304. }
  305. }
  306. return false;
  307. }
  308. /**
  309. * Load an user in the cache
  310. *
  311. * @param string $uid the username
  312. * @return boolean true if user was found, false otherwise
  313. */
  314. private function loadUser($uid) {
  315. $this->fixDI();
  316. $uid = (string)$uid;
  317. if (!isset($this->cache[$uid])) {
  318. //guests $uid could be NULL or ''
  319. if ($uid === '') {
  320. $this->cache[$uid] = false;
  321. return true;
  322. }
  323. $qb = $this->dbConn->getQueryBuilder();
  324. $qb->select('uid', 'displayname', 'password')
  325. ->from($this->table)
  326. ->where(
  327. $qb->expr()->eq(
  328. 'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
  329. )
  330. );
  331. $result = $qb->execute();
  332. $row = $result->fetch();
  333. $result->closeCursor();
  334. // "uid" is primary key, so there can only be a single result
  335. if ($row !== false) {
  336. $this->cache[$uid] = [
  337. 'uid' => (string)$row['uid'],
  338. 'displayname' => (string)$row['displayname'],
  339. 'password' => (string)$row['password'],
  340. ];
  341. } else {
  342. $this->cache[$uid] = false;
  343. return false;
  344. }
  345. }
  346. return true;
  347. }
  348. /**
  349. * Get a list of all users
  350. *
  351. * @param string $search
  352. * @param null|int $limit
  353. * @param null|int $offset
  354. * @return string[] an array of all uids
  355. */
  356. public function getUsers($search = '', $limit = null, $offset = null) {
  357. $limit = $this->fixLimit($limit);
  358. $users = $this->getDisplayNames($search, $limit, $offset);
  359. $userIds = array_map(function ($uid) {
  360. return (string)$uid;
  361. }, array_keys($users));
  362. sort($userIds, SORT_STRING | SORT_FLAG_CASE);
  363. return $userIds;
  364. }
  365. /**
  366. * check if a user exists
  367. *
  368. * @param string $uid the username
  369. * @return boolean
  370. */
  371. public function userExists($uid) {
  372. $this->loadUser($uid);
  373. return $this->cache[$uid] !== false;
  374. }
  375. /**
  376. * get the user's home directory
  377. *
  378. * @param string $uid the username
  379. * @return string|false
  380. */
  381. public function getHome(string $uid) {
  382. if ($this->userExists($uid)) {
  383. return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
  384. }
  385. return false;
  386. }
  387. /**
  388. * @return bool
  389. */
  390. public function hasUserListings() {
  391. return true;
  392. }
  393. /**
  394. * counts the users in the database
  395. *
  396. * @return int|bool
  397. */
  398. public function countUsers() {
  399. $this->fixDI();
  400. $query = $this->dbConn->getQueryBuilder();
  401. $query->select($query->func()->count('uid'))
  402. ->from($this->table);
  403. $result = $query->execute();
  404. return $result->fetchOne();
  405. }
  406. /**
  407. * returns the username for the given login name in the correct casing
  408. *
  409. * @param string $loginName
  410. * @return string|false
  411. */
  412. public function loginName2UserName($loginName) {
  413. if ($this->userExists($loginName)) {
  414. return $this->cache[$loginName]['uid'];
  415. }
  416. return false;
  417. }
  418. /**
  419. * Backend name to be shown in user management
  420. *
  421. * @return string the name of the backend to be shown
  422. */
  423. public function getBackendName() {
  424. return 'Database';
  425. }
  426. public static function preLoginNameUsedAsUserName($param) {
  427. if (!isset($param['uid'])) {
  428. throw new \Exception('key uid is expected to be set in $param');
  429. }
  430. $backends = \OC::$server->getUserManager()->getBackends();
  431. foreach ($backends as $backend) {
  432. if ($backend instanceof Database) {
  433. /** @var \OC\User\Database $backend */
  434. $uid = $backend->loginName2UserName($param['uid']);
  435. if ($uid !== false) {
  436. $param['uid'] = $uid;
  437. return;
  438. }
  439. }
  440. }
  441. }
  442. public function getRealUID(string $uid): string {
  443. if (!$this->userExists($uid)) {
  444. throw new \RuntimeException($uid . ' does not exist');
  445. }
  446. return $this->cache[$uid]['uid'];
  447. }
  448. private function fixLimit($limit) {
  449. if (is_int($limit) && $limit >= 0) {
  450. return $limit;
  451. }
  452. return null;
  453. }
  454. }