try to fix cors issues

This commit is contained in:
tracer 2024-04-25 20:58:01 +02:00
parent a312ad9095
commit e9b14a11d7
10 changed files with 220 additions and 214 deletions

View File

@ -2,7 +2,7 @@
"name": "24unix/bindapi", "name": "24unix/bindapi",
"description": "manage Bind9 DNS server via REST API", "description": "manage Bind9 DNS server via REST API",
"version": "1.0.9", "version": "1.0.9",
"build_number": "355", "build_number": "356",
"authors": [ "authors": [
{ {
"name": "Micha Espey", "name": "Micha Espey",
@ -30,7 +30,7 @@
"robmorgan/phinx": "^0.15", "robmorgan/phinx": "^0.15",
"symfony/property-access": "^6.1", "symfony/property-access": "^6.1",
"symfony/serializer": "^6.1", "symfony/serializer": "^6.1",
"zircote/swagger-php": "^4.2" "zircote/swagger-php": "^4.8"
}, },
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,

24
composer.lock generated
View File

@ -4,20 +4,20 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "39a97c9f763fcd937f90143307fa8185", "content-hash": "5dbbe0ea570912e4a3664e4798edaccd",
"packages": [ "packages": [
{ {
"name": "arubacao/tld-checker", "name": "arubacao/tld-checker",
"version": "1.2.228", "version": "1.2.229",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/arubacao/tld-checker.git", "url": "https://github.com/arubacao/tld-checker.git",
"reference": "2b203b2ceac5bad62fed07f1613c9cf118fe6f96" "reference": "194a704aef0b5e07b5695c5a2769f664e7cf9185"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/arubacao/tld-checker/zipball/2b203b2ceac5bad62fed07f1613c9cf118fe6f96", "url": "https://api.github.com/repos/arubacao/tld-checker/zipball/194a704aef0b5e07b5695c5a2769f664e7cf9185",
"reference": "2b203b2ceac5bad62fed07f1613c9cf118fe6f96", "reference": "194a704aef0b5e07b5695c5a2769f664e7cf9185",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -65,9 +65,9 @@
], ],
"support": { "support": {
"issues": "https://github.com/arubacao/tld-checker/issues", "issues": "https://github.com/arubacao/tld-checker/issues",
"source": "https://github.com/arubacao/tld-checker/tree/1.2.228" "source": "https://github.com/arubacao/tld-checker/tree/1.2.229"
}, },
"time": "2024-04-14T04:01:22+00:00" "time": "2024-04-21T04:01:27+00:00"
}, },
{ {
"name": "cakephp/chronos", "name": "cakephp/chronos",
@ -4116,16 +4116,16 @@
}, },
{ {
"name": "squizlabs/php_codesniffer", "name": "squizlabs/php_codesniffer",
"version": "3.9.1", "version": "3.9.2",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git", "url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git",
"reference": "267a4405fff1d9c847134db3a3c92f1ab7f77909" "reference": "aac1f6f347a5c5ac6bc98ad395007df00990f480"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/267a4405fff1d9c847134db3a3c92f1ab7f77909", "url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/aac1f6f347a5c5ac6bc98ad395007df00990f480",
"reference": "267a4405fff1d9c847134db3a3c92f1ab7f77909", "reference": "aac1f6f347a5c5ac6bc98ad395007df00990f480",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -4192,7 +4192,7 @@
"type": "open_collective" "type": "open_collective"
} }
], ],
"time": "2024-03-31T21:03:09+00:00" "time": "2024-04-23T20:25:34+00:00"
}, },
{ {
"name": "theseer/tokenizer", "name": "theseer/tokenizer",

View File

@ -2,4 +2,5 @@
Description=BindAPI Service to check zone file and reload configuration Description=BindAPI Service to check zone file and reload configuration
[Service] [Service]
User=<paneluser>
ExecStart=/home/users/<user>/<bindApi>/bin/console -q cron:run ExecStart=/home/users/<user>/<bindApi>/bin/console -q cron:run

View File

@ -6,10 +6,15 @@ error_reporting(error_level: E_ALL);
require dirname(path: __DIR__) . '/vendor/autoload.php'; require dirname(path: __DIR__) . '/vendor/autoload.php';
$uri = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH); $parsedUrl = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH);
$uri = explode(separator: '/', string: $uri); $uri = explode(separator: '/', string: $parsedUrl);
if ($uri[1] !== 'api') { $baseRoutes = ['app', 'api'];
$uriPrefix = $uriFirstThreeLetters = substr(string: $uri[1], offset: 0, length: 3);
if (!in_array(needle: $uriPrefix, haystack: $baseRoutes)) {
// only handle $baseRoutes, elso go to swagger ui
$scheme = $_SERVER['REQUEST_SCHEME']; $scheme = $_SERVER['REQUEST_SCHEME'];
$host = $_SERVER['SERVER_NAME']; $host = $_SERVER['SERVER_NAME'];
$header = "$scheme://$host/openapi/index.html"; $header = "$scheme://$host/openapi/index.html";
@ -25,6 +30,12 @@ header(header: "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow
$requestMethod = $_SERVER["REQUEST_METHOD"]; $requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod === "OPTIONS") {
// Respond with OK status code for preflight requests
http_response_code(response_code: 200);
exit();
}
try { try {
$app = new BindAPI(quiet: false); $app = new BindAPI(quiet: false);
$app->handleRequest(requestMethod: $requestMethod, uri: $uri); $app->handleRequest(requestMethod: $requestMethod, uri: $uri);

View File

@ -19,8 +19,9 @@
<script> <script>
window.onload = function () { window.onload = function () {
// Begin Swagger UI call region // Begin Swagger UI call region
const ui = SwaggerUIBundle({ let ui;
url: "/openapi/bindapi.json", ui = SwaggerUIBundle({
url: "/app/apidoc",
dom_id: "#swagger-ui", dom_id: "#swagger-ui",
deepLinking: true, deepLinking: true,
presets: [ presets: [

View File

@ -1,5 +1,4 @@
<?php <?php declare(strict_types=1);
declare(strict_types=1);
namespace App\Controller; namespace App\Controller;
@ -27,6 +26,7 @@ use App\Repository\DynDNSRepository;
use App\Repository\NameserverRepository; use App\Repository\NameserverRepository;
use App\Repository\PanelRepository; use App\Repository\PanelRepository;
use App\Repository\SettingsRepository; use App\Repository\SettingsRepository;
use App\Service\ApiClient;
use Arubacao\TldChecker\Validator; use Arubacao\TldChecker\Validator;
use Exception; use Exception;
use JsonMapper; use JsonMapper;
@ -36,9 +36,7 @@ use Odan\Migration\Command\GenerateCommand;
use Phinx\Console\PhinxApplication; use Phinx\Console\PhinxApplication;
use SodiumException; use SodiumException;
use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
if (php_sapi_name() !== 'cli') { if (php_sapi_name() !== 'cli') {
exit; exit;
@ -54,7 +52,7 @@ class CLIController
* @throws Exception * @throws Exception
*/ */
public function __construct( public function __construct(
private readonly ApiController $apiController, private readonly ApiClient $apiClient,
private readonly ApikeyRepository $apikeyRepository, private readonly ApikeyRepository $apikeyRepository,
private readonly DomainController $domainController, private readonly DomainController $domainController,
private readonly DomainRepository $domainRepository, private readonly DomainRepository $domainRepository,
@ -65,7 +63,7 @@ class CLIController
private readonly EncryptionController $encryptionController, private readonly EncryptionController $encryptionController,
private readonly SettingsRepository $settingsRepository, private readonly SettingsRepository $settingsRepository,
private $logger, private $logger,
private bool $quiet private readonly bool $quiet
) )
{ {
$this->commandGroupContainer = (new CommandGroupContainer()) $this->commandGroupContainer = (new CommandGroupContainer())
@ -74,13 +72,16 @@ class CLIController
name: 'list', name: 'list',
callback: function () { callback: function () {
$this->apikeysList(); $this->apikeysList();
})) }
)
)
->addCommand(command: new Command( ->addCommand(command: new Command(
name: 'create', name: 'create',
callback: function () { callback: function () {
$this->apikeysCreate(); $this->apikeysCreate();
}, },
mandatoryParameters: ['name'])) mandatoryParameters: ['name'])
)
->addCommand(command: new Command( ->addCommand(command: new Command(
name: 'update', name: 'update',
callback: function () { callback: function () {
@ -524,7 +525,7 @@ class CLIController
} }
if (!empty($panel->getA())) { if (!empty($panel->getA())) {
$panelRequest = $this->apiController->sendCommand( $panelRequest = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -532,7 +533,7 @@ class CLIController
command: '/server', command: '/server',
serverType: 'panel'); serverType: 'panel');
} else { } else {
$panelRequest = $this->apiController->sendCommand( $panelRequest = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -553,7 +554,7 @@ class CLIController
} }
if (empty($panel->getA())) { if (empty($panel->getA())) {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -562,7 +563,7 @@ class CLIController
serverType: 'panel' serverType: 'panel'
); );
} else { } else {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -726,7 +727,7 @@ class CLIController
echo COLOR_YELLOW . ' ' . $nameserver->getName(); echo COLOR_YELLOW . ' ' . $nameserver->getName();
} }
if (!empty($nameserver->getA())) { if (!empty($nameserver->getA())) {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $nameserver->getName(), serverName: $nameserver->getName(),
versionIP: 4, versionIP: 4,
@ -734,7 +735,7 @@ class CLIController
command: 'domains/name/' . $domainName, command: 'domains/name/' . $domainName,
serverType: 'nameserver'); serverType: 'nameserver');
} else { } else {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $nameserver->getName(), serverName: $nameserver->getName(),
versionIP: 6, versionIP: 6,
@ -754,7 +755,6 @@ class CLIController
echo COLOR_RED . ' Error: ' . COLOR_YELLOW . $result['data'] . COLOR_DEFAULT . PHP_EOL; echo COLOR_RED . ' Error: ' . COLOR_YELLOW . $result['data'] . COLOR_DEFAULT . PHP_EOL;
} }
exit(1); exit(1);
break;
case 404: case 404:
if (!$this->quiet) { if (!$this->quiet) {
echo COLOR_RED . ' ' . $result['header'] . COLOR_DEFAULT; echo COLOR_RED . ' ' . $result['header'] . COLOR_DEFAULT;
@ -771,7 +771,7 @@ class CLIController
$decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $nameserver->getApikey(), key: $encryptionKey); $decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $nameserver->getApikey(), key: $encryptionKey);
if (!empty($nameserver->getAaaa())) { if (!empty($nameserver->getAaaa())) {
$create = $this->apiController->sendCommand( $create = $this->apiClient->sendCommand(
requestType: 'POST', requestType: 'POST',
serverName: $nameserver->getName(), serverName: $nameserver->getName(),
versionIP: 6, versionIP: 6,
@ -780,7 +780,7 @@ class CLIController
serverType: 'nameserver', serverType: 'nameserver',
body: $body); body: $body);
} else { } else {
$create = $this->apiController->sendCommand( $create = $this->apiClient->sendCommand(
requestType: 'POST', requestType: 'POST',
serverName: $nameserver->getName(), serverName: $nameserver->getName(),
versionIP: 4, versionIP: 4,
@ -1094,7 +1094,7 @@ class CLIController
if (!$this->configController->getConfig(configKey: 'quiet')) { if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_DEFAULT . ' ' . str_pad(string: $a, length: $maxA, pad_type: STR_PAD_LEFT) . ' '; echo COLOR_DEFAULT . ' ' . str_pad(string: $a, length: $maxA, pad_type: STR_PAD_LEFT) . ' ';
} }
if ($result = $this->apiController->sendCommand( if ($result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $server->getName(), serverName: $server->getName(),
versionIP: 4, versionIP: 4,
@ -1121,7 +1121,7 @@ class CLIController
if (!$this->configController->getConfig(configKey: 'quiet')) { if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_DEFAULT . ' ' . str_pad(string: $aaaa, length: $maxAAAA, pad_type: STR_PAD_LEFT) . ' '; echo COLOR_DEFAULT . ' ' . str_pad(string: $aaaa, length: $maxAAAA, pad_type: STR_PAD_LEFT) . ' ';
} }
if ($result = $this->apiController->sendCommand( if ($result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $server->getName(), serverName: $server->getName(),
versionIP: 6, versionIP: 6,
@ -1708,7 +1708,7 @@ class CLIController
echo 'fixme'; echo 'fixme';
} }
/** /**
*/ */
private function dynDnsPush(): void private function dynDnsPush(): void
{ {
@ -1736,7 +1736,7 @@ class CLIController
$decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $panel->getApikey(), key: $encryptionKey); $decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $panel->getApikey(), key: $encryptionKey);
if (!empty($panel->getAaaa())) { if (!empty($panel->getAaaa())) {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'POST', requestType: 'POST',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -1744,7 +1744,7 @@ class CLIController
command: 'dyndns/' . $hostName, command: 'dyndns/' . $hostName,
serverType: 'nameserver'); serverType: 'nameserver');
} else { } else {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'POST', requestType: 'POST',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -1806,7 +1806,7 @@ class CLIController
$currentDomains = $this->domainRepository->findByPanel(name: $panel->getName()); $currentDomains = $this->domainRepository->findByPanel(name: $panel->getName());
if (empty($panel->getA())) { if (empty($panel->getA())) {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -1815,7 +1815,7 @@ class CLIController
serverType: 'panel' serverType: 'panel'
); );
} else { } else {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -1840,7 +1840,7 @@ class CLIController
foreach ($domains as $domain) { foreach ($domains as $domain) {
$domainCount++; $domainCount++;
if (!$this->quiet) { if (!$this->quiet) {
echo COLOR_YELLOW . ' ' .str_pad(string: $domain->domain, length: $longestEntry + 1, pad_type: STR_PAD_RIGHT); echo COLOR_YELLOW . ' ' . str_pad(string: $domain->domain, length: $longestEntry + 1, pad_type: STR_PAD_RIGHT);
} }
if ($currentDomain = $this->domainRepository->findByName(name: $domain->domain)) { if ($currentDomain = $this->domainRepository->findByName(name: $domain->domain)) {
$currentPanel = $currentDomain->getPanel(); $currentPanel = $currentDomain->getPanel();
@ -1928,7 +1928,7 @@ class CLIController
if (!$quiet) { if (!$quiet) {
echo 'Check using IPv6: ' . COLOR_YELLOW . $panel->getAaaa() . '.' . COLOR_DEFAULT . PHP_EOL; echo 'Check using IPv6: ' . COLOR_YELLOW . $panel->getAaaa() . '.' . COLOR_DEFAULT . PHP_EOL;
} }
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -1939,7 +1939,7 @@ class CLIController
if (!$quiet) { if (!$quiet) {
echo 'Check using IPv4: ' . COLOR_YELLOW . $panel->getA() . COLOR_DEFAULT . PHP_EOL; echo 'Check using IPv4: ' . COLOR_YELLOW . $panel->getA() . COLOR_DEFAULT . PHP_EOL;
} }
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -1963,7 +1963,7 @@ class CLIController
if (!$quiet) { if (!$quiet) {
echo "Found IPv4 entry: " . COLOR_YELLOW . $v4['ip'] . COLOR_DEFAULT . '.' . PHP_EOL; echo "Found IPv4 entry: " . COLOR_YELLOW . $v4['ip'] . COLOR_DEFAULT . '.' . PHP_EOL;
} }
$v4Test = $this->apiController->fileGetContents(url: $webmailDomain, versionIP: 4); $v4Test = $this->apiClient->fileGetContents(url: $webmailDomain, versionIP: 4);
if ($v4Test['error']) { if ($v4Test['error']) {
if (!$quiet) { if (!$quiet) {
@ -1986,7 +1986,7 @@ class CLIController
if (!$quiet) { if (!$quiet) {
echo "Found IPv6 entry: " . COLOR_YELLOW . $v6['ipv6'] . COLOR_DEFAULT . '.' . PHP_EOL; echo "Found IPv6 entry: " . COLOR_YELLOW . $v6['ipv6'] . COLOR_DEFAULT . '.' . PHP_EOL;
} }
$v6Test = $this->apiController->fileGetContents(url: $webmailDomain, versionIP: 6); $v6Test = $this->apiClient->fileGetContents(url: $webmailDomain, versionIP: 6);
if ($v6Test['error']) { if ($v6Test['error']) {
if (!$quiet) { if (!$quiet) {
@ -2089,7 +2089,7 @@ class CLIController
$currentDBVersion = $this->settingsRepository->findByName(name: 'version'); $currentDBVersion = $this->settingsRepository->findByName(name: 'version');
$dbVersion = json_decode($currentDBVersion); $dbVersion = json_decode($currentDBVersion);
$currentDBBuildnumber= $this->settingsRepository->findByName(name: 'buildnumber'); $currentDBBuildnumber = $this->settingsRepository->findByName(name: 'buildnumber');
echo "DB version:\t\t"; echo "DB version:\t\t";
echo $dbVersion->version->major . '.'; echo $dbVersion->version->major . '.';
echo $dbVersion->version->minor . '.'; echo $dbVersion->version->minor . '.';

View File

@ -6,6 +6,7 @@ use App\Entity\Domain;
use App\Repository\DomainRepository; use App\Repository\DomainRepository;
use App\Repository\NameserverRepository; use App\Repository\NameserverRepository;
use App\Repository\PanelRepository; use App\Repository\PanelRepository;
use App\Service\ApiClient;
use Monolog\Logger; use Monolog\Logger;
error_reporting(error_level: E_ALL); error_reporting(error_level: E_ALL);
@ -25,7 +26,7 @@ class DomainController
public function __construct( public function __construct(
private readonly NameserverRepository $nameserverRepository, private readonly NameserverRepository $nameserverRepository,
private readonly ApiController $checkController, private readonly ApiClient $checkController,
private readonly DomainRepository $domainRepository, private readonly DomainRepository $domainRepository,
private readonly PanelRepository $panelRepository, private readonly PanelRepository $panelRepository,
private readonly ConfigController $configController, private readonly ConfigController $configController,

View File

@ -12,7 +12,10 @@ use App\Repository\DynDNSRepository;
use App\Repository\PanelRepository; use App\Repository\PanelRepository;
use Monolog\Logger; use Monolog\Logger;
use OpenApi\Attributes as OAT; use OpenApi\Attributes as OAT;
use OpenApi\Attributes\OpenApi;
use OpenApi\Generator;
use UnhandledMatchError; use UnhandledMatchError;
use function Symfony\Component\String\s;
// TODO attributes for swaggerUI // TODO attributes for swaggerUI
@ -26,13 +29,14 @@ use UnhandledMatchError;
description: "The bindAPI URL.", description: "The bindAPI URL.",
variables: [ variables: [
new OAT\ServerVariable( new OAT\ServerVariable(
serverVariable: "schema", serverVariable: 'schema',
default: "https", default: 'https',
enum: ["https", "http"] enum: ['http', 'https']
), ),
new OAT\ServerVariable( new OAT\ServerVariable(
serverVariable: "hostname", serverVariable: 'hostname',
default: "ns2.24unix.net", default: 'ns1.24unix.net',
enum: ['ns1.24unix.net', 'ns2.24unix.net', 'ns3.24unix.net', 'ns4.24unix.net']
) )
] ]
)] )]
@ -42,7 +46,7 @@ use UnhandledMatchError;
#[OAT\SecurityScheme( #[OAT\SecurityScheme(
securityScheme: "Authorization", securityScheme: "Authorization",
type: "apiKey", type: "apiKey",
description: "description", description: "Api Authentication",
name: "X-API-Key", name: "X-API-Key",
in: "header" in: "header"
)] )]
@ -56,19 +60,7 @@ class RequestController
private array $uri; private array $uri;
/**
* @param ApiController $apiController
* @param ApikeyRepository $apikeyRepository
* @param DomainController $domainController
* @param DomainRepository $domainRepository
* @param DynDNSRepository $dynDNSRepository
* @param PanelRepository $panelRepository
* @param ConfigController $configController
* @param EncryptionController $encryptionController
* @param Logger $logger
*/
public function __construct( public function __construct(
private readonly ApiController $apiController,
private readonly ApikeyRepository $apikeyRepository, private readonly ApikeyRepository $apikeyRepository,
private readonly DomainController $domainController, private readonly DomainController $domainController,
private readonly DomainRepository $domainRepository, private readonly DomainRepository $domainRepository,
@ -84,21 +76,68 @@ class RequestController
$this->result = []; $this->result = [];
} }
/** public function handleRequest(string $requestMethod, array $uri): void
* @return void {
*/ $this->logger->debug(message: "Request: $requestMethod $uri[1]");
$this->requestMethod = strtoupper(string: $requestMethod);
$this->uri = $uri;
$command = $this->uri[2];
// use my router class from address book?
$routes = ['domains', 'ping', 'apidoc', 'dyndns'];
if (empty($command) || !(in_array(needle: $command, haystack: $routes))) {
$this->status = "404 Not Found";
$this->message = "Endpoint not found.";
} else {
try {
match ($command) {
'dyndns' => $this->handleDynDNS(),
'ping' => $this->handlePing(),
'domains' => $this->handleDomains(),
'apidoc' => $this->apiDoc(),
};
} catch (UnhandledMatchError) {
$this->status = '400 Bad Request';
$this->message = 'Unknown path: ' . $command;
}
}
// process api requests
if (!empty($this->status)) {
header(header: $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->status);
}
if (!empty($this->response)) {
echo json_encode(value: [
'response' => $this->response
]);
} elseif (!empty($this->result)) {
echo json_encode(value: [
'result' => $this->result
]);
} elseif (!empty($this->message)) {
echo json_encode(value: [
'message' => $this->message
]);
} else {
echo json_encode(value: [
'message' => $this->message ?? 'Error: No message.'
]);
}
}
#[OAT\Get( #[OAT\Get(
path: '/domains', path: '/domains',
operationId: 'getAllDomains', operationId: 'getAllDomains',
description: 'Returns a list of all domains on this server.', description: 'Returns a list of all domains on this server.',
summary: 'Listing all domains.', summary: 'Listing all domains.',
// security: [ security: [
// 'Authorization' => [ ['Authorization' => []]
// ],
// "read:api"
// ]
// ],
servers: [],
tags: ['Domains'], tags: ['Domains'],
responses: [ responses: [
new OAT\Response( new OAT\Response(
@ -236,58 +275,8 @@ class RequestController
)] )]
)] )]
public function handleRequest(string $requestMethod, array $uri): void
{
$this->logger->debug(message: "Request: $requestMethod $uri[1]");
$this->requestMethod = strtoupper(string: $requestMethod);
$this->uri = $uri;
$command = $this->uri[2];
if (empty($command) || !(($command == 'domains') || ($command == 'ping') || ($command == 'apidoc') || ($command == 'dyndns'))) {
$this->status = "404 Not Found";
$this->message = "Endpoint not found.";
} else {
try {
match ($command) {
'dyndns' => $this->handleDynDNS(),
'ping' => $this->handlePing(),
'domains' => $this->handleDomains(),
};
} catch (UnhandledMatchError) {
$this->status = '400 Bad Request';
$this->message = 'Unknown path: ' . $command;
}
}
if (!empty($this->status)) {
header(header: $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->status);
}
if (!empty($this->response)) {
echo json_encode(value: [
'response' => $this->response
]);
} elseif (!empty($this->result)) {
echo json_encode(value: [
'result' => $this->result
]);
} elseif (!empty($this->message)) {
echo json_encode(value: [
'message' => $this->message
]);
} else {
echo json_encode(value: [
'message' => $this->message ?? 'Error: No message.'
]);
}
}
/**
* @return bool
*/
private function checkPassword(): bool private function checkPassword(): bool
{ {
$headers = array_change_key_case(array: getallheaders(), case: CASE_UPPER); $headers = array_change_key_case(array: getallheaders(), case: CASE_UPPER);
@ -537,7 +526,7 @@ class RequestController
$panel = $this->panelRepository->findByName(name: $domain->getPanel()); $panel = $this->panelRepository->findByName(name: $domain->getPanel());
if (!empty($panel->getAaaa())) { if (!empty($panel->getAaaa())) {
$domainData = $this->apiController->sendCommand( $domainData = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -545,7 +534,7 @@ class RequestController
command: 'domains/name/' . $domainName, command: 'domains/name/' . $domainName,
serverType: 'panel'); serverType: 'panel');
} else { } else {
$domainData = $this->apiController->sendCommand( $domainData = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -558,7 +547,7 @@ class RequestController
$domainID = $domainDecodedData->id; $domainID = $domainDecodedData->id;
if (!empty($panel->getAaaa())) { if (!empty($panel->getAaaa())) {
$dnsData = $this->apiController->sendCommand( $dnsData = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -566,7 +555,7 @@ class RequestController
command: 'dns/' . $domainID, command: 'dns/' . $domainID,
serverType: 'panel'); serverType: 'panel');
} else { } else {
$dnsData = $this->apiController->sendCommand( $dnsData = $this->apiClient->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -607,7 +596,7 @@ class RequestController
]); ]);
if (!empty($panel->getAaaa())) { if (!empty($panel->getAaaa())) {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'PUT', requestType: 'PUT',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -617,7 +606,7 @@ class RequestController
body: json_decode(json: $newDnsData, associative: true) body: json_decode(json: $newDnsData, associative: true)
); );
} else { } else {
$result = $this->apiController->sendCommand( $result = $this->apiClient->sendCommand(
requestType: 'PUT', requestType: 'PUT',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -664,5 +653,17 @@ class RequestController
return $host; return $host;
} }
private function apiDoc(): void
{
$srcDir = dirname(path: __DIR__);
$requestControllerPath = $srcDir . '/Controller/RequestController.php';
$openApi = Generator::scan(sources: [$requestControllerPath]);
header(header: 'Content-Type: application/json');
echo $openApi->toJson();
exit(0);
}
} }

View File

@ -1,25 +1,13 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
namespace App\Controller; namespace App\Service;
use UnhandledMatchError; use UnhandledMatchError;
error_reporting(error_level: E_ALL); error_reporting(error_level: E_ALL);
class ApiController class ApiClient
{ {
/**
* @param String $requestType
* @param String $serverName
* @param int $versionIP
* @param String $apiKey
* @param String $command
* @param String $serverType
* @param array $body
*
* @return array
*/
function sendCommand(string $requestType, string $serverName, int $versionIP, string $apiKey, string $command, string $serverType, array $body = []): array function sendCommand(string $requestType, string $serverName, int $versionIP, string $apiKey, string $command, string $serverType, array $body = []): array
{ {
$error = false; $error = false;
@ -113,7 +101,7 @@ class ApiController
$options = array( $options = array(
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true, CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "", CURLOPT_ENCODING => '',
CURLOPT_AUTOREFERER => true, CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120, CURLOPT_TIMEOUT => 120,
@ -139,4 +127,6 @@ class ApiController
return $header; return $header;
} }
} }

View File

@ -10,6 +10,7 @@ use App\Controller\DomainController;
use App\Controller\RequestController; use App\Controller\RequestController;
use App\Repository\DomainRepository; use App\Repository\DomainRepository;
use App\Repository\DynDNSRepository; use App\Repository\DynDNSRepository;
use App\Service\ApiClient;
use DI\Container; use DI\Container;
use DI\ContainerBuilder; use DI\ContainerBuilder;
use DI\DependencyException; use DI\DependencyException;
@ -19,77 +20,77 @@ use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler; use Monolog\Handler\StreamHandler;
use Monolog\Level; use Monolog\Level;
use Monolog\Logger; use Monolog\Logger;
use OpenApi\Attributes as OA;
use function DI\autowire; use function DI\autowire;
#[OA\Info(version: '1.0.9', title: 'bindAPI')]
class BindAPI class BindAPI
{ {
private Logger $logger; private Logger $logger;
private Container $container; private Container $container;
/** public function __construct(bool $quiet)
* @throws Exception {
*/ // init the logger
public function __construct(bool $quiet) $dateFormat = "Y:m:d H:i:s";
{ $output = "%datetime% %channel%.%level_name% %message%\n"; // %context% %extra%
// init the logger $formatter = new LineFormatter(format: $output, dateFormat: $dateFormat);
$dateFormat = "Y:m:d H:i:s";
$output = "%datetime% %channel%.%level_name% %message%\n"; // %context% %extra%
$formatter = new LineFormatter(format: $output, dateFormat: $dateFormat);
$debug = (new ConfigController(quiet: $quiet))->getConfig(configKey: 'debug'); $debug = (new ConfigController(quiet: $quiet))->getConfig(configKey: 'debug');
if ($debug) { if ($debug) {
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/var/log/bindAPI.debug', level: Level::Debug); $stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/var/log/bindAPI.debug', level: Level::Debug);
} else { } else {
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/var/log/bindAPI.info', level: Level::Info); $stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/var/log/bindAPI.info', level: Level::Info);
} }
$stream->setFormatter(formatter: $formatter); $stream->setFormatter(formatter: $formatter);
$this->logger = new Logger(name: 'bindAPI'); $this->logger = new Logger(name: 'bindAPI');
$this->logger->pushHandler(handler: $stream); $this->logger->pushHandler(handler: $stream);
$this->logger->debug(message: 'bindAPI started'); $this->logger->debug(message: 'bindAPI started');
$containerBuilder = new ContainerBuilder(); $containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([ $containerBuilder->addDefinitions([
ConfigController::class => autowire() ApiClient::class => autowire(),
ConfigController::class => autowire()
->constructorParameter(parameter: 'quiet', value: $quiet), ->constructorParameter(parameter: 'quiet', value: $quiet),
CLIController::class => autowire() CLIController::class => autowire()
->constructorParameter(parameter: 'logger', value: $this->logger) ->constructorParameter(parameter: 'logger', value: $this->logger)
->constructorParameter(parameter: 'quiet', value: $quiet), ->constructorParameter(parameter: 'quiet', value: $quiet),
DomainController::class => autowire() DomainController::class => autowire()
->constructorParameter(parameter: 'logger', value: $this->logger) ->constructorParameter(parameter: 'logger', value: $this->logger)
->constructorParameter(parameter: 'quiet', value: $quiet), ->constructorParameter(parameter: 'quiet', value: $quiet),
DomainRepository::class => autowire() DomainRepository::class => autowire()
->constructorParameter(parameter: 'logger', value: $this->logger), ->constructorParameter(parameter: 'logger', value: $this->logger),
DynDnsRepository::class => autowire() DynDnsRepository::class => autowire()
->constructorParameter(parameter: 'logger', value: $this->logger), ->constructorParameter(parameter: 'logger', value: $this->logger),
RequestController::class => autowire() RequestController::class => autowire()
->constructorParameter(parameter: 'logger', value: $this->logger) ->constructorParameter(parameter: 'logger', value: $this->logger)
]); ]);
$this->container = $containerBuilder->build(); $this->container = $containerBuilder->build();
} }
/** /**
* @throws DependencyException * @throws DependencyException
* @throws NotFoundException * @throws NotFoundException
*/ */
public function runCommand(array $arguments): void public function runCommand(array $arguments): void
{ {
$this->logger->debug(message: 'runCommand()'); $this->logger->debug(message: 'runCommand()');
$cliController = $this->container->get(name: CLIController::class); $cliController = $this->container->get(name: CLIController::class);
$cliController->runCommand(arguments: $arguments); $cliController->runCommand(arguments: $arguments);
} }
/** /**
* @throws DependencyException * @throws DependencyException
* @throws NotFoundException * @throws NotFoundException
*/ */
public function handleRequest(string $requestMethod, array $uri): void public function handleRequest(string $requestMethod, array $uri): void
{ {
$this->logger->debug(message: 'handleRequest()'); $this->logger->debug(message: 'handleRequest()');
$requestController = $this->container->get(name: RequestController::class); $requestController = $this->container->get(name: RequestController::class);
$requestController->handleRequest(requestMethod: $requestMethod, uri: $uri); $requestController->handleRequest(requestMethod: $requestMethod, uri: $uri);
} }
} }