Database.php 14 KB

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