PostgreSQL.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author eduardo <eduardo@vnexu.net>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\Setup;
  28. use OC\DatabaseException;
  29. use OC\DB\QueryBuilder\Literal;
  30. use OCP\IDBConnection;
  31. class PostgreSQL extends AbstractDatabase {
  32. public $dbprettyname = 'PostgreSQL';
  33. /**
  34. * @param string $username
  35. * @throws \OC\DatabaseSetupException
  36. * @suppress SqlInjectionChecker
  37. */
  38. public function setupDatabase($username) {
  39. try {
  40. $connection = $this->connect([
  41. 'dbname' => 'postgres'
  42. ]);
  43. //check for roles creation rights in postgresql
  44. $builder = $connection->getQueryBuilder();
  45. $builder->automaticTablePrefix(false);
  46. $query = $builder
  47. ->select('rolname')
  48. ->from('pg_roles')
  49. ->where($builder->expr()->eq('rolcreaterole', new Literal('TRUE')))
  50. ->andWhere($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  51. try {
  52. $result = $query->execute();
  53. $canCreateRoles = $result->rowCount() > 0;
  54. } catch (DatabaseException $e) {
  55. $canCreateRoles = false;
  56. }
  57. if ($canCreateRoles) {
  58. //use the admin login data for the new database user
  59. //add prefix to the postgresql user name to prevent collisions
  60. $this->dbUser = 'oc_' . strtolower($username);
  61. //create a new password so we don't need to store the admin config in the config file
  62. $this->dbPassword = \OC::$server->getSecureRandom()->generate(30, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
  63. $this->createDBUser($connection);
  64. }
  65. $this->config->setValues([
  66. 'dbuser' => $this->dbUser,
  67. 'dbpassword' => $this->dbPassword,
  68. ]);
  69. //create the database
  70. $this->createDatabase($connection);
  71. $query = $connection->prepare("select count(*) FROM pg_class WHERE relname=? limit 1");
  72. $query->execute([$this->tablePrefix . "users"]);
  73. $tablesSetup = $query->fetchColumn() > 0;
  74. // the connection to dbname=postgres is not needed anymore
  75. $connection->close();
  76. } catch (\Exception $e) {
  77. $this->logger->logException($e);
  78. $this->logger->warning('Error trying to connect as "postgres", assuming database is setup and tables need to be created');
  79. $tablesSetup = false;
  80. $this->config->setValues([
  81. 'dbuser' => $this->dbUser,
  82. 'dbpassword' => $this->dbPassword,
  83. ]);
  84. }
  85. // connect to the ownCloud database (dbname=$this->dbname) and check if it needs to be filled
  86. $this->dbUser = $this->config->getValue('dbuser');
  87. $this->dbPassword = $this->config->getValue('dbpassword');
  88. $connection = $this->connect();
  89. try {
  90. $connection->connect();
  91. } catch (\Exception $e) {
  92. $this->logger->logException($e);
  93. throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'),
  94. $this->trans->t('You need to enter details of an existing account.'));
  95. }
  96. }
  97. private function createDatabase(IDBConnection $connection) {
  98. if (!$this->databaseExists($connection)) {
  99. //The database does not exists... let's create it
  100. $query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER " . addslashes($this->dbUser));
  101. try {
  102. $query->execute();
  103. } catch (DatabaseException $e) {
  104. $this->logger->error('Error while trying to create database');
  105. $this->logger->logException($e);
  106. }
  107. } else {
  108. $query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
  109. try {
  110. $query->execute();
  111. } catch (DatabaseException $e) {
  112. $this->logger->error('Error while trying to restrict database permissions');
  113. $this->logger->logException($e);
  114. }
  115. }
  116. }
  117. private function userExists(IDBConnection $connection) {
  118. $builder = $connection->getQueryBuilder();
  119. $builder->automaticTablePrefix(false);
  120. $query = $builder->select('*')
  121. ->from('pg_roles')
  122. ->where($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  123. $result = $query->execute();
  124. return $result->rowCount() > 0;
  125. }
  126. private function databaseExists(IDBConnection $connection) {
  127. $builder = $connection->getQueryBuilder();
  128. $builder->automaticTablePrefix(false);
  129. $query = $builder->select('datname')
  130. ->from('pg_database')
  131. ->where($builder->expr()->eq('datname', $builder->createNamedParameter($this->dbName)));
  132. $result = $query->execute();
  133. return $result->rowCount() > 0;
  134. }
  135. private function createDBUser(IDBConnection $connection) {
  136. $dbUser = $this->dbUser;
  137. try {
  138. $i = 1;
  139. while ($this->userExists($connection)) {
  140. $i++;
  141. $this->dbUser = $dbUser . $i;
  142. }
  143. // create the user
  144. $query = $connection->prepare("CREATE USER " . addslashes($this->dbUser) . " CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
  145. $query->execute();
  146. } catch (DatabaseException $e) {
  147. $this->logger->error('Error while trying to create database user');
  148. $this->logger->logException($e);
  149. }
  150. }
  151. }