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