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.

168 lines
5.7 KiB

3 years ago
  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. * @author Roeland Jago Douma <roeland@famdouma.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\QueryBuilder\Literal;
  32. use OCP\IDBConnection;
  33. class PostgreSQL extends AbstractDatabase {
  34. public $dbprettyname = 'PostgreSQL';
  35. /**
  36. * @param string $username
  37. * @throws \OC\DatabaseSetupException
  38. */
  39. public function setupDatabase($username) {
  40. try {
  41. $connection = $this->connect([
  42. 'dbname' => 'postgres'
  43. ]);
  44. //check for roles creation rights in postgresql
  45. $builder = $connection->getQueryBuilder();
  46. $builder->automaticTablePrefix(false);
  47. $query = $builder
  48. ->select('rolname')
  49. ->from('pg_roles')
  50. ->where($builder->expr()->eq('rolcreaterole', new Literal('TRUE')))
  51. ->andWhere($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  52. try {
  53. $result = $query->execute();
  54. $canCreateRoles = $result->rowCount() > 0;
  55. } catch (DatabaseException $e) {
  56. $canCreateRoles = false;
  57. }
  58. if ($canCreateRoles) {
  59. //use the admin login data for the new database user
  60. //add prefix to the postgresql user name to prevent collisions
  61. $this->dbUser = 'oc_' . strtolower($username);
  62. //create a new password so we don't need to store the admin config in the config file
  63. $this->dbPassword = \OC::$server->getSecureRandom()->generate(30, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
  64. $this->createDBUser($connection);
  65. }
  66. $this->config->setValues([
  67. 'dbuser' => $this->dbUser,
  68. 'dbpassword' => $this->dbPassword,
  69. ]);
  70. //create the database
  71. $this->createDatabase($connection);
  72. // the connection to dbname=postgres is not needed anymore
  73. $connection->close();
  74. } catch (\Exception $e) {
  75. $this->logger->logException($e);
  76. $this->logger->warning('Error trying to connect as "postgres", assuming database is setup and tables need to be created');
  77. $this->config->setValues([
  78. 'dbuser' => $this->dbUser,
  79. 'dbpassword' => $this->dbPassword,
  80. ]);
  81. }
  82. // connect to the database (dbname=$this->dbname) and check if it needs to be filled
  83. $this->dbUser = $this->config->getValue('dbuser');
  84. $this->dbPassword = $this->config->getValue('dbpassword');
  85. $connection = $this->connect();
  86. try {
  87. $connection->connect();
  88. } catch (\Exception $e) {
  89. $this->logger->logException($e);
  90. throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'),
  91. $this->trans->t('You need to enter details of an existing account.'));
  92. }
  93. }
  94. private function createDatabase(IDBConnection $connection) {
  95. if (!$this->databaseExists($connection)) {
  96. //The database does not exists... let's create it
  97. $query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER " . addslashes($this->dbUser));
  98. try {
  99. $query->execute();
  100. } catch (DatabaseException $e) {
  101. $this->logger->error('Error while trying to create database');
  102. $this->logger->logException($e);
  103. }
  104. } else {
  105. $query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
  106. try {
  107. $query->execute();
  108. } catch (DatabaseException $e) {
  109. $this->logger->error('Error while trying to restrict database permissions');
  110. $this->logger->logException($e);
  111. }
  112. }
  113. }
  114. private function userExists(IDBConnection $connection) {
  115. $builder = $connection->getQueryBuilder();
  116. $builder->automaticTablePrefix(false);
  117. $query = $builder->select('*')
  118. ->from('pg_roles')
  119. ->where($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  120. $result = $query->execute();
  121. return $result->rowCount() > 0;
  122. }
  123. private function databaseExists(IDBConnection $connection) {
  124. $builder = $connection->getQueryBuilder();
  125. $builder->automaticTablePrefix(false);
  126. $query = $builder->select('datname')
  127. ->from('pg_database')
  128. ->where($builder->expr()->eq('datname', $builder->createNamedParameter($this->dbName)));
  129. $result = $query->execute();
  130. return $result->rowCount() > 0;
  131. }
  132. private function createDBUser(IDBConnection $connection) {
  133. $dbUser = $this->dbUser;
  134. try {
  135. $i = 1;
  136. while ($this->userExists($connection)) {
  137. $i++;
  138. $this->dbUser = $dbUser . $i;
  139. }
  140. // create the user
  141. $query = $connection->prepare("CREATE USER " . addslashes($this->dbUser) . " CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
  142. $query->execute();
  143. if ($this->databaseExists($connection)) {
  144. $query = $connection->prepare('GRANT CONNECT ON DATABASE ' . addslashes($this->dbName) . ' TO '.addslashes($this->dbUser));
  145. $query->execute();
  146. }
  147. } catch (DatabaseException $e) {
  148. $this->logger->error('Error while trying to create database user');
  149. $this->logger->logException($e);
  150. }
  151. }
  152. }