initial commit

This commit is contained in:
tracer 2022-01-18 19:14:24 +01:00
commit 13ee784385
20 changed files with 1025 additions and 0 deletions

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

14
.idea/bindAPI.iml Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/bindAPI/src" isTestSource="false" packagePrefix="App\" />
<sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/bindAPI/vendor/composer" />
<excludeFolder url="file://$MODULE_DIR$/bindAPI/vendor/phplucidframe/console-table" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

15
.idea/deployment.xml Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData" autoUpload="Always" serverName="executor.24unix.net" autoUploadExternalChanges="true">
<serverData>
<paths name="executor.24unix.net">
<serverdata>
<mappings>
<mapping deploy="/home/users/tfunix/www" local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
</serverData>
<option name="myAutoUpload" value="ALWAYS" />
</component>
</project>

View File

@ -0,0 +1,102 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<Languages>
<language minSize="85" name="PHP" />
</Languages>
</inspection_tool>
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="JSClassNamingConvention" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_minLength" value="3" />
</inspection_tool>
<inspection_tool class="JSXNamespaceValidation" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="MsBuiltinInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="MsOrderByInspection" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="MysqlLoadDataPathInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="MysqlParsingInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="PhpCSValidationInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false">
<option name="CODING_STANDARD" value="Custom" />
<option name="CUSTOM_RULESET_PATH" value="$PROJECT_DIR$/phpcs.xml.dist" />
<option name="USE_INSTALLED_PATHS" value="true" />
<option name="INSTALLED_PATHS" value="$PROJECT_DIR$/vendor/doctrine/coding-standard/lib/Doctrine" />
<option name="EXTENSIONS" value="php,js,css,inc" />
</inspection_tool>
<inspection_tool class="PhpClassNamingConventionInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_minLength" value="3" />
<option name="m_maxLength" value="24" />
</inspection_tool>
<inspection_tool class="PhpConstantNamingConventionInspection" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PhpFunctionNamingConventionInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_regex" value="[a-z][A-Za-z\d]*" />
<option name="m_minLength" value="2" />
<option name="m_maxLength" value="50" />
</inspection_tool>
<inspection_tool class="PhpMethodNamingConventionInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_minLength" value="2" />
<option name="m_maxLength" value="24" />
</inspection_tool>
<inspection_tool class="PhpMissingDocCommentInspection" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PhpNonCanonicalElementsOrderInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
<inspection_tool class="PhpPropertyNamingConventionInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_regex" value="[a-z][A-Z_a-z\d]*" />
<option name="m_minLength" value="2" />
<option name="m_maxLength" value="24" />
</inspection_tool>
<inspection_tool class="PhpPureAttributeCanBeAddedInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="PhpVariableNamingConventionInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_regex" value="[a-z][A-Za-z\d]*" />
<option name="m_minLength" value="1" />
<option name="m_maxLength" value="24" />
</inspection_tool>
<inspection_tool class="SqlAddNotNullColumnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlAggregatesInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlAmbiguousColumnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlAutoIncrementDuplicateInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlCallNotationInspection" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="SqlCaseVsCoalesceInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlCaseVsIfInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlCheckUsingColumnsInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlConstantConditionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlConstantExpressionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlCurrentSchemaInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlDeprecateTypeInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlDerivedTableAliasInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlDialectInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlDropIndexedColumnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlDtInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlDuplicateColumnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlIdentifierInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlIllegalCursorStateInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlInsertIntoGeneratedColumnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlInsertNullIntoNotNullInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlInsertValuesInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlJoinWithoutOnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlMisleadingReferenceInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlMissingReturnInspection" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="SqlMultipleLimitClausesInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlNoDataSourceInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlNullComparisonInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlRedundantAliasInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlRedundantCodeInCoalesceInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlRedundantElseNullInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlRedundantLimitInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlRedundantOrderingDirectionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlResolveInspection" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="SqlShadowingAliasInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlShouldBeInGroupByInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlSideEffectsInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlSignatureInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlStorageInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlStringLengthExceededInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlTransactionStatementInTriggerInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlTriggerTransitionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlTypeInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlUnicodeStringLiteralInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlUnreachableCodeInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlUnusedCteInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlUnusedSubqueryItemInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlUnusedVariableInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlWithoutWhereInspection" enabled="false" level="WARNING" enabled_by_default="false" />
</profile>
</component>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/bindAPI.iml" filepath="$PROJECT_DIR$/.idea/bindAPI.iml" />
</modules>
</component>
</project>

12
.idea/php.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PhpIncludePathManager">
<include_path>
<path value="$PROJECT_DIR$/bindAPI/vendor/composer" />
<path value="$PROJECT_DIR$/bindAPI/vendor/phplucidframe/console-table" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.1">
<option name="suggestChangeDefaultLanguageLevel" value="false" />
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

0
README.md Normal file
View File

3
bindAPI/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.idea
/vendor/

111
bindAPI/bin/console Executable file
View File

@ -0,0 +1,111 @@
#!/usr/bin/keyhelp-php81
<?php
use App\Controller\ApiUsers;
use App\Controller\DatabaseConnection;
use App\Controller\DomainController;
use CLIFramework\Component\Table\Table;
//echo $argc;
//print_r($argv);
// 61e6ce5dd8a1b.bc1c314ce364f6878084c254fe4c6345801c43a49bb8eb71
if ($argc < 2) {
echo 'Usage' . PHP_EOL;
echo "\033[33mapikeys" . PHP_EOL;
echo "\033[32m\tapikeys:list" . PHP_EOL;
echo "\033[32m\tapikeys:create" . PHP_EOL;
echo "\033[32m\tapikeys:delete {ID}" . PHP_EOL;
echo "\033[33mdomains" . PHP_EOL;
echo "\033[32m\tdomains:list" . PHP_EOL;
echo "\033[32m\tdomains:create <name> {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL;
echo "\033[32m\tdomains:update <ID> {name} {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL;
echo "\033[32m\tdomains:delete" . PHP_EOL;
echo "\033[32m\tdomains:check" . PHP_EOL;
echo PHP_EOL . "\033[39me.g. ./bin/console apikey:list" . PHP_EOL;
exit(0);
}
//print(__DIR__ . PHP_EOL);
//print(dirname(__DIR__) . PHP_EOL);
//exit;
require dirname(__DIR__) . '/vendor/autoload.php';
$dbConnection = (new DatabaseConnection())->getConnection();
$apiUsers = new ApiUsers($dbConnection);
$domainController = new DomainController($dbConnection);
[$command, $subcommand] = explode(':', $argv[1]);
//echo $command, $subcommand;
switch($command) {
case 'apikeys':
switch($subcommand) {
case "create";
$result = $apiUsers->create();
echo 'API key ' . $result['row'] . ' has been generated. Store it in a save place, it cannot be recovered.' . PHP_EOL;
echo "\033[32m\t" . $result['tokenPrefix'] . '.' . $result['key'] . PHP_EOL;
exit(0);
case "list":
echo 'All available API keys:' . PHP_EOL;
echo " No\tAPI key prefix" . PHP_EOL;
$keys = $apiUsers->findAll();
if ($keys) {
foreach ($keys as $key) {
echo $key['id'] . "\t". $key['api_token_prefix'] . PHP_EOL;
}
} else {
echo 'No keys found.' . PHP_EOL;
}
exit(0);
case "delete":
$id = $argv[2] ?? 0;
if ($id == 0) {
echo 'You need to add the ID of the token.' .PHP_EOL;
exit(1);
}
if ($apiUsers->findByID($id)) {
$apiUsers->delete($id);
echo 'Token ' . $id . ' has been deleted.' . PHP_EOL;
exit(0);
} else {
echo 'Unknown ID: ' . $id . PHP_EOL;
exit(1);
}
default:
echo 'Unknown command: ' . $subcommand . PHP_EOL;
}
break;
case 'domains':
switch($subcommand) {
case 'list':
echo 'All available domains:' . PHP_EOL;
$domains = $domainController->findAll();
if ($domains) {
$table = new \LucidFrame\Console\ConsoleTable();
$table->setHeaders(['ID', 'Name', 'A', 'AAAA']);
foreach ($domains as $domain) {
$table->addRow([$domain['id'], $domain['name'], $domain['a'], $domain['aaaa']]);
}
$table->setPadding(2);
$table->display();
} else {
echo 'No domains found.' . PHP_EOL;
}
exit(0);
break;
default:
echo("Unknown Command: $subcommand" . PHP_EOL);
exit(1);
}
break;
default:
echo 'Unknown command: ' . $command . PHP_EOL;
}

29
bindAPI/composer.json Normal file
View File

@ -0,0 +1,29 @@
{
"type": "project",
"license": "proprietary",
"minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": ">=8.1",
"ext-json": "*",
"ext-pdo": "*",
"phplucidframe/console-table": "^1.2"
},
"config": {
"optimize-autoloader": true,
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Src\\": "src/"
}
}
}

67
bindAPI/composer.lock generated Normal file
View File

@ -0,0 +1,67 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "0f698e244946cb8cd564781a86b98a1c",
"packages": [
{
"name": "phplucidframe/console-table",
"version": "v1.2.4",
"source": {
"type": "git",
"url": "https://github.com/phplucidframe/console-table.git",
"reference": "a973d911af96f3db42fca92cbeb1f473c9ad505e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phplucidframe/console-table/zipball/a973d911af96f3db42fca92cbeb1f473c9ad505e",
"reference": "a973d911af96f3db42fca92cbeb1f473c9ad505e",
"shasum": ""
},
"require": {
"php": ">=5.3"
},
"require-dev": {
"phpunit/phpunit": "*"
},
"type": "library",
"autoload": {
"psr-0": {
"LucidFrame\\": "src/",
"LucidFrameTest\\": "tests/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Sithu K.",
"email": "cithukyaw@gmail.com"
}
],
"description": "Console Table",
"support": {
"issues": "https://github.com/phplucidframe/console-table/issues",
"source": "https://github.com/phplucidframe/console-table/tree/v1.2.4"
},
"time": "2019-03-03T12:17:32+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": true,
"prefer-lowest": false,
"platform": {
"php": ">=8.1",
"ext-json": "*",
"ext-pdo": "*"
},
"platform-dev": [],
"plugin-api-version": "2.2.0"
}

11
bindAPI/public/.htaccess Normal file
View File

@ -0,0 +1,11 @@
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI}::$0 ^(/.+)/(.*)::\2$
RewriteRule .* - [E=BASE:%1]
RewriteCond %{HTTP:Authorization} .+
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]
RewriteCond %{ENV:REDIRECT_STATUS} =""
RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>

39
bindAPI/public/index.php Normal file
View File

@ -0,0 +1,39 @@
<?php
require '../vendor/autoload.php';
use App\Controller\DatabaseConnection;
use App\Controller\RequestController;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$dbConnection = (new DatabaseConnection())->getConnection();
// TODO make a log class
$oFile = fopen ('log.txt', 'a');
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
fputs($oFile, $uri);
$uri = explode( '/', $uri );
if ($uri[1] !== 'api') {
header("HTTP/1.1 404 Not Found");
exit();
}
// TODO check for valid API key
$requestMethod = $_SERVER["REQUEST_METHOD"];
// pass the request method and user ID to the PersonController and process the HTTP request:
$controller = new RequestController($dbConnection, $requestMethod, $uri);
$controller->processRequest();
fclose($oFile);

0
bindAPI/src/Controller/.gitignore vendored Normal file
View File

View File

@ -0,0 +1,135 @@
<?php
namespace App\Controller;
use PDO;
use PDOException;
/**
*
*/
class ApiUsers
{
private PDO $dbConnection;
public function __construct(PDO $dbConnection)
{
$this->dbConnection = $dbConnection;
}
/**
* @return array|false
*/
public function findAll(): bool|array
{
$statement = "
SELECT id, api_token_prefix, api_token
FROM user";
try {
$statement = $this->dbConnection->query($statement);
return $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
exit($e->getMessage());
}
}
/**
* @param Int $id
*
* @return array|false
*/
public function findByID(Int $id): bool|array
{
$statement = "
SELECT api_token_prefix, api_token
FROM user
WHERE id = :id;
";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam(':id', $id);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
exit($e->getMessage());
}
}
public function findByPrefix(String $prefix): bool|array
{
$statement = "
SELECT api_token
FROM user
WHERE api_token_prefix = :prefix;
";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam(':prefix', $prefix);
$statement->execute();
return $statement->fetch(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
exit($e->getMessage());
}
}
/**
* @return array|void
*/
public function create()
{
$tokenPrefix = uniqid();
$result['tokenPrefix'] = $tokenPrefix;
try {
$key = bin2hex(random_bytes(24));
$result['key'] = $key;
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
exit(1);
}
$token = password_hash($tokenPrefix . '.' . $key, PASSWORD_ARGON2ID);
//print()
$statement = "
INSERT INTO user (api_token_prefix, api_token)
VALUES (:token_prefix, :token)";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam(':token_prefix', $tokenPrefix);
$statement->bindParam(':token', $token);
$statement->execute();
$result['row'] = $this->dbConnection->lastInsertId();
return $result;
} catch (\PDOException $e) {
exit($e->getMessage());
}
}
/**
* @param $id
*
* @return void
*/
public function delete($id)
{
$statement = "
DELETE FROM user
WHERE id = :id";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam('id', $id);
$statement->execute();
return $statement->rowCount();
} catch (\PDOException $e) {
exit($e->getMessage());
}
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace App\Controller;
use PDO;
use PDOException;
/**
*
*/
class DatabaseConnection
{
private PDO $dbConnection;
public function __construct()
{
// get from config later
$dbHost = "localhost";
$dbPort = 3306;
$dbDatabase = "tfunix_db1";
$dbUser = "tfunix_db1";
$dbPassword = "aWeirder1";
try {
$this->dbConnection = new PDO(
dsn: "mysql:host=$dbHost;port=$dbPort;charset=utf8mb4;dbname=$dbDatabase",
username: $dbUser,
password: $dbPassword
);
} catch (PDOException $exception) {
exit($exception->getMessage());
}
}
/**
* @return \PDO
*/
public function getConnection(): PDO
{
return $this->dbConnection;
}
}

View File

@ -0,0 +1,172 @@
<?php
namespace App\Controller;
use PDO;
use PDOException;
/**
*
*/
class DomainController
{
private PDO $dbConnection;
public function __construct(PDO $dbConnection)
{
$this->dbConnection = $dbConnection;
}
/**
* @return array|false
*/
public function findAll(): bool|array
{
$statement = "
SELECT id, name, a, aaaa
FROM domains";
try {
$statement = $this->dbConnection->query($statement);
return $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
exit($e->getMessage());
}
}
/**
* @param String $name
*
* @return array|false
*/
public function findByName(String $name): bool|array
{
$statement = "
SELECT id, name, a, aaaa
FROM domains
WHERE name = :name";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam(':name', $name);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
exit($e->getMessage());
}
}
/**
* @param Int $id
*
* @return array|false
*/
public function findByID(Int $id): bool|array
{
$statement = "
SELECT id, name, a, aaaa
FROM domains
WHERE id = :id";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam(':id', $id);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
exit($e->getMessage());
}
}
/**
* @param String $name
* @param String $a
* @param String $aaaa
*
* @return int
*/
public function insert(String $name, String $a, String $aaaa): int
{
// TODO create zone file and include
$statement = "
INSERT INTO domains (name, a, aaaa)
VALUES (:name, :a, :aaaa)";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam(':name', $name);
$statement->bindParam(':a', $a);
$statement->bindParam(':aaaa', $aaaa);
$statement->execute();
return $statement->rowCount();
} catch (\PDOException $e) {
exit($e->getMessage());
}
// TODO
// create zone file
// add zone file to include file
}
/**
* @param Int $id
* @param String $name
* @param String $a
* @param String $aaaa
*
* @return int|void
*/
public function update(Int $id, String $name, String $a, String $aaaa)
{
// TODO UPDATE Zone file
$statement = "
UPDATE domains SET
name = :name,
a = :a,
aaaa = :aaaa
WHERE id = :id";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam('id', $id);
$statement->bindParam('name', $name);
$statement->bindParam('a', $a);
$statement->bindParam('aaaa', $aaaa);
$statement->execute();
return $statement->rowCount();
} catch (\PDOException $e) {
exit($e->getMessage());
}
// TODO
// recreate zone file
}
/**
* @param $id
*
* @return int
*/
public function delete($id): int
{
// TODO delete zone file and include
$statement = "
DELETE FROM domains
WHERE id = :id";
try {
$statement = $this->dbConnection->prepare($statement);
$statement->bindParam('id', $id);
$statement->execute();
return $statement->rowCount();
} catch (\PDOException $e) {
exit($e->getMessage());
}
}
}

View File

@ -0,0 +1,244 @@
<?php
namespace App\Controller;
use PDO;
/**
*
*/
class RequestController
{
private PDO $dbConnection;
private DomainController $domainController;
private String $requestMethod;
private array $uri;
private String $status;
private String $message;
public function __construct(PDO $dbConnection, String $requestMethod, array $uri)
{
$this->dbConnection = $dbConnection;
$this->requestMethod = strtoupper($requestMethod);
$this->uri = $uri;
$this->domainController = new DomainController($dbConnection);
}
public function processRequest()
{
$result = Array();
if (empty($this->uri[2]) || $this->uri[2] != 'domains') {
$this->status = "404 Not Found";
$this->message = "Endpoint not found.";
} else {
if ($this->checkPassword()) {
switch ($this->requestMethod) {
case 'GET':
if (empty($this->uri[3])) {
$result = $this->domainController->findAll();
} else {
if (strtolower($this->uri[3]) == "check") {
$result = $this->checkDomains();
} else {
$result = $this->domainController->findByName($this->uri[3]);
}
}
break;
case 'POST':
$name = $_POST['name'] ?? "";
$a = $_POST['a'] ?? "";
$aaaa = $_POST['aaaa'] ?? "";
if (empty($name)) {
$this->status = "400 Bad Request";
$this->message = "A name is required";
break;
}
if (empty($a) && empty($aaaa)) {
$this->status = "400 Bad Request";
$this->message = "At least one IP address is required.";
break;
}
if($this->domainController->findByName($name)) {
$this->status = "400 Bad request";
$this->message = "Domain: $name already exists.";
} else {
$dcResult = $this->domainController->insert($name, $a, $aaaa);
$this->status = "201 Created";
$this->message = $dcResult;
}
break;
case 'PUT':
$putData = fopen('php://input', 'r');
$data = fread($putData, 512);
$params = explode( '&', $data);
foreach ($params as $param) {
[$key, $value] = explode('=', $param);
$put[$key] = $value;
}
$id = $put['id'] ?? 0;
$name = $put['name'] ?? "";
$a = $put['a'] ?? "";
$aaaa = $put['aaaa'] ?? "";
if ($id == 0) {
$this->status = "400 Bad Request";
$this->message = "An ID is required";
break;
}
if(!$this->domainController->findByID($id)) {
$this->status = "400 Bad request";
$this->message = "Domain with ID : $id doesn't exist.";
break;
}
if (empty($name)) {
$this->status = "400 Bad Request";
$this->message = "A name is required";
break;
}
if (empty($a) && empty($aaaa)) {
$this->status = "400 Bad Request";
$this->message = "At least one IP address is required.";
break;
}
$dcResult = $this->domainController->update($id, $name, $a, $aaaa);
$this->status = "201 Updated";
$this->message = $dcResult;
break;
case "DELETE":
$deleteData = fopen('php://input', 'r');
$data = fread($deleteData, 512);
$params = explode( '&', $data);
foreach ($params as $param) {
[$key, $value] = explode('=', $param);
$delete[$key] = $value;
}
$id = $delete['id'] ?? 0;
if ($id == 0) {
$this->status = "400 Bad Request";
$this->message = "A valid ID is required.";
break;
}
if(!$this->domainController->findByID($id)) {
$this->status = "400 Bad Request";
$this->message = "There is no domain with ID $id.";
break;
}
$this->domainController->delete($id);
$this->status = "204 No content.";
$this->message = "The domain $id has been deleted.";
break;
default:
$this->status = "400 Bad Request";
$this->message = "unknown request method: $this->requestMethod";
}
}
}
if (!empty($result)) {
echo json_encode($result);
} else {
echo json_encode([
'status' => $this->status ?? "Error: No status",
'message' => $this->message ?? "Error: No message."
]);
}
}
/**
* @return array
*/
function checkDomains(): array
{
$errors = Array();
$domains = $this->domainController->findAll();
// check for included main file in /etc/bind/named.conf.local
// it needs to include "/etc/bind/local.zones";
$localZoneFile = '/etc/bind/local.zones';
$localZonesDir = '/etc/bind/zones/';
$namedConfLocalFile = '/etc/bind/named.conf.local';
if ($namedConfLocal = file_get_contents($namedConfLocalFile)) {
if (!str_contains($namedConfLocal, $localZoneFile)) {
$errors[] = "$localZoneFile needs to be included in $namedConfLocalFile.";
}
} else {
$errors[] = "No access to '$namedConfLocalFile'. Please check permissions";
return $errors;
}
if (!fileperms($localZoneFile)) {
$errors[] = "No access to $localZoneFile. Please check permissions.";
return $errors;
}
$localZones = file_get_contents($localZoneFile);
foreach($domains as $domain) {
if(!str_contains($localZones, $domain['name'])) {
$errors[] = $domain['name'] . " is missing in '$localZoneFile'";
}
$zoneFile = $localZonesDir . $domain['name'];
if (!file_exists($zoneFile)) {
$errors[] = "Missing zone file for $zoneFile. Update zone to create it";
}
}
if (empty($errors)) {
return [
'status' => "200 domains healthy.",
'message' => "All domains ar setup."
];
} else {
return $errors;
}
}
/**
* @return bool
*/
public function checkPassword(): bool
{
$headers = array_change_key_case(getallheaders(), CASE_UPPER);
$apiKey = $headers['X-API-KEY'] ?? "";
if (empty($apiKey)) {
$this->status = "401 Unauthorized";
$this->message = "API key is missing.";
return false;
} else {
[$prefix,] = explode('.', $apiKey);
$apiUsers = new ApiUsers($this->dbConnection);
$apiResult = $apiUsers->findByPrefix($prefix);
$storedHash = $apiResult['api_token'];
if (!password_verify($apiKey, $storedHash)) {
$this->status = "401 Unauthorized";
$this->message = "API key mismatch.";
return false;
}
}
return true;
}
}