Database.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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\User\Backend\ABackend;
  51. use OCP\User\Backend\ICheckPasswordBackend;
  52. use OCP\User\Backend\ICountUsersBackend;
  53. use OCP\User\Backend\ICreateUserBackend;
  54. use OCP\User\Backend\IGetDisplayNameBackend;
  55. use OCP\User\Backend\IGetHomeBackend;
  56. use OCP\User\Backend\IGetRealUIDBackend;
  57. use OCP\User\Backend\ISearchKnownUsersBackend;
  58. use OCP\User\Backend\ISetDisplayNameBackend;
  59. use OCP\User\Backend\ISetPasswordBackend;
  60. /**
  61. * Class for user management in a SQL Database (e.g. MySQL, SQLite)
  62. */
  63. class Database extends ABackend implements
  64. ICreateUserBackend,
  65. ISetPasswordBackend,
  66. ISetDisplayNameBackend,
  67. IGetDisplayNameBackend,
  68. ICheckPasswordBackend,
  69. IGetHomeBackend,
  70. ICountUsersBackend,
  71. ISearchKnownUsersBackend,
  72. IGetRealUIDBackend {
  73. /** @var CappedMemoryCache */
  74. private $cache;
  75. /** @var IEventDispatcher */
  76. private $eventDispatcher;
  77. /** @var IDBConnection */
  78. private $dbConn;
  79. /** @var string */
  80. private $table;
  81. use TTransactional;
  82. /**
  83. * \OC\User\Database constructor.
  84. *
  85. * @param IEventDispatcher $eventDispatcher
  86. * @param string $table
  87. */
  88. public function __construct($eventDispatcher = null, $table = 'users') {
  89. $this->cache = new CappedMemoryCache();
  90. $this->table = $table;
  91. $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->query(IEventDispatcher::class);
  92. }
  93. /**
  94. * FIXME: This function should not be required!
  95. */
  96. private function fixDI() {
  97. if ($this->dbConn === null) {
  98. $this->dbConn = \OC::$server->getDatabaseConnection();
  99. }
  100. }
  101. /**
  102. * Create a new user
  103. *
  104. * @param string $uid The username of the user to create
  105. * @param string $password The password of the new user
  106. * @return bool
  107. *
  108. * Creates a new user. Basic checking of username is done in OC_User
  109. * itself, not in its subclasses.
  110. */
  111. public function createUser(string $uid, string $password): bool {
  112. $this->fixDI();
  113. if (!$this->userExists($uid)) {
  114. $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
  115. return $this->atomic(function () use ($uid, $password) {
  116. $qb = $this->dbConn->getQueryBuilder();
  117. $qb->insert($this->table)
  118. ->values([
  119. 'uid' => $qb->createNamedParameter($uid),
  120. 'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
  121. 'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
  122. ]);
  123. $result = $qb->executeStatement();
  124. // Clear cache
  125. unset($this->cache[$uid]);
  126. // Repopulate the cache
  127. $this->loadUser($uid);
  128. return (bool) $result;
  129. }, $this->dbConn);
  130. }
  131. return false;
  132. }
  133. /**
  134. * delete a user
  135. *
  136. * @param string $uid The username of the user to delete
  137. * @return bool
  138. *
  139. * Deletes a user
  140. */
  141. public function deleteUser($uid) {
  142. $this->fixDI();
  143. // Delete user-group-relation
  144. $query = $this->dbConn->getQueryBuilder();
  145. $query->delete($this->table)
  146. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  147. $result = $query->execute();
  148. if (isset($this->cache[$uid])) {
  149. unset($this->cache[$uid]);
  150. }
  151. return $result ? true : false;
  152. }
  153. private function updatePassword(string $uid, string $passwordHash): bool {
  154. $query = $this->dbConn->getQueryBuilder();
  155. $query->update($this->table)
  156. ->set('password', $query->createNamedParameter($passwordHash))
  157. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  158. $result = $query->execute();
  159. return $result ? true : false;
  160. }
  161. /**
  162. * Set password
  163. *
  164. * @param string $uid The username
  165. * @param string $password The new password
  166. * @return bool
  167. *
  168. * Change the password of a user
  169. */
  170. public function setPassword(string $uid, string $password): bool {
  171. $this->fixDI();
  172. if ($this->userExists($uid)) {
  173. $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
  174. $hasher = \OC::$server->getHasher();
  175. $hashedPassword = $hasher->hash($password);
  176. $return = $this->updatePassword($uid, $hashedPassword);
  177. if ($return) {
  178. $this->cache[$uid]['password'] = $hashedPassword;
  179. }
  180. return $return;
  181. }
  182. return false;
  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->getHasher()->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. }