1
0

Database.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 OC\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. }
  172. return false;
  173. }
  174. /**
  175. * Set display name
  176. *
  177. * @param string $uid The username
  178. * @param string $displayName The new display name
  179. * @return bool
  180. *
  181. * Change the display name of a user
  182. */
  183. public function setDisplayName(string $uid, string $displayName): bool {
  184. $this->fixDI();
  185. if ($this->userExists($uid)) {
  186. $query = $this->dbConn->getQueryBuilder();
  187. $query->update($this->table)
  188. ->set('displayname', $query->createNamedParameter($displayName))
  189. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  190. $query->execute();
  191. $this->cache[$uid]['displayname'] = $displayName;
  192. return true;
  193. }
  194. return false;
  195. }
  196. /**
  197. * get display name of the user
  198. *
  199. * @param string $uid user ID of the user
  200. * @return string display name
  201. */
  202. public function getDisplayName($uid): string {
  203. $uid = (string)$uid;
  204. $this->loadUser($uid);
  205. return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
  206. }
  207. /**
  208. * Get a list of all display names and user ids.
  209. *
  210. * @param string $search
  211. * @param int|null $limit
  212. * @param int|null $offset
  213. * @return array an array of all displayNames (value) and the corresponding uids (key)
  214. */
  215. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  216. $limit = $this->fixLimit($limit);
  217. $this->fixDI();
  218. $query = $this->dbConn->getQueryBuilder();
  219. $query->select('uid', 'displayname')
  220. ->from($this->table, 'u')
  221. ->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
  222. $query->expr()->eq('userid', 'uid'),
  223. $query->expr()->eq('appid', $query->expr()->literal('settings')),
  224. $query->expr()->eq('configkey', $query->expr()->literal('email')))
  225. )
  226. // sqlite doesn't like re-using a single named parameter here
  227. ->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  228. ->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  229. ->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  230. ->orderBy($query->func()->lower('displayname'), 'ASC')
  231. ->addOrderBy('uid_lower', 'ASC')
  232. ->setMaxResults($limit)
  233. ->setFirstResult($offset);
  234. $result = $query->execute();
  235. $displayNames = [];
  236. while ($row = $result->fetch()) {
  237. $displayNames[(string)$row['uid']] = (string)$row['displayname'];
  238. }
  239. return $displayNames;
  240. }
  241. /**
  242. * @param string $searcher
  243. * @param string $pattern
  244. * @param int|null $limit
  245. * @param int|null $offset
  246. * @return array
  247. * @since 21.0.1
  248. */
  249. public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array {
  250. $limit = $this->fixLimit($limit);
  251. $this->fixDI();
  252. $query = $this->dbConn->getQueryBuilder();
  253. $query->select('u.uid', 'u.displayname')
  254. ->from($this->table, 'u')
  255. ->leftJoin('u', 'known_users', 'k', $query->expr()->andX(
  256. $query->expr()->eq('k.known_user', 'u.uid'),
  257. $query->expr()->eq('k.known_to', $query->createNamedParameter($searcher))
  258. ))
  259. ->where($query->expr()->eq('k.known_to', $query->createNamedParameter($searcher)))
  260. ->andWhere($query->expr()->orX(
  261. $query->expr()->iLike('u.uid', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($pattern) . '%')),
  262. $query->expr()->iLike('u.displayname', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($pattern) . '%'))
  263. ))
  264. ->orderBy('u.displayname', 'ASC')
  265. ->addOrderBy('u.uid_lower', 'ASC')
  266. ->setMaxResults($limit)
  267. ->setFirstResult($offset);
  268. $result = $query->execute();
  269. $displayNames = [];
  270. while ($row = $result->fetch()) {
  271. $displayNames[(string)$row['uid']] = (string)$row['displayname'];
  272. }
  273. return $displayNames;
  274. }
  275. /**
  276. * Check if the password is correct
  277. *
  278. * @param string $loginName The loginname
  279. * @param string $password The password
  280. * @return string
  281. *
  282. * Check if the password is correct without logging in the user
  283. * returns the user id or false
  284. */
  285. public function checkPassword(string $loginName, string $password) {
  286. $this->fixDI();
  287. $qb = $this->dbConn->getQueryBuilder();
  288. $qb->select('uid', 'password')
  289. ->from($this->table)
  290. ->where(
  291. $qb->expr()->eq(
  292. 'uid_lower', $qb->createNamedParameter(mb_strtolower($loginName))
  293. )
  294. );
  295. $result = $qb->execute();
  296. $row = $result->fetch();
  297. $result->closeCursor();
  298. if ($row) {
  299. $storedHash = $row['password'];
  300. $newHash = '';
  301. if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
  302. if (!empty($newHash)) {
  303. $this->updatePassword($loginName, $newHash);
  304. }
  305. return (string)$row['uid'];
  306. }
  307. }
  308. return false;
  309. }
  310. /**
  311. * Load an user in the cache
  312. *
  313. * @param string $uid the username
  314. * @return boolean true if user was found, false otherwise
  315. */
  316. private function loadUser($uid) {
  317. $this->fixDI();
  318. $uid = (string)$uid;
  319. if (!isset($this->cache[$uid])) {
  320. //guests $uid could be NULL or ''
  321. if ($uid === '') {
  322. $this->cache[$uid] = false;
  323. return true;
  324. }
  325. $qb = $this->dbConn->getQueryBuilder();
  326. $qb->select('uid', 'displayname')
  327. ->from($this->table)
  328. ->where(
  329. $qb->expr()->eq(
  330. 'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
  331. )
  332. );
  333. $result = $qb->execute();
  334. $row = $result->fetch();
  335. $result->closeCursor();
  336. $this->cache[$uid] = false;
  337. // "uid" is primary key, so there can only be a single result
  338. if ($row !== false) {
  339. $this->cache[$uid]['uid'] = (string)$row['uid'];
  340. $this->cache[$uid]['displayname'] = (string)$row['displayname'];
  341. } else {
  342. return false;
  343. }
  344. }
  345. return true;
  346. }
  347. /**
  348. * Get a list of all users
  349. *
  350. * @param string $search
  351. * @param null|int $limit
  352. * @param null|int $offset
  353. * @return string[] an array of all uids
  354. */
  355. public function getUsers($search = '', $limit = null, $offset = null) {
  356. $limit = $this->fixLimit($limit);
  357. $users = $this->getDisplayNames($search, $limit, $offset);
  358. $userIds = array_map(function ($uid) {
  359. return (string)$uid;
  360. }, array_keys($users));
  361. sort($userIds, SORT_STRING | SORT_FLAG_CASE);
  362. return $userIds;
  363. }
  364. /**
  365. * check if a user exists
  366. *
  367. * @param string $uid the username
  368. * @return boolean
  369. */
  370. public function userExists($uid) {
  371. $this->loadUser($uid);
  372. return $this->cache[$uid] !== false;
  373. }
  374. /**
  375. * get the user's home directory
  376. *
  377. * @param string $uid the username
  378. * @return string|false
  379. */
  380. public function getHome(string $uid) {
  381. if ($this->userExists($uid)) {
  382. return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
  383. }
  384. return false;
  385. }
  386. /**
  387. * @return bool
  388. */
  389. public function hasUserListings() {
  390. return true;
  391. }
  392. /**
  393. * counts the users in the database
  394. *
  395. * @return int|bool
  396. */
  397. public function countUsers() {
  398. $this->fixDI();
  399. $query = $this->dbConn->getQueryBuilder();
  400. $query->select($query->func()->count('uid'))
  401. ->from($this->table);
  402. $result = $query->execute();
  403. return $result->fetchOne();
  404. }
  405. /**
  406. * returns the username for the given login name in the correct casing
  407. *
  408. * @param string $loginName
  409. * @return string|false
  410. */
  411. public function loginName2UserName($loginName) {
  412. if ($this->userExists($loginName)) {
  413. return $this->cache[$loginName]['uid'];
  414. }
  415. return false;
  416. }
  417. /**
  418. * Backend name to be shown in user management
  419. *
  420. * @return string the name of the backend to be shown
  421. */
  422. public function getBackendName() {
  423. return 'Database';
  424. }
  425. public static function preLoginNameUsedAsUserName($param) {
  426. if (!isset($param['uid'])) {
  427. throw new \Exception('key uid is expected to be set in $param');
  428. }
  429. $backends = \OC::$server->getUserManager()->getBackends();
  430. foreach ($backends as $backend) {
  431. if ($backend instanceof Database) {
  432. /** @var \OC\User\Database $backend */
  433. $uid = $backend->loginName2UserName($param['uid']);
  434. if ($uid !== false) {
  435. $param['uid'] = $uid;
  436. return;
  437. }
  438. }
  439. }
  440. }
  441. public function getRealUID(string $uid): string {
  442. if (!$this->userExists($uid)) {
  443. throw new \RuntimeException($uid . ' does not exist');
  444. }
  445. return $this->cache[$uid]['uid'];
  446. }
  447. private function fixLimit($limit) {
  448. if (is_int($limit) && $limit >= 0) {
  449. return $limit;
  450. }
  451. return null;
  452. }
  453. }