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.

PostgreSQL.php 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. //use the admin login data for the new database user
  61. //add prefix to the postgresql user name to prevent collisions
  62. $this->dbUser = 'oc_' . strtolower($username);
  63. //create a new password so we don't need to store the admin config in the config file
  64. $this->dbPassword = \OC::$server->getSecureRandom()->generate(30, ISecureRandom::CHAR_ALPHANUMERIC);
  65. $this->createDBUser($connection);
  66. }
  67. $this->config->setValues([
  68. 'dbuser' => $this->dbUser,
  69. 'dbpassword' => $this->dbPassword,
  70. ]);
  71. //create the database
  72. $this->createDatabase($connection);
  73. // the connection to dbname=postgres is not needed anymore
  74. $connection->close();
  75. } catch (\Exception $e) {
  76. $this->logger->warning('Error trying to connect as "postgres", assuming database is setup and tables need to be created', [
  77. 'exception' => $e,
  78. ]);
  79. $this->config->setValues([
  80. 'dbuser' => $this->dbUser,
  81. 'dbpassword' => $this->dbPassword,
  82. ]);
  83. }
  84. // connect to the database (dbname=$this->dbname) and check if it needs to be filled
  85. $this->dbUser = $this->config->getValue('dbuser');
  86. $this->dbPassword = $this->config->getValue('dbpassword');
  87. $connection = $this->connect();
  88. try {
  89. $connection->connect();
  90. } catch (\Exception $e) {
  91. $this->logger->error($e->getMessage(), [
  92. 'exception' => $e,
  93. ]);
  94. throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'),
  95. $this->trans->t('You need to enter details of an existing account.'), 0, $e);
  96. }
  97. }
  98. private function createDatabase(Connection $connection) {
  99. if (!$this->databaseExists($connection)) {
  100. //The database does not exists... let's create it
  101. $query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER " . addslashes($this->dbUser));
  102. try {
  103. $query->execute();
  104. } catch (DatabaseException $e) {
  105. $this->logger->error('Error while trying to create database', [
  106. 'exception' => $e,
  107. ]);
  108. }
  109. } else {
  110. $query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
  111. try {
  112. $query->execute();
  113. } catch (DatabaseException $e) {
  114. $this->logger->error('Error while trying to restrict database permissions', [
  115. 'exception' => $e,
  116. ]);
  117. }
  118. }
  119. }
  120. private function userExists(Connection $connection) {
  121. $builder = $connection->getQueryBuilder();
  122. $builder->automaticTablePrefix(false);
  123. $query = $builder->select('*')
  124. ->from('pg_roles')
  125. ->where($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  126. $result = $query->execute();
  127. return $result->rowCount() > 0;
  128. }
  129. private function databaseExists(Connection $connection) {
  130. $builder = $connection->getQueryBuilder();
  131. $builder->automaticTablePrefix(false);
  132. $query = $builder->select('datname')
  133. ->from('pg_database')
  134. ->where($builder->expr()->eq('datname', $builder->createNamedParameter($this->dbName)));
  135. $result = $query->execute();
  136. return $result->rowCount() > 0;
  137. }
  138. private function createDBUser(Connection $connection) {
  139. $dbUser = $this->dbUser;
  140. try {
  141. $i = 1;
  142. while ($this->userExists($connection)) {
  143. $i++;
  144. $this->dbUser = $dbUser . $i;
  145. }
  146. // create the user
  147. $query = $connection->prepare("CREATE USER " . addslashes($this->dbUser) . " CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
  148. $query->execute();
  149. if ($this->databaseExists($connection)) {
  150. $query = $connection->prepare('GRANT CONNECT ON DATABASE ' . addslashes($this->dbName) . ' TO '.addslashes($this->dbUser));
  151. $query->execute();
  152. }
  153. } catch (DatabaseException $e) {
  154. $this->logger->error('Error while trying to create database user', [
  155. 'exception' => $e,
  156. ]);
  157. }
  158. }
  159. }