PostgreSQL.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author eduardo <eduardo@vnexu.net>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Vitor Mattos <vitor@php.rio>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC\Setup;
  30. use OC\DatabaseException;
  31. use OC\DB\Connection;
  32. use OC\DB\QueryBuilder\Literal;
  33. use OCP\Security\ISecureRandom;
  34. class PostgreSQL extends AbstractDatabase {
  35. public $dbprettyname = 'PostgreSQL';
  36. /**
  37. * @param string $username
  38. * @throws \OC\DatabaseSetupException
  39. */
  40. public function setupDatabase($username) {
  41. try {
  42. $connection = $this->connect([
  43. 'dbname' => 'postgres'
  44. ]);
  45. //check for roles creation rights in postgresql
  46. $builder = $connection->getQueryBuilder();
  47. $builder->automaticTablePrefix(false);
  48. $query = $builder
  49. ->select('rolname')
  50. ->from('pg_roles')
  51. ->where($builder->expr()->eq('rolcreaterole', new Literal('TRUE')))
  52. ->andWhere($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  53. try {
  54. $result = $query->execute();
  55. $canCreateRoles = $result->rowCount() > 0;
  56. } catch (DatabaseException $e) {
  57. $canCreateRoles = false;
  58. }
  59. if ($canCreateRoles) {
  60. $connectionMainDatabase = $this->connect();
  61. //use the admin login data for the new database user
  62. //add prefix to the postgresql user name to prevent collisions
  63. $this->dbUser = 'oc_' . strtolower($username);
  64. //create a new password so we don't need to store the admin config in the config file
  65. $this->dbPassword = \OC::$server->getSecureRandom()->generate(30, ISecureRandom::CHAR_ALPHANUMERIC);
  66. $this->createDBUser($connection);
  67. // Go to the main database and grant create on the public schema
  68. // The code below is implemented to make installing possible with PostgreSQL version 15:
  69. // https://www.postgresql.org/docs/release/15.0/
  70. // From the release notes: For new databases having no need to defend against insider threats, granting CREATE permission will yield the behavior of prior releases
  71. // Therefore we assume that the database is only used by one user/service which is Nextcloud
  72. // Additional services should get installed in a separate database in order to stay secure
  73. // Also see https://www.postgresql.org/docs/15/ddl-schemas.html#DDL-SCHEMAS-PATTERNS
  74. $connectionMainDatabase->executeQuery('GRANT CREATE ON SCHEMA public TO ' . addslashes($this->dbUser));
  75. $connectionMainDatabase->close();
  76. }
  77. $this->config->setValues([
  78. 'dbuser' => $this->dbUser,
  79. 'dbpassword' => $this->dbPassword,
  80. ]);
  81. //create the database
  82. $this->createDatabase($connection);
  83. // the connection to dbname=postgres is not needed anymore
  84. $connection->close();
  85. } catch (\Exception $e) {
  86. $this->logger->warning('Error trying to connect as "postgres", assuming database is setup and tables need to be created', [
  87. 'exception' => $e,
  88. ]);
  89. $this->config->setValues([
  90. 'dbuser' => $this->dbUser,
  91. 'dbpassword' => $this->dbPassword,
  92. ]);
  93. }
  94. // connect to the database (dbname=$this->dbname) and check if it needs to be filled
  95. $this->dbUser = $this->config->getValue('dbuser');
  96. $this->dbPassword = $this->config->getValue('dbpassword');
  97. $connection = $this->connect();
  98. try {
  99. $connection->connect();
  100. } catch (\Exception $e) {
  101. $this->logger->error($e->getMessage(), [
  102. 'exception' => $e,
  103. ]);
  104. throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'),
  105. $this->trans->t('You need to enter details of an existing account.'), 0, $e);
  106. }
  107. }
  108. private function createDatabase(Connection $connection) {
  109. if (!$this->databaseExists($connection)) {
  110. //The database does not exists... let's create it
  111. $query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER " . addslashes($this->dbUser));
  112. try {
  113. $query->execute();
  114. } catch (DatabaseException $e) {
  115. $this->logger->error('Error while trying to create database', [
  116. 'exception' => $e,
  117. ]);
  118. }
  119. } else {
  120. $query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
  121. try {
  122. $query->execute();
  123. } catch (DatabaseException $e) {
  124. $this->logger->error('Error while trying to restrict database permissions', [
  125. 'exception' => $e,
  126. ]);
  127. }
  128. }
  129. }
  130. private function userExists(Connection $connection) {
  131. $builder = $connection->getQueryBuilder();
  132. $builder->automaticTablePrefix(false);
  133. $query = $builder->select('*')
  134. ->from('pg_roles')
  135. ->where($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  136. $result = $query->execute();
  137. return $result->rowCount() > 0;
  138. }
  139. private function databaseExists(Connection $connection) {
  140. $builder = $connection->getQueryBuilder();
  141. $builder->automaticTablePrefix(false);
  142. $query = $builder->select('datname')
  143. ->from('pg_database')
  144. ->where($builder->expr()->eq('datname', $builder->createNamedParameter($this->dbName)));
  145. $result = $query->execute();
  146. return $result->rowCount() > 0;
  147. }
  148. private function createDBUser(Connection $connection) {
  149. $dbUser = $this->dbUser;
  150. try {
  151. $i = 1;
  152. while ($this->userExists($connection)) {
  153. $i++;
  154. $this->dbUser = $dbUser . $i;
  155. }
  156. // create the user
  157. $query = $connection->prepare("CREATE USER " . addslashes($this->dbUser) . " CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
  158. $query->execute();
  159. if ($this->databaseExists($connection)) {
  160. $query = $connection->prepare('GRANT CONNECT ON DATABASE ' . addslashes($this->dbName) . ' TO '.addslashes($this->dbUser));
  161. $query->execute();
  162. }
  163. } catch (DatabaseException $e) {
  164. $this->logger->error('Error while trying to create database user', [
  165. 'exception' => $e,
  166. ]);
  167. }
  168. }
  169. }