Skip to content

Commit

Permalink
Allow database authentication using .env file
Browse files Browse the repository at this point in the history
  • Loading branch information
Shadow243 committed Nov 10, 2023
1 parent 3789776 commit faf567b
Show file tree
Hide file tree
Showing 8 changed files with 228 additions and 26 deletions.
6 changes: 6 additions & 0 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
DB_DRIVER=mysql
DB_PORT=3306
DB_HOST=localhost
DB_NAME=cypht_db
DB_USER=root
DB_PASS=rootroot
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
"webklex/composer-info": "^0.0.1",
"composer" : "^2.0.0",
"zbateson/mail-mime-parser": "^2.4",
"league/commonmark": "^2.4"
"league/commonmark": "^2.4",
"symfony/dotenv": "^4.3 || 5.4"
},
"require-dev": {
"phpunit/phpunit": "^9.3.0"
Expand Down
73 changes: 72 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 27 additions & 24 deletions lib/db.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,20 @@ class Hm_DB {
* @return void
*/
static private function parse_config($site_config) {
self::$config = array('db_driver' => $site_config->get('db_driver', false),
'db_host' => $site_config->get('db_host', false),
'db_name' => $site_config->get('db_name', false),
'db_user' => $site_config->get('db_user', false),
'db_pass' => $site_config->get('db_pass', false),
'db_socket' => $site_config->get('db_socket', false),
'db_conn_type' => $site_config->get('db_connection_type', 'host'),
'db_port' => $site_config->get('db_port', false),
$environment = Hm_Environment::getInstance();
$environment->load();//load env files

self::$config = array(
'db_driver' => $environment->get('DB_DRIVER', $site_config->get('db_driver', false)),
'db_host' => $environment->get('DB_HOST', $site_config->get('db_host', false)),
'db_name' => $environment->get('DB_NAME', $site_config->get('db_name', false)),
'db_user' => $environment->get('DB_USER', $site_config->get('db_user', false)),
'db_pass' => $environment->get('DB_PASS', $site_config->get('db_pass', false)),
'db_socket' => $environment->get('DB_SOCKET', $site_config->get('db_socket', false)),
'db_conn_type' => $environment->get('DB_CONNECTION_TYPE', $site_config->get('db_connection_type', 'host')),
'db_port' => $environment->get('DB_PORT', $site_config->get('db_port', false)),
);

foreach (self::$required_config as $v) {
if (!self::$config[$v]) {
Hm_Debug::add(sprintf('Missing configuration setting for %s', $v));
Expand All @@ -47,14 +52,15 @@ static private function parse_config($site_config) {
* @return string md5 of the DB settings
*/
static private function db_key() {
return md5(self::$config['db_driver'].
self::$config['db_host'].
self::$config['db_port'].
self::$config['db_name'].
self::$config['db_user'].
self::$config['db_pass'].
self::$config['db_conn_type'].
self::$config['db_socket']
return md5(
self::$config['db_driver'] .
self::$config['db_host'] .
self::$config['db_port'] .
self::$config['db_name'] .
self::$config['db_user'] .
self::$config['db_pass'] .
self::$config['db_conn_type'] .
self::$config['db_socket']
);
}

Expand All @@ -68,12 +74,10 @@ static public function build_dsn() {
}
if (self::$config['db_conn_type'] == 'socket') {
return sprintf('%s:unix_socket=%s;dbname=%s', self::$config['db_driver'], self::$config['db_socket'], self::$config['db_name']);
}
else {
} else {
if (self::$config['db_port']) {
return sprintf('%s:host=%s;port=%s;dbname=%s', self::$config['db_driver'], self::$config['db_host'], self::$config['db_port'], self::$config['db_name']);
}
else {
} else {
return sprintf('%s:host=%s;dbname=%s', self::$config['db_driver'], self::$config['db_host'], self::$config['db_name']);
}
}
Expand All @@ -87,7 +91,7 @@ static public function build_dsn() {
* @param bool $all optional flag to return multiple rows
* @return boolean|integer|array
*/
static public function execute($dbh, $sql, $args, $type=false, $all=false) {
static public function execute($dbh, $sql, $args, $type = false, $all = false) {
if (!$dbh) {
return false;
}
Expand All @@ -112,7 +116,7 @@ static public function execute($dbh, $sql, $args, $type=false, $all=false) {
* @return string
*/
static private function execute_type($sql) {
switch(substr($sql, 0, 1)) {
switch (substr($sql, 0, 1)) {
case 'd':
case 'u':
case 'i':
Expand Down Expand Up @@ -141,8 +145,7 @@ static public function connect($site_config) {
self::$dbh[$key]->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Hm_Debug::add(sprintf('Connecting to dsn: %s', $dsn));
return self::$dbh[$key];
}
catch (Exception $oops) {
} catch (Exception $oops) {
Hm_Debug::add($oops->getMessage());
self::$dbh[$key] = false;
return false;
Expand Down
67 changes: 67 additions & 0 deletions lib/environment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

/**
* Environment objects
* @package framework
* @subpackage environment
*/

use Symfony\Component\Dotenv\Dotenv;

class Hm_Environment {

private static $instance;

public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new static();
}
return self::$instance;
}

public function load() {
$this->set_required_environment_variables();

$dotenvLoader = new Dotenv();
if (method_exists($dotenvLoader, 'usePutenv')) {
$dotenvLoader->usePutenv(true);
}
$envDistFile = APP_PATH. '.env.dist';
if (!file_exists($envDistFile)) {
Hm_Msgs::add('ERR.env.dist file not found at: "' . $envDistFile . '"');
return;
}

$envFile = static::get('TM_DOTENV');
$dotenvLoader->load($envDistFile);
if ($envFile) {
$dotenvLoader->loadEnv($envFile);
}
}

public static function get($key, $defaultValue = null)
{
$variables = self::getInstance()->get_environment_variables();

return array_key_exists($key, $variables) ? $variables[$key] : $defaultValue;
}

/**
* Sets required environment variables that are used within .env files
*/
private function set_required_environment_variables()
{
$_ENV['TM_DOTENV'] = APP_PATH . '.env';
}

/**
* Get a merge of environment variables $_ENV and $_SERVER.
*
* @return array
*/
protected function get_environment_variables()
{
return array_merge($_ENV, $_SERVER);
}
}
1 change: 1 addition & 0 deletions lib/framework.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
require APP_PATH.'lib/crypt.php';
require APP_PATH.'lib/crypt_sodium.php';
require APP_PATH.'lib/sodium_compat.php';
require APP_PATH.'lib/environment.php';
require APP_PATH.'lib/db.php';
require APP_PATH.'lib/servers.php';
require APP_PATH.'lib/api.php';
Expand Down
50 changes: 50 additions & 0 deletions tests/phpunit/environment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

use PHPUnit\Framework\TestCase;

/**
* tests for Hm_Environment
*/
class Hm_Test_Environment_Variable extends TestCase {

public function setUp(): void {
require 'bootstrap.php';

}
/**
* @preserveGlobalState disabled
* @runInSeparateProcess
*/
public function test_get() {
$environment = Hm_Environment::getInstance();
$environment->load();
$tm_dotenv = $environment->get('TM_DOTENV');
$this->assertStringEndsWith(".env", $tm_dotenv);
}

/**
* @preserveGlobalState disabled
* @runInSeparateProcess
*/
public function test_get_default_value() {
$environment = Hm_Environment::getInstance();
$environment->load();
$undifined_env_data = $environment::get('APP_VERSION', "DEFAUL_VALUE");
$this->assertEquals('DEFAUL_VALUE', $undifined_env_data);
}

/**
* @preserveGlobalState disabled
* @runInSeparateProcess
*/
public function test_get_environment_variables() {
$environment = Hm_Environment::getInstance();
$reflection = new ReflectionClass($environment);
$method = $reflection->getMethod('get_environment_variables');
$method->setAccessible(true);
$env_vars = $method->invoke($environment);
$expected = array_merge($_ENV, $_SERVER);
$this->assertEquals($expected, $env_vars);
}
}
?>
3 changes: 3 additions & 0 deletions tests/phpunit/phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
<testsuite name="config">
<file>./config.php</file>
</testsuite>
<testsuite name="environment">
<file>./environment.php</file>
</testsuite>
<testsuite name="db">
<file>./db.php</file>
</testsuite>
Expand Down

0 comments on commit faf567b

Please sign in to comment.