From dd095e8933c949e6881f50a999302d1f0bd0eff7 Mon Sep 17 00:00:00 2001 From: Duncan Sommerville Date: Mon, 9 Feb 2015 17:41:03 -0500 Subject: [PATCH 1/6] Added create endpoint to provisioning controller, fixed RestAuth helper --- .../controllers/ProvisioningController.php | 99 +++++++++++---- .../modules/rest/helpers/RestAuth.php | 118 +++++++++--------- 2 files changed, 134 insertions(+), 83 deletions(-) diff --git a/airtime_mvc/application/controllers/ProvisioningController.php b/airtime_mvc/application/controllers/ProvisioningController.php index e847ff661..4186fd05b 100644 --- a/airtime_mvc/application/controllers/ProvisioningController.php +++ b/airtime_mvc/application/controllers/ProvisioningController.php @@ -6,9 +6,16 @@ use Aws\S3\S3Client; class ProvisioningController extends Zend_Controller_Action { + + static $dbh; + + // Parameter values + private $dbuser, $dbpass, $dbname, $dbhost; + public function init() { } + /** * Delete the Airtime Pro station's files from Amazon S3 */ @@ -16,8 +23,8 @@ class ProvisioningController extends Zend_Controller_Action { $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - - if (!$this->verifyAPIKey()) { + + if (!RestAuth::verifyAuth(true, true, $this)) { return; } @@ -33,27 +40,75 @@ class ProvisioningController extends Zend_Controller_Action ->appendBody("OK"); } - private function verifyAPIKey() - { - // The API key is passed in via HTTP "basic authentication": - // http://en.wikipedia.org/wiki/Basic_access_authentication - - $CC_CONFIG = Config::getConfig(); - - // Decode the API key that was passed to us in the HTTP request. - $authHeader = $this->getRequest()->getHeader("Authorization"); - $encodedRequestApiKey = substr($authHeader, strlen("Basic ")); - $encodedStoredApiKey = base64_encode($CC_CONFIG["apiKey"][0] . ":"); - - if ($encodedRequestApiKey === $encodedStoredApiKey) - { - return true; + /** + * RESTful endpoint for setting up and installing the Airtime database + */ + public function createDatabaseAction() { + Logging::info("Create Database action received"); + + if (!RestAuth::verifyAuth(true, true, $this)) { + return; } - + + try { + $this->getParams(); + $this->setNewDatabaseConnection(); + $this->createDatabaseTables(); + } catch(Exception $e) { + $this->getResponse() + ->setHttpResponseCode(400) + ->appendBody($e->getMessage()); + return; + } + $this->getResponse() - ->setHttpResponseCode(401) - ->appendBody("ERROR: Incorrect API key."); - - return false; + ->setHttpResponseCode(201); } + + private function getParams() { + $this->dbuser = $this->_getParam('dbuser', ''); + $this->dbpass = $this->_getParam('dbpass', ''); + $this->dbname = $this->_getParam('dbname', ''); + $this->dbhost = $this->_getParam('dbhost', ''); + } + + /** + * Set up a new database connection based on the parameters in the request + * @throws PDOException upon failure to connect + */ + private function setNewDatabaseConnection() { + self::$dbh = new PDO("pgsql:host=" . $this->dbhost + . ";dbname=" . $this->dbname + . ";port=5432" . ";user=" . $this->dbuser + . ";password=" . $this->dbpass); + $err = self::$dbh->errorInfo(); + if ($err[1] != null) { + throw new PDOException("ERROR: Could not connect to database"); + } + } + + /** + * Install the Airtime database + * @throws Exception + */ + private function createDatabaseTables() { + $sqlDir = dirname(APPLICATION_PATH) . "/build/sql/"; + $files = array("schema.sql", "sequences.sql", "views.sql", "triggers.sql", "defaultdata.sql"); + foreach ($files as $f) { + try { + /* + * Unfortunately, we need to use exec here due to PDO's lack of support for importing + * multi-line .sql files. PDO->exec() almost works, but any SQL errors stop the import, + * so the necessary DROPs on non-existent tables make it unusable. Prepared statements + * have multiple issues; they similarly die on any SQL errors, fail to read in multi-line + * commands, and fail on any unescaped ? or $ characters. + */ + exec("export PGPASSWORD=" . $this->dbpass . " && psql -U " . $this->dbuser . " --dbname " + . $this->dbname . " -h " . $this->dbhost . " -f $sqlDir$f 2>/dev/null", $out, $status); + } catch (Exception $e) { + throw new Exception("ERROR: Failed to create database tables"); + } + } + } + } diff --git a/airtime_mvc/application/modules/rest/helpers/RestAuth.php b/airtime_mvc/application/modules/rest/helpers/RestAuth.php index 6024ad582..d7390ab8b 100644 --- a/airtime_mvc/application/modules/rest/helpers/RestAuth.php +++ b/airtime_mvc/application/modules/rest/helpers/RestAuth.php @@ -1,64 +1,60 @@ getResponse(); - $resp->setHttpResponseCode(401); - $resp->appendBody("ERROR: Incorrect API key."); - - return false; - } - - public static function getOwnerId() - { - try { - if (RestAuth::verifySession()) { - $service_user = new Application_Service_UserService(); - return $service_user->getCurrentUser()->getDbId(); - } else { - $defaultOwner = CcSubjsQuery::create() - ->filterByDbType('A') - ->orderByDbId() - ->findOne(); - if (!$defaultOwner) { - // what to do if there is no admin user? - // should we handle this case? - return null; - } - return $defaultOwner->getDbId(); - } - } catch(Exception $e) { - Logging::info($e->getMessage()); - } - } - - private static function verifySession() - { - $auth = Zend_Auth::getInstance(); - return $auth->hasIdentity(); - } - - private static function verifyAPIKey() - { - //The API key is passed in via HTTP "basic authentication": - // http://en.wikipedia.org/wiki/Basic_access_authentication - $CC_CONFIG = Config::getConfig(); - - //Decode the API key that was passed to us in the HTTP request. - $authHeader = $this->getRequest()->getHeader("Authorization"); - $encodedRequestApiKey = substr($authHeader, strlen("Basic ")); - $encodedStoredApiKey = base64_encode($CC_CONFIG["apiKey"][0] . ":"); - - return ($encodedRequestApiKey === $encodedStoredApiKey); - } - +class RestAuth { + + public static function verifyAuth($checkApiKey, $checkSession, $action) { + //Session takes precedence over API key for now: + if ($checkSession && self::verifySession() + || $checkApiKey && self::verifyAPIKey($action) + ) { + return true; + } + + $action->getResponse() + ->setHttpResponseCode(401) + ->appendBody(json_encode(array("message" => "ERROR: Incorrect API key."))); + + return false; + } + + public static function getOwnerId() { + try { + if (self::verifySession()) { + $service_user = new Application_Service_UserService(); + return $service_user->getCurrentUser()->getDbId(); + } else { + $defaultOwner = CcSubjsQuery::create() + ->filterByDbType(array('A', 'S'), Criteria::IN) + ->orderByDbId() + ->findOne(); + if (!$defaultOwner) { + // what to do if there is no admin user? + // should we handle this case? + return null; + } + return $defaultOwner->getDbId(); + } + } catch (Exception $e) { + Logging::info($e->getMessage()); + } + } + + private static function verifySession() { + $auth = Zend_Auth::getInstance(); + return $auth->hasIdentity(); + } + + private static function verifyAPIKey($action) { + //The API key is passed in via HTTP "basic authentication": + // http://en.wikipedia.org/wiki/Basic_access_authentication + $CC_CONFIG = Config::getConfig(); + + //Decode the API key that was passed to us in the HTTP request. + $authHeader = $action->getRequest()->getHeader("Authorization"); + $encodedRequestApiKey = substr($authHeader, strlen("Basic ")); + $encodedStoredApiKey = base64_encode($CC_CONFIG["apiKey"][0] . ":"); + + return ($encodedRequestApiKey === $encodedStoredApiKey); + } + } \ No newline at end of file From ad5536dedd762bf3078a7c802333d6e01d3dc1e1 Mon Sep 17 00:00:00 2001 From: Duncan Sommerville Date: Thu, 12 Feb 2015 15:39:22 -0500 Subject: [PATCH 2/6] SAAS-582 - Added provisioning class to create database from within Airtime --- airtime_mvc/application/Bootstrap.php | 6 + .../application/common/ProvisioningHelper.php | 132 ++++++++++++++++++ .../controllers/ProvisioningController.php | 76 ---------- 3 files changed, 138 insertions(+), 76 deletions(-) create mode 100644 airtime_mvc/application/common/ProvisioningHelper.php diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index 988e5ee4a..fb6ec0ddc 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -21,6 +21,7 @@ require_once "LocaleHelper.php"; require_once "HTTPHelper.php"; require_once "OsPath.php"; require_once "Database.php"; +require_once "ProvisioningHelper.php"; require_once "Timezone.php"; require_once "Auth.php"; require_once __DIR__.'/forms/helpers/ValidationTypes.php'; @@ -33,6 +34,11 @@ require_once __DIR__.'/modules/rest/controllers/MediaController.php'; require_once (APPLICATION_PATH."/logging/Logging.php"); Logging::setLogPath('/var/log/airtime/zendphp.log'); +if (strpos("/provisioning/create-database", $_SERVER["REDIRECT_URL"]) !== false) { + (new ProvisioningHelper($CC_CONFIG["apiKey"][0]))->createDatabaseAction(); + die; +} + Config::setAirtimeVersion(); require_once __DIR__."/configs/navigation.php"; diff --git a/airtime_mvc/application/common/ProvisioningHelper.php b/airtime_mvc/application/common/ProvisioningHelper.php new file mode 100644 index 000000000..0537f5f60 --- /dev/null +++ b/airtime_mvc/application/common/ProvisioningHelper.php @@ -0,0 +1,132 @@ +apikey = $apikey; + } + + /** + * Endpoint for setting up and installing the Airtime database + */ + public function createDatabaseAction() { + Logging::info("Create Database action received"); + + $this->getParams(); + Logging::info("Parameters: " + . "\nUser: " . $this->dbuser + . "\nPass: " . $this->dbpass + . "\nName: " . $this->dbname + . "\nHost: " . $this->dbhost + . "\nOwner: " . $this->dbowner); + + $apikey = $_SERVER['PHP_AUTH_USER']; + if (!isset($apikey) || $apikey != $this->apikey) { + Logging::info("Invalid API Key: $apikey"); + http_response_code(403); + echo "ERROR: Incorrect API key"; + return; + } + + try { + $this->setNewDatabaseConnection(); + if ($this->checkDatabaseExists()) { + throw new Exception("ERROR: Airtime database already exists"); + } + $this->createDatabase(); + $this->createDatabaseTables(); + } catch(Exception $e) { + http_response_code(400); + Logging::info($e->getMessage()); + echo $e->getMessage(); + return; + } + + http_response_code(201); + } + + /** + * Check if the database settings and credentials given are valid + * @return boolean true if the database given exists and the user is valid and can access it + */ + private function checkDatabaseExists() { + $statement = self::$dbh->prepare("SELECT datname FROM pg_database WHERE datname = :dbname"); + $statement->execute(array(":dbname" => $this->dbname)); + $result = $statement->fetch(); + return isset($result[0]); + } + + private function getParams() { + $params = []; + parse_str($_SERVER["QUERY_STRING"], $params); + foreach ($params as $k => $v) { + $this->$k = $v; + } + } + + /** + * Set up a new database connection based on the parameters in the request + * @throws PDOException upon failure to connect + */ + private function setNewDatabaseConnection() { + self::$dbh = new PDO("pgsql:host=" . $this->dbhost + . ";dbname=postgres" + . ";port=5432" . ";user=" . $this->dbuser + . ";password=" . $this->dbpass); + $err = self::$dbh->errorInfo(); + if ($err[1] != null) { + throw new PDOException("ERROR: Could not connect to database"); + } + } + + /** + * Creates the Airtime database using the given credentials + * @throws Exception + */ + private function createDatabase() { + Logging::info("Creating database..."); + $statement = self::$dbh->prepare("CREATE DATABASE " . pg_escape_string($this->dbname) + . " WITH ENCODING 'UTF8' TEMPLATE template0" + . " OWNER " . pg_escape_string($this->dbowner)); + if (!$statement->execute()) { + throw new Exception("ERROR: Failed to create Airtime database"); + } + } + + /** + * Install the Airtime database + * @throws Exception + */ + private function createDatabaseTables() { + $sqlDir = dirname(APPLICATION_PATH) . "/build/sql/"; + $files = array("schema.sql", "sequences.sql", "views.sql", "triggers.sql", "defaultdata.sql"); + foreach ($files as $f) { + try { + /* + * Unfortunately, we need to use exec here due to PDO's lack of support for importing + * multi-line .sql files. PDO->exec() almost works, but any SQL errors stop the import, + * so the necessary DROPs on non-existent tables make it unusable. Prepared statements + * have multiple issues; they similarly die on any SQL errors, fail to read in multi-line + * commands, and fail on any unescaped ? or $ characters. + */ + exec("export PGPASSWORD=" . $this->dbpass . " && psql -U " . $this->dbuser . " --dbname " + . $this->dbname . " -h " . $this->dbhost . " -f $sqlDir$f 2>/dev/null", $out, $status); + } catch (Exception $e) { + throw new Exception("ERROR: Failed to create database tables"); + } + } + } + +} \ No newline at end of file diff --git a/airtime_mvc/application/controllers/ProvisioningController.php b/airtime_mvc/application/controllers/ProvisioningController.php index 4186fd05b..6c2ea2a5d 100644 --- a/airtime_mvc/application/controllers/ProvisioningController.php +++ b/airtime_mvc/application/controllers/ProvisioningController.php @@ -7,11 +7,6 @@ use Aws\S3\S3Client; class ProvisioningController extends Zend_Controller_Action { - static $dbh; - - // Parameter values - private $dbuser, $dbpass, $dbname, $dbhost; - public function init() { } @@ -39,76 +34,5 @@ class ProvisioningController extends Zend_Controller_Action ->setHttpResponseCode(200) ->appendBody("OK"); } - - /** - * RESTful endpoint for setting up and installing the Airtime database - */ - public function createDatabaseAction() { - Logging::info("Create Database action received"); - - if (!RestAuth::verifyAuth(true, true, $this)) { - return; - } - - try { - $this->getParams(); - $this->setNewDatabaseConnection(); - $this->createDatabaseTables(); - } catch(Exception $e) { - $this->getResponse() - ->setHttpResponseCode(400) - ->appendBody($e->getMessage()); - return; - } - - $this->getResponse() - ->setHttpResponseCode(201); - } - - private function getParams() { - $this->dbuser = $this->_getParam('dbuser', ''); - $this->dbpass = $this->_getParam('dbpass', ''); - $this->dbname = $this->_getParam('dbname', ''); - $this->dbhost = $this->_getParam('dbhost', ''); - } - - /** - * Set up a new database connection based on the parameters in the request - * @throws PDOException upon failure to connect - */ - private function setNewDatabaseConnection() { - self::$dbh = new PDO("pgsql:host=" . $this->dbhost - . ";dbname=" . $this->dbname - . ";port=5432" . ";user=" . $this->dbuser - . ";password=" . $this->dbpass); - $err = self::$dbh->errorInfo(); - if ($err[1] != null) { - throw new PDOException("ERROR: Could not connect to database"); - } - } - - /** - * Install the Airtime database - * @throws Exception - */ - private function createDatabaseTables() { - $sqlDir = dirname(APPLICATION_PATH) . "/build/sql/"; - $files = array("schema.sql", "sequences.sql", "views.sql", "triggers.sql", "defaultdata.sql"); - foreach ($files as $f) { - try { - /* - * Unfortunately, we need to use exec here due to PDO's lack of support for importing - * multi-line .sql files. PDO->exec() almost works, but any SQL errors stop the import, - * so the necessary DROPs on non-existent tables make it unusable. Prepared statements - * have multiple issues; they similarly die on any SQL errors, fail to read in multi-line - * commands, and fail on any unescaped ? or $ characters. - */ - exec("export PGPASSWORD=" . $this->dbpass . " && psql -U " . $this->dbuser . " --dbname " - . $this->dbname . " -h " . $this->dbhost . " -f $sqlDir$f 2>/dev/null", $out, $status); - } catch (Exception $e) { - throw new Exception("ERROR: Failed to create database tables"); - } - } - } } From e6035971015f21d0c2d811f1ea87197049be39f1 Mon Sep 17 00:00:00 2001 From: Albert Santoni Date: Tue, 17 Feb 2015 12:13:37 -0500 Subject: [PATCH 3/6] Cleanup and comments --- airtime_mvc/application/Bootstrap.php | 8 +++++--- .../application/common/ProvisioningHelper.php | 12 +++--------- .../controllers/ProvisioningController.php | 7 +++++++ 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index fb6ec0ddc..9fb3dd5c0 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -34,9 +34,11 @@ require_once __DIR__.'/modules/rest/controllers/MediaController.php'; require_once (APPLICATION_PATH."/logging/Logging.php"); Logging::setLogPath('/var/log/airtime/zendphp.log'); -if (strpos("/provisioning/create-database", $_SERVER["REDIRECT_URL"]) !== false) { - (new ProvisioningHelper($CC_CONFIG["apiKey"][0]))->createDatabaseAction(); - die; +// We need to manually route because we can't load Zend without the database being initialized first. +if (strpos("/provisioning/create", $_SERVER["REDIRECT_URL"]) !== false) { + $provisioningHelper = new ProvisioningHelper($CC_CONFIG["apiKey"][0]); + $provisioningHelper->createAction(); + die(); } Config::setAirtimeVersion(); diff --git a/airtime_mvc/application/common/ProvisioningHelper.php b/airtime_mvc/application/common/ProvisioningHelper.php index 0537f5f60..95c180e61 100644 --- a/airtime_mvc/application/common/ProvisioningHelper.php +++ b/airtime_mvc/application/common/ProvisioningHelper.php @@ -19,18 +19,12 @@ class ProvisioningHelper { } /** - * Endpoint for setting up and installing the Airtime database + * Endpoint for setting up and installing the Airtime database. This all has to be done without Zend + * which is why the code looks so old school (eg. http_response_code). */ - public function createDatabaseAction() { - Logging::info("Create Database action received"); + public function createAction() { $this->getParams(); - Logging::info("Parameters: " - . "\nUser: " . $this->dbuser - . "\nPass: " . $this->dbpass - . "\nName: " . $this->dbname - . "\nHost: " . $this->dbhost - . "\nOwner: " . $this->dbowner); $apikey = $_SERVER['PHP_AUTH_USER']; if (!isset($apikey) || $apikey != $this->apikey) { diff --git a/airtime_mvc/application/controllers/ProvisioningController.php b/airtime_mvc/application/controllers/ProvisioningController.php index 6c2ea2a5d..fc0c28cbb 100644 --- a/airtime_mvc/application/controllers/ProvisioningController.php +++ b/airtime_mvc/application/controllers/ProvisioningController.php @@ -11,6 +11,13 @@ class ProvisioningController extends Zend_Controller_Action { } + /** + * + * The "create action" is in ProvisioningHelper because it needs to have no dependency on Zend, + * since when we bootstrap Zend, we already need the database set up and working (Bootstrap.php is a mess). + * + */ + /** * Delete the Airtime Pro station's files from Amazon S3 */ From d2fae5adaef267cd6292fc64140bebc4b3438433 Mon Sep 17 00:00:00 2001 From: Albert Santoni Date: Tue, 17 Feb 2015 16:49:52 -0500 Subject: [PATCH 4/6] Testing out only creating the database tables ... --- airtime_mvc/application/common/ProvisioningHelper.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/application/common/ProvisioningHelper.php b/airtime_mvc/application/common/ProvisioningHelper.php index 95c180e61..58e78b75f 100644 --- a/airtime_mvc/application/common/ProvisioningHelper.php +++ b/airtime_mvc/application/common/ProvisioningHelper.php @@ -35,11 +35,11 @@ class ProvisioningHelper { } try { - $this->setNewDatabaseConnection(); - if ($this->checkDatabaseExists()) { - throw new Exception("ERROR: Airtime database already exists"); - } - $this->createDatabase(); + // $this->setNewDatabaseConnection(); + //if ($this->checkDatabaseExists()) { + // throw new Exception("ERROR: Airtime database already exists"); + //} + //$this->createDatabase(); $this->createDatabaseTables(); } catch(Exception $e) { http_response_code(400); From dcac7ab65281f2ca6017ce5776bd421c9f19bf81 Mon Sep 17 00:00:00 2001 From: Albert Santoni Date: Wed, 18 Feb 2015 12:21:15 -0500 Subject: [PATCH 5/6] Fixed a couple of bugs in the new /provisioning/create API --- airtime_mvc/application/Bootstrap.php | 2 +- .../application/common/ProvisioningHelper.php | 92 ++++++++++--------- airtime_mvc/build/sql/defaultdata.sql | 3 + 3 files changed, 53 insertions(+), 44 deletions(-) diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index 9fb3dd5c0..bb0954694 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -35,7 +35,7 @@ require_once (APPLICATION_PATH."/logging/Logging.php"); Logging::setLogPath('/var/log/airtime/zendphp.log'); // We need to manually route because we can't load Zend without the database being initialized first. -if (strpos("/provisioning/create", $_SERVER["REDIRECT_URL"]) !== false) { +if (strpos($_SERVER["REQUEST_URI"], "/provisioning/create") !== false) { $provisioningHelper = new ProvisioningHelper($CC_CONFIG["apiKey"][0]); $provisioningHelper->createAction(); die(); diff --git a/airtime_mvc/application/common/ProvisioningHelper.php b/airtime_mvc/application/common/ProvisioningHelper.php index 58e78b75f..b745b639c 100644 --- a/airtime_mvc/application/common/ProvisioningHelper.php +++ b/airtime_mvc/application/common/ProvisioningHelper.php @@ -1,12 +1,8 @@ apikey = $apikey; } /** * Endpoint for setting up and installing the Airtime database. This all has to be done without Zend - * which is why the code looks so old school (eg. http_response_code). + * which is why the code looks so old school (eg. http_response_code). (We can't currently bootstrap our + * Zend app without the database unfortunately.) */ - public function createAction() { - - $this->getParams(); - + public function createAction() + { $apikey = $_SERVER['PHP_AUTH_USER']; if (!isset($apikey) || $apikey != $this->apikey) { Logging::info("Invalid API Key: $apikey"); @@ -35,15 +31,21 @@ class ProvisioningHelper { } try { - // $this->setNewDatabaseConnection(); + + $this->parsePostParams(); + + //For security, the Airtime Pro provisioning system creates the database for the user. + // $this->setNewDatabaseConnection(); //if ($this->checkDatabaseExists()) { // throw new Exception("ERROR: Airtime database already exists"); //} //$this->createDatabase(); + + //All we need to do is create the database tables. $this->createDatabaseTables(); - } catch(Exception $e) { + } catch (Exception $e) { http_response_code(400); - Logging::info($e->getMessage()); + Logging::error($e->getMessage()); echo $e->getMessage(); return; } @@ -55,30 +57,33 @@ class ProvisioningHelper { * Check if the database settings and credentials given are valid * @return boolean true if the database given exists and the user is valid and can access it */ - private function checkDatabaseExists() { + private function checkDatabaseExists() + { $statement = self::$dbh->prepare("SELECT datname FROM pg_database WHERE datname = :dbname"); $statement->execute(array(":dbname" => $this->dbname)); $result = $statement->fetch(); return isset($result[0]); } - private function getParams() { - $params = []; - parse_str($_SERVER["QUERY_STRING"], $params); - foreach ($params as $k => $v) { - $this->$k = $v; - } + private function parsePostParams() + { + $this->dbuser = $_POST['dbuser']; + $this->dbpass = $_POST['dbpass']; + $this->dbname = $_POST['dbname']; + $this->dbhost = $_POST['dbhost']; + $this->dbowner = $_POST['dbowner']; } /** * Set up a new database connection based on the parameters in the request * @throws PDOException upon failure to connect */ - private function setNewDatabaseConnection() { + private function setNewDatabaseConnection() + { self::$dbh = new PDO("pgsql:host=" . $this->dbhost - . ";dbname=postgres" - . ";port=5432" . ";user=" . $this->dbuser - . ";password=" . $this->dbpass); + . ";dbname=postgres" + . ";port=5432" . ";user=" . $this->dbuser + . ";password=" . $this->dbpass); $err = self::$dbh->errorInfo(); if ($err[1] != null) { throw new PDOException("ERROR: Could not connect to database"); @@ -89,11 +94,12 @@ class ProvisioningHelper { * Creates the Airtime database using the given credentials * @throws Exception */ - private function createDatabase() { + private function createDatabase() + { Logging::info("Creating database..."); $statement = self::$dbh->prepare("CREATE DATABASE " . pg_escape_string($this->dbname) - . " WITH ENCODING 'UTF8' TEMPLATE template0" - . " OWNER " . pg_escape_string($this->dbowner)); + . " WITH ENCODING 'UTF8' TEMPLATE template0" + . " OWNER " . pg_escape_string($this->dbowner)); if (!$statement->execute()) { throw new Exception("ERROR: Failed to create Airtime database"); } @@ -103,24 +109,24 @@ class ProvisioningHelper { * Install the Airtime database * @throws Exception */ - private function createDatabaseTables() { + private function createDatabaseTables() + { + Logging::info("Creating database tables..."); $sqlDir = dirname(APPLICATION_PATH) . "/build/sql/"; $files = array("schema.sql", "sequences.sql", "views.sql", "triggers.sql", "defaultdata.sql"); foreach ($files as $f) { - try { - /* - * Unfortunately, we need to use exec here due to PDO's lack of support for importing - * multi-line .sql files. PDO->exec() almost works, but any SQL errors stop the import, - * so the necessary DROPs on non-existent tables make it unusable. Prepared statements - * have multiple issues; they similarly die on any SQL errors, fail to read in multi-line - * commands, and fail on any unescaped ? or $ characters. - */ - exec("export PGPASSWORD=" . $this->dbpass . " && psql -U " . $this->dbuser . " --dbname " - . $this->dbname . " -h " . $this->dbhost . " -f $sqlDir$f 2>/dev/null", $out, $status); - } catch (Exception $e) { + /* + * Unfortunately, we need to use exec here due to PDO's lack of support for importing + * multi-line .sql files. PDO->exec() almost works, but any SQL errors stop the import, + * so the necessary DROPs on non-existent tables make it unusable. Prepared statements + * have multiple issues; they similarly die on any SQL errors, fail to read in multi-line + * commands, and fail on any unescaped ? or $ characters. + */ + exec("PGPASSWORD=$this->dbpass psql -U $this->dbuser --dbname $this->dbname -h $this->dbhost -f $sqlDir$f", $out, $status); + if ($status != 0) { throw new Exception("ERROR: Failed to create database tables"); } } } -} \ No newline at end of file +} diff --git a/airtime_mvc/build/sql/defaultdata.sql b/airtime_mvc/build/sql/defaultdata.sql index af82be2b8..3c1a60752 100644 --- a/airtime_mvc/build/sql/defaultdata.sql +++ b/airtime_mvc/build/sql/defaultdata.sql @@ -1,3 +1,6 @@ +-- Schema version +INSERT INTO cc_pref("keystr", "valstr") VALUES('system_version', '2.5.9'); + INSERT INTO cc_subjs ("login", "type", "pass") VALUES ('admin', 'A', md5('admin')); -- added in 2.3 INSERT INTO cc_stream_setting ("keyname", "value", "type") VALUES ('off_air_meta', 'Airtime - offline', 'string'); From 12c0617e57a12affa127cd6267a5937f99ee2821 Mon Sep 17 00:00:00 2001 From: Albert Santoni Date: Wed, 18 Feb 2015 13:27:52 -0500 Subject: [PATCH 6/6] Set up the cc_music_dirs entry in /provisioning/create --- .../application/common/ProvisioningHelper.php | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/airtime_mvc/application/common/ProvisioningHelper.php b/airtime_mvc/application/common/ProvisioningHelper.php index b745b639c..a396f3911 100644 --- a/airtime_mvc/application/common/ProvisioningHelper.php +++ b/airtime_mvc/application/common/ProvisioningHelper.php @@ -9,6 +9,7 @@ class ProvisioningHelper // Parameter values private $dbuser, $dbpass, $dbname, $dbhost, $dbowner, $apikey; + private $instanceId; public function __construct($apikey) { @@ -34,6 +35,8 @@ class ProvisioningHelper $this->parsePostParams(); + if (empty($this->instanceId)) + //For security, the Airtime Pro provisioning system creates the database for the user. // $this->setNewDatabaseConnection(); //if ($this->checkDatabaseExists()) { @@ -43,6 +46,7 @@ class ProvisioningHelper //All we need to do is create the database tables. $this->createDatabaseTables(); + $this->initializeMusicDirsTable($this->instanceId); } catch (Exception $e) { http_response_code(400); Logging::error($e->getMessage()); @@ -72,6 +76,7 @@ class ProvisioningHelper $this->dbname = $_POST['dbname']; $this->dbhost = $_POST['dbhost']; $this->dbowner = $_POST['dbowner']; + $this->instanceId = $_POST['instanceid']; } /** @@ -129,4 +134,26 @@ class ProvisioningHelper } } + private function initializeMusicDirsTable($instanceId) + { + if (!is_string($instanceId) || empty($instanceId) || !is_numeric($instanceId)) + { + throw new Exception("Invalid instance id: " . $instanceId); + } + + $instanceIdPrefix = $instanceId[0]; + + //Reinitialize Propel, just in case... + Propel::init(__DIR__."/../configs/airtime-conf-production.php"); + + //Create the cc_music_dir entry + $musicDir = new CcMusicDirs(); + $musicDir->setType("stor"); + $musicDir->setExists(true); + $musicDir->setWatched(true); + $musicDir->setDirectory("/mnt/airtimepro/instances/$instanceIdPrefix/$instanceId/srv/airtime/stor/"); + $musicDir->save(); + } + + }