refactored

This commit is contained in:
tracer 2022-09-17 16:28:04 +02:00
parent b25f0ab1eb
commit cce30b17ad
1 changed files with 72 additions and 127 deletions

View File

@ -10,14 +10,13 @@ use App\Repository\ApikeyRepository;
use App\Repository\DomainRepository; use App\Repository\DomainRepository;
use App\Repository\DynDNSRepository; use App\Repository\DynDNSRepository;
use App\Repository\PanelRepository; use App\Repository\PanelRepository;
use DI\Container;
use DI\ContainerBuilder;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger; use Monolog\Logger;
use OpenApi\Annotations as OA;
use OpenApi\Attributes as OAT; use OpenApi\Attributes as OAT;
use UnhandledMatchError; use UnhandledMatchError;
use function DI\autowire;
// TODO attributes for swaggerUI
/** /**
* *
@ -50,69 +49,36 @@ use function DI\autowire;
)] )]
class RequestController class RequestController
{ {
private Logger $log;
private ApiController $apiController;
private ApikeyRepository $apikeyRepository;
private DomainController $domainController;
private DomainRepository $domainRepository;
private PanelRepository $panelRepository;
private DynDNSRepository $dynDNSRepository;
private Container $container;
private string $header;
private array $result;
private string $status; private string $status;
private string $response;
private string $message; private string $message;
private array $result;
private string $requestMethod;
private array $uri;
/** /**
* @param array $config * @param \App\Controller\ApiController $apiController
* @param String $requestMethod * @param \App\Repository\ApikeyRepository $apikeyRepository
* @param array $uri * @param \App\Controller\DomainController $domainController
* * @param \App\Repository\DomainRepository $domainRepository
* @throws \Exception * @param \App\Repository\DynDNSRepository $dynDNSRepository
* @param \App\Repository\PanelRepository $panelRepository
* @param \Monolog\Logger $logger
*/ */
public function __construct(private array $config, private string $requestMethod, private array $uri) public function __construct(
private readonly ApiController $apiController,
private readonly ApikeyRepository $apikeyRepository,
private readonly DomainController $domainController,
private readonly DomainRepository $domainRepository,
private readonly DynDNSRepository $dynDNSRepository,
private readonly PanelRepository $panelRepository,
private readonly Logger $logger)
{ {
$this->requestMethod = strtoupper(string: $requestMethod); $this->status = '';
$this->response = '';
$dateFormat = "Y:m:d H:i:s"; $this->message = '';
$output = "%datetime% %channel%.%level_name% %message%\n"; // %context% %extra% $this->result = [];
$formatter = new LineFormatter(format: $output, dateFormat: $dateFormat);
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log');
$stream->setFormatter(formatter: $formatter);
$this->log = new Logger(name: 'bindAPI');
$this->log->pushHandler(handler: $stream);
if ($this->config['debug']) {
$this->log->debug(message: 'RequestController::__construct');
}
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([
DatabaseConnection::class => autowire()->constructorParameter(parameter: 'config', value: $this->config),
DomainController::class => autowire()
->constructorParameter(parameter: 'config', value: $this->config)
->constructorParameter(parameter: 'log', value: $this->log),
DomainRepository::class => autowire()
->constructorParameter(parameter: 'config', value: $this->config)
->constructorParameter(parameter: 'log', value: $this->log),
DynDNSRepository::class => autowire()
->constructorParameter(parameter: 'config', value: $this->config)
->constructorParameter(parameter: 'log', value: $this->log),
]);
$this->container = $containerBuilder->build();
$this->apiController = $this->container->get(name: ApiController::class);
$this->apikeyRepository = $this->container->get(name: ApikeyRepository::class);
$this->domainController = $this->container->get(name: DomainController::class);
$this->domainRepository = $this->container->get(name: DomainRepository::class);
$this->panelRepository = $this->container->get(name: PanelRepository::class);
$this->dynDNSRepository = $this->container->get(name: DynDNSRepository::class);
} }
/** /**
@ -162,14 +128,14 @@ class RequestController
/** /**
*/ */
private function handlePing() private function handlePing(): void
{ {
if ($this->checkPassword()) { if ($this->checkPassword()) {
$this->header = '200 OK'; $this->status = '200 OK';
$this->status = json_encode(value: ['response' => 'pong']); $this->response = 'pong';
} else { } else {
$this->header = '401 Unauthorized'; $this->status = '401 Unauthorized';
$this->status = json_encode(value: ['message' => 'API key is missing or invalid']); $this->message = 'API key is missing or invalid';
} }
} }
@ -188,7 +154,6 @@ class RequestController
'DELETE' => $this->handleDomainsDeleteRequest() 'DELETE' => $this->handleDomainsDeleteRequest()
}; };
} catch (UnhandledMatchError) { } catch (UnhandledMatchError) {
$this->header = '400 Bad Request';
$this->status = '400 Bad Request'; $this->status = '400 Bad Request';
$this->message = "unknown request method: $this->requestMethod"; $this->message = "unknown request method: $this->requestMethod";
} }
@ -235,6 +200,9 @@ class RequestController
* {"Authorization":{"read":"write"}} * {"Authorization":{"read":"write"}}
* } * }
* ) * )
* @param string $requestMethod
* @param array $uri
*
* @return void * @return void
*/ */
@ -265,40 +233,50 @@ class RequestController
)] )]
)] )]
public function processRequest() 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]; $command = $this->uri[2];
if (empty($command) || !(($command == 'domains') || ($command == 'ping') || ($command == 'apidoc') || ($command == 'dyndns'))) { if (empty($command) || !(($command == 'domains') || ($command == 'ping') || ($command == 'apidoc') || ($command == 'dyndns'))) {
$this->header = '404 Not Found';
$this->status = "404 Not Found"; $this->status = "404 Not Found";
$this->message = "Endpoint not found."; $this->message = "Endpoint not found.";
} else { } else {
try { try {
match ($command) { match ($command) {
'apidoc' => $this->apiDoc(),
'dyndns' => $this->handleDynDNS(), 'dyndns' => $this->handleDynDNS(),
'ping' => $this->handlePing(), 'ping' => $this->handlePing(),
'domains' => $this->handleDomains(), 'domains' => $this->handleDomains(),
}; };
} catch (UnhandledMatchError) { } catch (UnhandledMatchError) {
$this->header = '404 Bad Request'; $this->status = '400 Bad Request';
$this->status = '404 Bad Request';
$this->message = 'Unknown path: ' . $command; $this->message = 'Unknown path: ' . $command;
} }
} }
if (!empty($this->header)) { if (!empty($this->status)) {
header(header: $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->header); header(header: $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->status);
} }
if (!empty($this->result)) { if (!empty($this->response)) {
echo json_encode(value: $this->result); echo json_encode(value: [
} elseif (!empty($this->status)) { 'response' => $this->response
echo $this->status; ]);
} elseif (!empty($this->result)) {
echo json_encode(value: [
'result' => $this->result
]);
} elseif (!empty($this->message)) {
echo json_encode(value: [
'message' => $this->message
]);
} else { } else {
echo json_encode(value: [ echo json_encode(value: [
'message' => $this->message ?? "Error: No message." 'message' => $this->message ?? 'Error: No message.'
]); ]);
} }
} }
@ -313,7 +291,6 @@ class RequestController
$apiKey = $headers['X-API-KEY'] ?? ''; $apiKey = $headers['X-API-KEY'] ?? '';
if (empty($apiKey)) { if (empty($apiKey)) {
$this->header = "401 Unauthorized";
$this->status = "401 Unauthorized"; $this->status = "401 Unauthorized";
$this->message = "API key is missing."; $this->message = "API key is missing.";
return false; return false;
@ -322,13 +299,11 @@ class RequestController
if ($apiResult = $this->apikeyRepository->findByPrefix(prefix: $prefix)) { if ($apiResult = $this->apikeyRepository->findByPrefix(prefix: $prefix)) {
$storedHash = $apiResult->getApiToken(); $storedHash = $apiResult->getApiToken();
if (!password_verify(password: $apiKey, hash: $storedHash)) { if (!password_verify(password: $apiKey, hash: $storedHash)) {
$this->header = "401 Unauthorized";
$this->status = "401 Unauthorized"; $this->status = "401 Unauthorized";
$this->message = "API key mismatch."; $this->message = "API key mismatch.";
return false; return false;
} }
} else { } else {
$this->header = "401 Unauthorized";
$this->status = "401 Unauthorized"; $this->status = "401 Unauthorized";
$this->message = "Invalid API key."; $this->message = "Invalid API key.";
return false; return false;
@ -354,7 +329,6 @@ class RequestController
]; ];
$this->result = $domain; $this->result = $domain;
} else { } else {
$this->header = "404 Not Found ";
$this->status = "404 Not Found "; $this->status = "404 Not Found ";
$this->message = "The specified domain was not found."; $this->message = "The specified domain was not found.";
} }
@ -372,13 +346,11 @@ class RequestController
]; ];
$this->result = $domain; $this->result = $domain;
} else { } else {
$this->header = "404 Not Found ";
$this->status = "404 Not Found "; $this->status = "404 Not Found ";
$this->message = "The specified domain was not found."; $this->message = "The specified domain was not found.";
} }
} else { } else {
$this->header = "400 Bad request"; $this->status = "400 Bad Request";
$this->status = "400 Not Found";
$this->message = "You need to supply an ID or user the /domain/name/<name> path."; $this->message = "You need to supply an ID or user the /domain/name/<name> path.";
} }
@ -395,27 +367,22 @@ class RequestController
$name = $_POST['name'] ?? ''; $name = $_POST['name'] ?? '';
$panel = $_POST['panel'] ?? ''; $panel = $_POST['panel'] ?? '';
if (empty($name)) { if (empty($name)) {
$this->header = "400 Bad Request";
$this->status = "400 Bad Request"; $this->status = "400 Bad Request";
$this->message = "A name is required"; $this->message = "A name is required";
} else { } else {
if (empty($panel)) { if (empty($panel)) {
$this->header = "400 Bad Request";
$this->status = "400 Bad Request"; $this->status = "400 Bad Request";
$this->message = "A panel ID is required."; $this->message = "A panel ID is required.";
} else { } else {
if ($this->domainRepository->findByName(name: $name)) { if ($this->domainRepository->findByName(name: $name)) {
$this->header = "400 Bad request";
$this->status = "400 Bad request"; $this->status = "400 Bad request";
$this->message = "Domain: $name already exists."; $this->message = "Domain: $name already exists.";
} else { } else {
$domain = new Domain(name: $name, panel: $panel); $domain = new Domain(name: $name, panel: $panel);
if ($result = $this->domainRepository->insert(domain: $domain)) { if ($result = $this->domainRepository->insert(domain: $domain)) {
$this->header = "201 Created";
$this->status = "201 Created"; $this->status = "201 Created";
$this->domainController->createSlaveZoneFile(domain: $domain); $this->domainController->createSlaveZoneFile(domain: $domain);
} else { } else {
$this->header = "500 Server error";
$this->status = "500 Server error"; $this->status = "500 Server error";
} }
$this->message = $result; $this->message = $result;
@ -443,7 +410,6 @@ class RequestController
$panel = $put['panel'] ?? ""; $panel = $put['panel'] ?? "";
if ($id == 0) { if ($id == 0) {
$this->header = "400 Bad Request";
$this->status = "400 Bad Request"; $this->status = "400 Bad Request";
$this->message = "An ID is required"; $this->message = "An ID is required";
} else { } else {
@ -453,7 +419,6 @@ class RequestController
} else { } else {
$domain = new Domain(name: $name, panel: $panel, id: $id); $domain = new Domain(name: $name, panel: $panel, id: $id);
$this->domainRepository->update(domain: $domain); $this->domainRepository->update(domain: $domain);
$this->header = "201 Updated";
$this->status = "201 Updated"; $this->status = "201 Updated";
$this->message = "201 Updated"; $this->message = "201 Updated";
$this->domainController->createSlaveZoneFile(domain: $domain); $this->domainController->createSlaveZoneFile(domain: $domain);
@ -479,42 +444,30 @@ class RequestController
$id = $delete['id'] ?? 0; $id = $delete['id'] ?? 0;
if ($id == 0) { if ($id == 0) {
$this->header = "400 Bad Request";
$this->status = "400 Bad Request"; $this->status = "400 Bad Request";
$this->message = "You need to supply an ID."; $this->message = "You need to supply an ID.";
} else { } else {
if (!$domain = $this->domainRepository->findByID(id: $id)) { if (!$domain = $this->domainRepository->findByID(id: $id)) {
$this->header = "400 Bad Request";
$this->status = "400 Bad Request"; $this->status = "400 Bad Request";
$this->message = "There is no domain with ID $id."; $this->message = "There is no domain with ID $id.";
} else { } else {
$this->domainRepository->delete(domain: $domain); $this->domainRepository->delete(domain: $domain);
$this->header = "204 No content.";
$this->status = "204 No content."; $this->status = "204 No content.";
$this->message = "The domain $id has been deleted."; $this->message = "The domain $id has been deleted.";
} }
} }
} }
private function apiDoc()
private function handleDynDNS(): void
{ {
//TODO forward to apidoc … $this->logger->debug(message: 'handleDynDNS()');
}
private function handleDynDNS()
{
if ($this->config['debug']) {
$this->log->debug(message: 'handleDynDNS()');
}
if ($this->checkPassword()) { if ($this->checkPassword()) {
$host = $this->uri[3] ?? ''; $host = $this->uri[3] ?? '';
if (empty($host)) { if (empty($host)) {
$this->header = '400 Bad Request';
$this->status = '400 Bad Request'; $this->status = '400 Bad Request';
} else { } else {
$a = $_POST['a'] ?? ''; $a = $_POST['a'] ?? '';
@ -530,33 +483,27 @@ class RequestController
} }
} }
if ($this->config['debug']) { $this->logger->debug(message: 'a: ' . $a);
$this->log->debug(message: 'a: ' . $a); $this->logger->debug(message: 'aaaa: ' . $aaaa);
$this->log->debug(message: 'aaaa: ' . $aaaa);
}
$domainName = $this->getDomain(host: $host); $domainName = $this->getDomain(host: $host);
$hostName = str_replace(search: '.' . $domainName, replace: '', subject: $host); $hostName = str_replace(search: '.' . $domainName, replace: '', subject: $host);
if (!$domain = $this->domainRepository->findByName(name: $domainName)) { if (!$domain = $this->domainRepository->findByName(name: $domainName)) {
$this->header = '404 Not Found'; $this->status = '404 Not Found';
$this->message = 'Domain ' . $domainName . ' not found'; $this->message = 'Domain ' . $domainName . ' not found';
} else { } else {
// check if address has changed // check if address has changed
if ($dynDNS = $this->dynDNSRepository->findByName(name: $host)) { if ($dynDNS = $this->dynDNSRepository->findByName(name: $host)) {
if ($this->config['debug']) { $this->logger->debug(message: 'found host: ' . $host);
$this->log->debug(message: 'found host: ' . $host); $this->logger->debug(message: "a: $a");
$this->log->debug(message: "a: $a"); $this->logger->debug(message: "aaaa: $aaaa");
$this->log->debug(message: "aaaa: $aaaa");
}
$ipChanged = false; $ipChanged = false;
if (!empty($a)) { if (!empty($a)) {
if ($a != $dynDNS->getA()) { if ($a != $dynDNS->getA()) {
if ($this->config['debug']) { $this->logger->debug(message: $a . ' != ' . $dynDNS->getA());
$this->log->debug(message: $a . ' != ' . $dynDNS->getA());
}
$dynDNS->setA(a: $a); $dynDNS->setA(a: $a);
$ipChanged = true; $ipChanged = true;
} }
@ -564,9 +511,7 @@ class RequestController
if (!empty($aaaa)) { if (!empty($aaaa)) {
if ($aaaa != $dynDNS->getAaaa()) { if ($aaaa != $dynDNS->getAaaa()) {
if ($this->config['debug']) { $this->logger->debug(message: $aaaa . ' != ' . $dynDNS->getAaaa());
$this->log->debug(message: $aaaa . ' != ' . $dynDNS->getAaaa());
}
$dynDNS->setAaaa(aaaa: $aaaa); $dynDNS->setAaaa(aaaa: $aaaa);
$ipChanged = true; $ipChanged = true;
} }
@ -677,15 +622,15 @@ class RequestController
); );
} }
if ($result['header'] == 200) { if ($result['header'] == 200) {
$this->header = '200 OK'; $this->status = '200 OK';
$this->message = 'DynDNS host successfully updated'; $this->message = 'DynDNS host successfully updated';
} }
} else { } else {
$this->header = '404 Not Found'; $this->status = '404 Not Found';
$this->message = 'Host ' . $hostName . ' not found'; $this->message = 'Host ' . $hostName . ' not found';
} }
} else { } else {
$this->header = '204 No content'; $this->status = '204 No content';
$this->message = 'No content'; $this->message = 'No content';
} }
} }