From dd095e8933c949e6881f50a999302d1f0bd0eff7 Mon Sep 17 00:00:00 2001 From: Duncan Sommerville Date: Mon, 9 Feb 2015 17:41:03 -0500 Subject: [PATCH] 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