Skip to content

Instantly share code, notes, and snippets.

@kyletaylored
Created September 30, 2021 19:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyletaylored/0ff616db4efb646d62fa9ed436b1e797 to your computer and use it in GitHub Desktop.
Save kyletaylored/0ff616db4efb646d62fa9ed436b1e797 to your computer and use it in GitHub Desktop.
Get Pantheon public database credentials for external integration
<?php
/**
* This is a script to retrieve DB credentials for database connections
*
*/
/**
* Check IP address function
*/
function checkIPAddress()
{
$allowed_ips_array = file(getcwd() . "/private/dbcr/allowed_ips.txt", FILE_IGNORE_NEW_LINES) or die("Unable to open ip list file!");
$ipArrayLength = count($allowed_ips_array);
if ($ipArrayLength > 0) {
if (in_array($_SERVER['REMOTE_ADDR'], $allowed_ips_array)) {
return true;
} else {
header("HTTP/1.0 404 Not Found");
exit;
}
} else {
return true;
}
}
/**
* Check authorization function
*/
function checkAuthCreds($posted_password)
{
$auth_password_object = fopen(getcwd() . "/private/dbcr/creds_pass.txt", "r") or die("Unable to open authorization file!");
$auth_password = fgets($auth_password_object);
$auth_password = str_replace("\r\n", "", $auth_password);
$auth_password = str_replace("\r", "", $auth_password);
$auth_password = str_replace("\n", "", $auth_password);
fclose($auth_password_object);
if ($posted_password == $auth_password) {
getDBCreds();
} else {
print $posted_password;
print $auth_password;
print "Invalid credentials.";
exit;
}
}
/**
* Retrieve DB Credentials
*/
function getDBCreds()
{
if (isset($_ENV['PANTHEON_ENVIRONMENT']) || isset($_ENV['LANDO_DOMAIN'])) {
if (function_exists('pantheon_curl')) {
$url = 'https://api.live.getpantheon.com/sites/self/variables';
$req = pantheon_curl($url, NULL, 8443);
$meta = json_decode($req['body'], true);
// Extract DB credentials
$db = json_encode([
'DB_USER' => $meta['username'],
'DB_PASSWORD' => $meta['password'],
'DB_HOST' => $meta['ideal_host'],
'DB_PORT' => $meta['port'],
'DB_NAME' => $meta['database']
]);
print($db);
}
} else {
die("This script will not run outside of the Pantheon Platform");
}
}
/**
* Init function to start execution of the script
*/
function credsInit()
{
if (isset($_GET['password'])) {
checkAuthCreds($_GET['password']);
} else {
print "Missing parameters.";
exit;
}
}
// Initiate the execution of the script.
// First, let's make sure Pantheon CDN does not cache these results
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
// Set the Content-Type header to application/json.
header('Content-Type: application/json');
// Now let's execute...
credsInit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment