Compare commits

..

8 Commits

Author SHA1 Message Date
tracer f70e87afce changed startpage
Signed-off-by: tracer <tracer@24unix.net>
2022-02-06 18:00:15 +01:00
tracer 909bfcdc85 added logger
Signed-off-by: tracer <tracer@24unix.net>
2022-02-06 17:59:43 +01:00
tracer ca1d4577dc added logger
Signed-off-by: tracer <tracer@24unix.net>
2022-02-06 17:59:17 +01:00
tracer 4fb5cdcffd refactored handleAllDomainsGetRequest
Signed-off-by: tracer <tracer@24unix.net>
2022-02-06 17:58:52 +01:00
tracer 0241afaa25 removed OAT
Signed-off-by: tracer <tracer@24unix.net>
2022-02-06 17:43:40 +01:00
tracer 6665933a41 added logger
Signed-off-by: tracer <tracer@24unix.net>
2022-02-06 17:42:26 +01:00
tracer b2452d349a changed params from array to Nameserver
Signed-off-by: tracer <tracer@24unix.net>
2022-02-06 17:42:01 +01:00
tracer b862611433 added Logger and config
Signed-off-by: tracer <tracer@24unix.net>
2022-02-06 17:41:04 +01:00
8 changed files with 371 additions and 219 deletions

View File

@ -14,6 +14,24 @@ $configJSON = file_get_contents(filename: $configFile);
$config = json_decode(json: $configJSON, associative: true); $config = json_decode(json: $configJSON, associative: true);
// TODO make a log class
$oFile = fopen(filename: 'log.txt', mode: 'a');
$uri = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH);
fputs(stream: $oFile, data: $uri . PHP_EOL);
fputs(stream: $oFile, data: "here");
$uri = explode(separator: '/', string: $uri);
fclose(stream: $oFile);
if ($uri[1] !== 'api') {
$scheme = $_SERVER['REQUEST_SCHEME'];
$host = $_SERVER['SERVER_NAME'];
$header = "$scheme://$host/openapi/index.html";
header(header: "Location: $header");
exit(0);
}
// TODO only valid clients? // TODO only valid clients?
header(header: "Access-Control-Allow-Origin: *"); header(header: "Access-Control-Allow-Origin: *");
header(header: "Content-Type: application/json; charset=UTF-8"); header(header: "Content-Type: application/json; charset=UTF-8");
@ -22,19 +40,6 @@ header(header: "Access-Control-Max-Age: 3600");
header(header: "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); header(header: "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// TODO make a log class
$oFile = fopen(filename: 'log.txt', mode: 'a');
$uri = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH);
fputs(stream: $oFile, data: $uri . PHP_EOL);
fclose(stream: $oFile);
$uri = explode(separator: '/', string: $uri);
if ($uri[1] !== 'api') {
header(header: "HTTP/1.1 404 Not Found");
exit();
}
$requestMethod = $_SERVER["REQUEST_METHOD"]; $requestMethod = $_SERVER["REQUEST_METHOD"];
try { try {

View File

@ -13,6 +13,7 @@ define(constant_name: 'COLOR_DEFAULT', value: "\033[39m");
use App\Entity\Domain; use App\Entity\Domain;
use App\Entity\Nameserver;
use App\Entity\Panel; use App\Entity\Panel;
use App\Repository\ApikeyRepository; use App\Repository\ApikeyRepository;
use App\Repository\DomainRepository; use App\Repository\DomainRepository;
@ -24,6 +25,9 @@ use DI\ContainerBuilder;
use DI\DependencyException; use DI\DependencyException;
use DI\NotFoundException; use DI\NotFoundException;
use LucidFrame\Console\ConsoleTable; use LucidFrame\Console\ConsoleTable;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use UnhandledMatchError; use UnhandledMatchError;
use function DI\autowire; use function DI\autowire;
@ -36,14 +40,14 @@ if (php_sapi_name() !== 'cli') {
*/ */
class BindAPI class BindAPI
{ {
//private DatabaseConnection $databaseConnection; private Logger $log;
private DomainController $domainController; private ApiController $apiController;
private PanelController $panelController;
private NameserverController $nameserverController;
private CheckController $checkController;
private DomainRepository $domainRepository;
private NameserverRepository $nameserverRepository;
private ApikeyRepository $apikeyRepository; private ApikeyRepository $apikeyRepository;
private DomainController $domainController;
private DomainRepository $domainRepository;
private NameserverController $nameserverController;
private NameserverRepository $nameserverRepository;
private PanelController $panelController;
private PanelRepository $panelRepository; private PanelRepository $panelRepository;
private Container $container; private Container $container;
@ -55,26 +59,46 @@ class BindAPI
*/ */
public function __construct(private array $config, private int $argumentsCount, private array $arguments) public function __construct(private array $config, private int $argumentsCount, private array $arguments)
{ {
$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);
$containerBuilder = new ContainerBuilder(); $containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([ $containerBuilder->addDefinitions([
DatabaseConnection::class => autowire()->constructorParameter(parameter: 'config', value: $this->config), 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),
]); ]);
$this->container = $containerBuilder->build(); $this->container = $containerBuilder->build();
//$this->databaseConnection = $this->container->get(name: DatabaseConnection::class); $this->apiController = $this->container->get(name: ApiController::class);
$this->panelController = $this->container->get(name: PanelController::class);
$this->checkController = $this->container->get(name: CheckController::class);
$this->nameserverController = $this->container->get(name: NameserverController::class);
$this->domainController = $this->container->get(name: DomainController::class); $this->domainController = $this->container->get(name: DomainController::class);
$this->domainRepository = $this->container->get(name: DomainRepository::class); $this->domainRepository = $this->container->get(name: DomainRepository::class);
$this->nameserverController = $this->container->get(name: NameserverController::class);
$this->nameserverRepository = $this->container->get(name: NameserverRepository::class); $this->nameserverRepository = $this->container->get(name: NameserverRepository::class);
$this->apikeyRepository = $this->container->get(name: ApikeyRepository::class); $this->panelController = $this->container->get(name: PanelController::class);
$this->panelRepository = $this->container->get(name: PanelRepository::class); $this->panelRepository = $this->container->get(name: PanelRepository::class);
$this->apikeyRepository = $this->container->get(name: ApikeyRepository::class);
//$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);
} }
function runCommand() function runCommand()
{ {
if ($this->config['debug']) {
$this->log->debug(message: "runCommand()");
}
if ($this->argumentsCount < 1) { if ($this->argumentsCount < 1) {
$this->showUsage(); $this->showUsage();
exit(0); exit(0);
@ -106,12 +130,16 @@ class BindAPI
*/ */
function showUsage(): void function showUsage(): void
{ {
if ($this->config['debug']) {
$this->log->debug(message: "showUsage()");
}
echo COLOR_YELLOW . 'Usage:' . PHP_EOL; echo COLOR_YELLOW . 'Usage:' . PHP_EOL;
echo COLOR_DEFAULT . "\t./bin/console {options} {arguments}" . PHP_EOL . PHP_EOL; echo COLOR_DEFAULT . "\t./bin/console {options} {arguments}" . PHP_EOL . PHP_EOL;
echo COLOR_YELLOW . 'Options:' . PHP_EOL; echo COLOR_YELLOW . 'Options:' . PHP_EOL;
echo COLOR_GREEN . "\t-v, --version\t\t" . COLOR_DEFAULT . "Display the version of the API" . PHP_EOL; echo COLOR_GREEN . "\t-v, --version\t\t" . COLOR_DEFAULT . "Display the version of the API" . PHP_EOL;
echo COLOR_GREEN . "\t-V, --verbose\t\t" . COLOR_DEFAULT . "All :list command are auto-verbose" . PHP_EOL . PHP_EOL; echo COLOR_GREEN . "\t-V, --verbose\t\t" . COLOR_DEFAULT . "All :lists command are auto-verbose" . PHP_EOL . PHP_EOL;
echo COLOR_YELLOW . "check" . COLOR_DEFAULT . "\t health checks the system can perform" . PHP_EOL; echo COLOR_YELLOW . "check" . COLOR_DEFAULT . "\t health checks the system can perform" . PHP_EOL;
echo COLOR_GREEN . "\t check:permissions" . PHP_EOL; echo COLOR_GREEN . "\t check:permissions" . PHP_EOL;
@ -122,26 +150,26 @@ class BindAPI
echo COLOR_GREEN . "\t panels:list" . PHP_EOL; echo COLOR_GREEN . "\t panels:list" . PHP_EOL;
echo COLOR_GREEN . "\t panels:create <name> {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL; echo COLOR_GREEN . "\t panels:create <name> {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t panels:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL; echo COLOR_GREEN . "\t panels:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t panels:delete" . PHP_EOL; echo COLOR_GREEN . "\t panels:delete <ID>" . PHP_EOL;
echo COLOR_GREEN . "\t panels:apiping {<ID>}" . PHP_EOL; echo COLOR_GREEN . "\t panels:apiping {<ID>}" . PHP_EOL;
echo COLOR_YELLOW . "nameservers" . COLOR_DEFAULT . " available nameservers" . PHP_EOL; echo COLOR_YELLOW . "nameservers" . COLOR_DEFAULT . " available nameservers" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:list" . PHP_EOL; echo COLOR_GREEN . "\t nameservers:list" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:create <name> {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL; echo COLOR_GREEN . "\t nameservers:create <name> {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:update <ID> {name=<name>} {panel_id=<ID>} {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL; echo COLOR_GREEN . "\t nameservers:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:delete <ID>" . PHP_EOL; echo COLOR_GREEN . "\t nameservers:delete <ID>" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:apiping {<ID>}" . PHP_EOL; echo COLOR_GREEN . "\t nameservers:apiping {<ID>}" . PHP_EOL;
echo COLOR_YELLOW . "domains" . COLOR_DEFAULT . " domains this server is responsible for" . PHP_EOL; echo COLOR_YELLOW . "domains" . COLOR_DEFAULT . " domains this server is responsible for" . PHP_EOL;
echo COLOR_GREEN . "\t domains:list" . PHP_EOL; echo COLOR_GREEN . "\t domains:list" . PHP_EOL;
echo COLOR_GREEN . "\t domains:create <name> {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL; echo COLOR_GREEN . "\t domains:create <name> {panel_id=<ID>} | {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL;
echo COLOR_GREEN . "\t domains:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL; echo COLOR_GREEN . "\t domains:update <ID> {name=<name>} {panel_id=<ID>} | {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL;
echo COLOR_GREEN . "\t domains:delete <ID>" . PHP_EOL; echo COLOR_GREEN . "\t domains:delete <ID>" . PHP_EOL;
echo COLOR_YELLOW . "apikeys" . COLOR_DEFAULT . "\t API keys for other nameservers" . PHP_EOL; echo COLOR_YELLOW . "apikeys" . COLOR_DEFAULT . "\t API keys for other nameservers" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:list" . PHP_EOL; echo COLOR_GREEN . "\t apikeys:list" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:create {name=<name>}" . PHP_EOL; echo COLOR_GREEN . "\t apikeys:create {name=<name>}" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:update <ID> name=<name>" . PHP_EOL; echo COLOR_GREEN . "\t apikeys:update <ID> {name=<name>}" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:delete <ID>" . PHP_EOL; echo COLOR_GREEN . "\t apikeys:delete <ID>" . PHP_EOL;
echo PHP_EOL . "\033[39me.g. ./bin/console apikeys:list" . PHP_EOL; echo PHP_EOL . "\033[39me.g. ./bin/console apikeys:list" . PHP_EOL;
@ -149,6 +177,10 @@ class BindAPI
function handleChecks(string $subcommand) function handleChecks(string $subcommand)
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handleChecks()");
}
try { try {
match ($subcommand) { match ($subcommand) {
'permissions' => $this->handleCheckPermissions(), 'permissions' => $this->handleCheckPermissions(),
@ -167,6 +199,10 @@ class BindAPI
*/ */
function handleCheckPermissions() function handleCheckPermissions()
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handleCheckPermissions()");
}
$this->domainController->checkPermissions(); $this->domainController->checkPermissions();
} }
@ -176,6 +212,10 @@ class BindAPI
*/ */
function handleCheckPanels() function handleCheckPanels()
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handleCheckPanels()");
}
$id = intval(value: $this->arguments[1] ?? 0); $id = intval(value: $this->arguments[1] ?? 0);
if ($id != 0) { if ($id != 0) {
@ -193,17 +233,22 @@ class BindAPI
} }
} }
/** /**
* @param array $panel * @param \App\Entity\Panel $panel
* *
* @return void * @return void
*/ */
public function checkSinglePanel(Panel $panel): void public function checkSinglePanel(Panel $panel): void
{ {
if ($this->config['debug']) {
$this->log->debug(message: "checkSinglePanel()");
}
echo COLOR_DEFAULT . 'Keyhelp-Panel: ' . COLOR_YELLOW . $panel->getName() . PHP_EOL; echo COLOR_DEFAULT . 'Keyhelp-Panel: ' . COLOR_YELLOW . $panel->getName() . PHP_EOL;
if (!empty($panel->getAaaa())) { if (!empty($panel->getAaaa())) {
try { try {
$result = $this->checkController->sendCommand( $result = $this->apiController->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 6, versionIP: 6,
@ -216,7 +261,7 @@ class BindAPI
} }
} else { } else {
try { try {
$result = $this->checkController->sendCommand( $result = $this->apiController->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $panel->getName(), serverName: $panel->getName(),
versionIP: 4, versionIP: 4,
@ -263,6 +308,10 @@ class BindAPI
function isValidSecondLevelDomain(string $domainName, string $panel, int $parent): bool function isValidSecondLevelDomain(string $domainName, string $panel, int $parent): bool
{ {
if ($this->config['debug']) {
$this->log->debug(message: "isValidSecondLevelDomain()");
}
// subdomain // subdomain
if ($parent != 0) { if ($parent != 0) {
return false; return false;
@ -294,6 +343,10 @@ class BindAPI
*/ */
function checkNS(string $domainName, $panel) function checkNS(string $domainName, $panel)
{ {
if ($this->config['debug']) {
$this->log->debug(message: "checkNS()");
}
try { try {
$nameServers = $this->nameserverRepository->findAll(); $nameServers = $this->nameserverRepository->findAll();
} catch (DependencyException|NotFoundException $e) { } catch (DependencyException|NotFoundException $e) {
@ -309,7 +362,7 @@ class BindAPI
} }
try { try {
if (!empty($nameServer->getName())) { if (!empty($nameServer->getName())) {
$result = $this->checkController->sendCommand( $result = $this->apiController->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $nameServer->getName(), serverName: $nameServer->getName(),
versionIP: 6, versionIP: 6,
@ -317,7 +370,7 @@ class BindAPI
command: 'domains/' . $domainName, command: 'domains/' . $domainName,
serverType: 'nameserver'); serverType: 'nameserver');
} else { } else {
$result = $this->checkController->sendCommand( $result = $this->apiController->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $nameServer->getName(), serverName: $nameServer->getName(),
versionIP: 4, versionIP: 4,
@ -332,7 +385,7 @@ class BindAPI
if ($result['header'] == 200) { if ($result['header'] == 200) {
echo COLOR_GREEN . ' OK'; echo COLOR_GREEN . ' OK';
} else { } else {
echo COLOR_RED . ' missing' . COLOR_DEFAULT; echo COLOR_RED . $result['header'] . COLOR_DEFAULT;
$arguments = $this->parseArguments(); $arguments = $this->parseArguments();
if (!empty($arguments['fix']) && $arguments['fix'] == 'yes') { if (!empty($arguments['fix']) && $arguments['fix'] == 'yes') {
echo 'trying to fix …'; echo 'trying to fix …';
@ -342,7 +395,7 @@ class BindAPI
]; ];
try { try {
if (!empty($nameServer['aaaa'])) { if (!empty($nameServer['aaaa'])) {
$this->checkController->sendCommand( $this->apiController->sendCommand(
requestType: 'POST', requestType: 'POST',
serverName: $nameServer['name'], serverName: $nameServer['name'],
versionIP: 6, versionIP: 6,
@ -351,7 +404,7 @@ class BindAPI
serverType: 'nameserver', serverType: 'nameserver',
body: $body); body: $body);
} else { } else {
$this->checkController->sendCommand( $this->apiController->sendCommand(
requestType: 'POST', requestType: 'POST',
serverName: $nameServer['name'], serverName: $nameServer['name'],
versionIP: 4, versionIP: 4,
@ -375,6 +428,10 @@ class BindAPI
*/ */
public function parseArguments(): array public function parseArguments(): array
{ {
if ($this->config['debug']) {
$this->log->debug(message: "parseArguments()");
}
$arguments = []; $arguments = [];
foreach ($this->arguments as $argument) { foreach ($this->arguments as $argument) {
if (str_contains(haystack: $argument, needle: '=')) { if (str_contains(haystack: $argument, needle: '=')) {
@ -394,6 +451,10 @@ class BindAPI
*/ */
public function handlePanels(string $subcommand): void public function handlePanels(string $subcommand): void
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handlePanels()");
}
try { try {
match ($subcommand) { match ($subcommand) {
'create' => $this->handlePanelsCreate(), 'create' => $this->handlePanelsCreate(),
@ -414,6 +475,10 @@ class BindAPI
*/ */
function handlePanelsCreate(): void function handlePanelsCreate(): void
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handlePanelsCreate()");
}
$name = $this->arguments[1] ?? ''; $name = $this->arguments[1] ?? '';
if (empty($name)) { if (empty($name)) {
echo 'You need to supply the panel name.' . PHP_EOL; echo 'You need to supply the panel name.' . PHP_EOL;
@ -458,6 +523,10 @@ class BindAPI
*/ */
function handlePanelsList(): void function handlePanelsList(): void
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handlePanelsList()");
}
echo 'All available panels:' . PHP_EOL; echo 'All available panels:' . PHP_EOL;
try { try {
$panels = $this->panelRepository->findAll(); $panels = $this->panelRepository->findAll();
@ -491,12 +560,17 @@ class BindAPI
exit(0); exit(0);
} }
/** /**
* @throws \DI\DependencyException * @throws \DI\DependencyException
* @throws \DI\NotFoundException * @throws \DI\NotFoundException
*/ */
function handlePanelsUpdate() function handlePanelsUpdate()
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handlePanelsUpdate()");
}
$arguments = $this->parseArguments(); $arguments = $this->parseArguments();
$id = $this->arguments[1] ?? 0; $id = $this->arguments[1] ?? 0;
@ -526,6 +600,10 @@ class BindAPI
*/ */
function handlePanelsDelete() function handlePanelsDelete()
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handlePanelsDelete()");
}
if (empty($this->arguments[1])) { if (empty($this->arguments[1])) {
echo "You need to supply an ID." . PHP_EOL; echo "You need to supply an ID." . PHP_EOL;
exit(1); exit(1);
@ -550,6 +628,10 @@ class BindAPI
*/ */
function handleAPIPing(string $type) function handleAPIPing(string $type)
{ {
if ($this->config['debug']) {
$this->log->debug(message: "handleApiPing()");
}
$error = false; $error = false;
$id = $this->getId(); $id = $this->getId();
@ -644,7 +726,7 @@ class BindAPI
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) . ' ';
} }
try { try {
if ($result = $this->checkController->sendCommand( if ($result = $this->apiController->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $server['name'], serverName: $server['name'],
versionIP: 4, versionIP: 4,
@ -671,7 +753,7 @@ class BindAPI
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) . ' ';
} }
try { try {
if ($result = $this->checkController->sendCommand( if ($result = $this->apiController->sendCommand(
requestType: 'GET', requestType: 'GET',
serverName: $server['name'], serverName: $server['name'],
versionIP: 6, versionIP: 6,
@ -924,16 +1006,16 @@ class BindAPI
echo "Domain: $name already exists." . PHP_EOL; echo "Domain: $name already exists." . PHP_EOL;
exit(1); exit(1);
} else { } else {
$result = $this->domainRepository->insert(name: $name, panelID: $panelID, a: $a, aaaa: $aaaa);
echo "Domain $name has been created with id $result" . PHP_EOL;
if (!empty($panelID)) { if (!empty($panelID)) {
if ($panel = $this->panelController->findByID(id: $panelID)) { if ($panel = $this->panelController->findByID(id: $panelID)) {
$a = $panel['a']; $a = $panel['a'];
$aaaa = $panel['aaaa']; $aaaa = $panel['aaaa'];
} }
} }
$this->domainController->createZoneFile(name: $name, a: $a, aaaa: $aaaa); $domain = new Domain(name: $name, id: $panelID, panelID: $a, a: $aaaa);
$result = $this->domainRepository->insert(domain: $domain);
echo "Domain $name has been created with id $result" . PHP_EOL;
$this->domainController->createZoneFile(domain: $domain);
exit(0); exit(0);
} }
} catch (DependencyException|NotFoundException $e) { } catch (DependencyException|NotFoundException $e) {
@ -963,19 +1045,21 @@ class BindAPI
echo "Domain with ID : $id doesn't exist." . PHP_EOL; echo "Domain with ID : $id doesn't exist." . PHP_EOL;
exit(1); exit(1);
} }
if ($this->domainRepository->update(id: $id, name: $name, panelID: $panelID, a: $a, aaaa: $aaaa) !== false) { if (!empty($panelID)) {
$panel = $this->panelController->findByID(id: $panelID);
$a = $panel['a'];
$aaaa = $panel['aaaa'];
}
$newDomain = new Domain(name: $name, id: $panelID, panelID: $a, a: $aaaa);
if ($this->domainRepository->update(domain: $newDomain) !== false) {
echo 'Domain server has been updated' . PHP_EOL; echo 'Domain server has been updated' . PHP_EOL;
if (!empty($panelID)) { $this->domainController->createZoneFile(domain: $domain);
$panel = $this->panelController->findByID(id: $panelID);
$a = $panel['a'];
$aaaa = $panel['aaaa'];
}
$this->domainController->createZoneFile(name: $domain['name'], a: $a, aaaa: $aaaa);
} else { } else {
echo 'Error while updating domain server.' . PHP_EOL; echo 'Error while updating domain server.' . PHP_EOL;
} }
} }
/** /**
* @throws \DI\DependencyException * @throws \DI\DependencyException
* @throws \DI\NotFoundException * @throws \DI\NotFoundException
@ -992,20 +1076,22 @@ class BindAPI
echo "Domain with ID $id not found." . PHP_EOL; echo "Domain with ID $id not found." . PHP_EOL;
exit(1); exit(1);
} }
if (!$this->domainRepository->findByID(id: $id)) { if (!$domain = $this->domainRepository->findByID(id: $id)) {
echo "There is no domain with ID $id." . PHP_EOL; echo "There is no domain with ID $id." . PHP_EOL;
exit(1); exit(1);
} }
$this->domainController->deleteZone(id: $id); $this->domainController->deleteZone(domain: $domain);
echo "The domain with ID $id has been deleted." . PHP_EOL; echo "The domain with ID $id has been deleted." . PHP_EOL;
} }
/** /**
* @param string $subcommand * @param string $subcommand
* *
* @return void * @return void
*/ */
public function handleNameservers(string $subcommand): void public
function handleNameservers(string $subcommand): void
{ {
try { try {
match ($subcommand) { match ($subcommand) {
@ -1022,6 +1108,7 @@ class BindAPI
} }
} }
/** /**
* @return void * @return void
*/ */
@ -1056,7 +1143,8 @@ class BindAPI
echo "Nameserver: $name already exists." . PHP_EOL; echo "Nameserver: $name already exists." . PHP_EOL;
exit(1); exit(1);
} else { } else {
$result = $this->nameserverRepository->insert(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey); $nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey);
$result = $this->nameserverRepository->insert(nameserver: $nameserver);
echo "Nameserver $name has been created with id $result" . PHP_EOL; echo "Nameserver $name has been created with id $result" . PHP_EOL;
exit(0); exit(0);
} }
@ -1066,6 +1154,7 @@ class BindAPI
} }
} }
/** /**
* @return void * @return void
*/ */
@ -1104,6 +1193,7 @@ class BindAPI
exit(0); exit(0);
} }
/** /**
* @throws \DI\DependencyException * @throws \DI\DependencyException
* @throws \DI\NotFoundException * @throws \DI\NotFoundException
@ -1133,6 +1223,7 @@ class BindAPI
} }
} }
/** /**
* @throws \DI\DependencyException * @throws \DI\DependencyException
* @throws \DI\NotFoundException * @throws \DI\NotFoundException

View File

@ -2,8 +2,10 @@
namespace App\Controller; namespace App\Controller;
use App\Entity\Domain;
use App\Repository\DomainRepository; use App\Repository\DomainRepository;
use App\Repository\NameserverRepository; use App\Repository\NameserverRepository;
use Monolog\Logger;
error_reporting(error_level: E_ALL); error_reporting(error_level: E_ALL);
@ -19,8 +21,13 @@ class DomainController
private string $namedConfLocalFile; private string $namedConfLocalFile;
private string $zoneCachePath; private string $zoneCachePath;
public function __construct(private NameserverRepository $nameserverRepository, private CheckController $checkController, private DomainRepository $domainRepository) public function __construct(private NameserverRepository $nameserverRepository, private ApiController $checkController, private DomainRepository $domainRepository, private array $config, private Logger $log)
{ {
if ($this->config['debug']) {
$this->log->debug(message: "__construct()");
}
$this->localZoneFile = '/etc/bind/local.zones'; $this->localZoneFile = '/etc/bind/local.zones';
$this->localZonesDir = '/etc/bind/zones/'; $this->localZonesDir = '/etc/bind/zones/';
$this->namedConfLocalFile = '/etc/bind/named.conf.local'; $this->namedConfLocalFile = '/etc/bind/named.conf.local';
@ -53,6 +60,10 @@ class DomainController
function createIncludeFile() function createIncludeFile()
{ {
if ($this->config['debug']) {
$this->log->debug(message: "createIncludeFile()");
}
$domains = $this->domainRepository->findAll(); $domains = $this->domainRepository->findAll();
$oFile = fopen(filename: $this->localZoneFile, mode: 'w'); $oFile = fopen(filename: $this->localZoneFile, mode: 'w');
@ -63,69 +74,55 @@ class DomainController
} }
function delete(int $id) function deleteOnNameservers(Domain $domain)
{ {
if ($this->config['debug']) {
if ($domain = $this->domainRepository->findByID(id: $id)) { $this->log->debug(message: "deleteOnNameserver()");
$this->domainRepository->delete(id: $id);
$zoneFile = $this->localZonesDir . $domain['name'];
print($zoneFile . PHP_EOL);
if (file_exists(filename: $this->localZonesDir . $domain['name'])) {
print("file exists");
unlink(filename: $zoneFile);
$this->createIncludeFile();
}
} }
$this->deleteOnNameservers(id: $id);
}
function deleteOnNameservers(int $id)
{
$nameservers = $this->nameserverRepository->findAll(); $nameservers = $this->nameserverRepository->findAll();
foreach ($nameservers as $nameserver) { foreach ($nameservers as $nameserver) {
echo($nameserver['name']);
$body = [ $body = [
'id' => $id 'name' => $domain->getName()
]; ];
if (!empty($nameserver['aaaa'])) { if (!empty($nameserver->getAaaa())) {
$this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver['name'], versionIP: 6, apiKey: $nameserver['apikey'], command: 'delete', serverType: 'nameserver', body: $body); $this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver->getName(), versionIP: 6, apiKey: $nameserver->getApikey(), command: 'delete', serverType: 'nameserver', body: $body);
} else { } else {
$this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver['name'], versionIP: 4, apiKey: $nameserver['apikey'], command: 'delete', serverType: 'nameserver', body: $body); $this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver->getName(), versionIP: 4, apiKey: $nameserver->getApikey(), command: 'delete', serverType: 'nameserver', body: $body);
} }
} }
} }
/** /**
* @param int $id * @param \App\Entity\Domain $domain
* *
* @return void * @return void
*/ */
function deleteZone(int $id) function deleteZone(Domain $domain)
{ {
if ($this->config['debug']) {
if ($domain = $this->domainRepository->findByID(id: $id)) { $this->log->debug(message: "deleteZone()");
$zoneFile = $this->localZonesDir . $domain['name'];
print($zoneFile . PHP_EOL);
if (file_exists(filename: $this->localZonesDir . $domain['name'])) {
print("file exists");
unlink(filename: $zoneFile);
$this->createIncludeFile();
}
} }
$this->deleteOnNameservers(id: $id); $zoneFile = $this->localZonesDir . $domain->getName();
$this->domainRepository->delete(id: $id); if (file_exists(filename: "$zoneFile")) {
unlink(filename: $zoneFile);
}
$this->createIncludeFile();
$this->deleteOnNameservers(domain: $domain);
} }
/** /**
* @return void * @return void
*/ */
function checkPermissions(): void function checkPermissions(): void
{ {
if ($this->config['debug']) {
$this->log->debug(message: "checkPermissions()");
}
echo 'Checking permission:' . PHP_EOL . PHP_EOL; echo 'Checking permission:' . PHP_EOL . PHP_EOL;
$uid = posix_geteuid(); $uid = posix_geteuid();
print("UID:\t$uid" . PHP_EOL); print("UID:\t$uid" . PHP_EOL);
@ -173,6 +170,7 @@ class DomainController
*/ */
function checkDomains(): array|bool function checkDomains(): array|bool
{ {
return true; return true;
/* /*
$domains = $this->findAll(); $domains = $this->findAll();
@ -213,28 +211,33 @@ class DomainController
/** /**
* @param mixed $name * @param \App\Entity\Domain $domain
* @param mixed $a
* @param mixed $aaaa
* *
* @return void * @return void
*/ */
public function createZoneFile(string $name, string $a, string $aaaa): void public function createZoneFile(Domain $domain): void
{ {
if ($zonefile = fopen(filename: $this->localZonesDir . $name, mode: 'w')) { if ($this->config['debug']) {
fputs(stream: $zonefile, data: "zone \"$name\" IN {" . PHP_EOL); $domainName = $domain->getName();
$this->log->debug(message: "createZoneFile($domainName)");
}
if ($zonefile = fopen(filename: $this->localZonesDir . $domain->getName(), mode: 'w')) {
fputs(stream: $zonefile, data: 'zone \"' . $domain->getA() . '"' . ' IN {' . PHP_EOL);
fputs(stream: $zonefile, data: "\ttype slave;" . PHP_EOL); fputs(stream: $zonefile, data: "\ttype slave;" . PHP_EOL);
fputs(stream: $zonefile, data: "\tfile \"" . $this->zoneCachePath . $name . '.db";' . PHP_EOL); fputs(stream: $zonefile, data: "\tfile \"" . $this->zoneCachePath . $domain->getName() . '.db";' . PHP_EOL);
fputs(stream: $zonefile, data: "\tmasters {" . PHP_EOL); fputs(stream: $zonefile, data: "\tmasters {" . PHP_EOL);
if (!empty($a)) { if (!empty($a)) {
fputs(stream: $zonefile, data: "\t\t$a;" . PHP_EOL); fputs(stream: $zonefile, data: "\t\t" . $domain->getA() . ';' . PHP_EOL);
} }
if (!empty($aaaa)) { if (!empty($aaaa)) {
fputs(stream: $zonefile, data: "\t\t$aaaa;" . PHP_EOL); fputs(stream: $zonefile, data: "\t\t" . $domain->getAaaa() . ';' . PHP_EOL);
} }
fputs(stream: $zonefile, data: "\t};" . PHP_EOL); fputs(stream: $zonefile, data: "\t};" . PHP_EOL);
fputs(stream: $zonefile, data: "};" . PHP_EOL); fputs(stream: $zonefile, data: "};" . PHP_EOL);
} }
$this->createIncludeFile(); $this->createIncludeFile();
// TODO add on nameservers
} }
} }

View File

@ -4,12 +4,11 @@ namespace App\Controller;
error_reporting(error_level: E_ALL); error_reporting(error_level: E_ALL);
use App\Entity\Domain;
use App\Repository\ApikeyRepository; use App\Repository\ApikeyRepository;
use App\Repository\DomainRepository; use App\Repository\DomainRepository;
use DI\Container; use DI\Container;
use DI\ContainerBuilder; use DI\ContainerBuilder;
use OpenApi\Annotations\ServerVariable;
use OpenApi\Annotations\Tag;
use OpenApi\Generator; use OpenApi\Generator;
use UnhandledMatchError; use UnhandledMatchError;
use function DI\autowire; use function DI\autowire;
@ -18,7 +17,32 @@ use OpenApi\Attributes as OAT;
/** /**
* *
*/ */
#[OAT\Info(version: '0.0.1', title: 'bindAPI' )] #[OAT\Info(version: '0.0.1', title: 'bindAPI')]
#[OAT\Server(
url: "{schema}://{hostname}/api",
description: "The bindAPI URL.",
variables: [
new OAT\ServerVariable(
serverVariable: "schema",
default: "https",
enum: ["https", "http"]
),
new OAT\ServerVariable(
serverVariable: "hostname",
default: "ns2.24unix.net",
)
]
)]
#[OAT\Tag(
name: "Server"
)]
#[OAT\SecurityScheme(
securityScheme: "Authorization",
type: "apiKey",
description: "description",
name: "X-API-Key",
in: "header"
)]
class RequestController class RequestController
{ {
//private DatabaseConnection $databaseConnection; //private DatabaseConnection $databaseConnection;
@ -51,12 +75,56 @@ class RequestController
$this->apikeyRepository = $this->container->get(name: ApikeyRepository::class); $this->apikeyRepository = $this->container->get(name: ApikeyRepository::class);
} }
/** /**
* @OA\Server( * @return void
* url = "https://ns2.24unix.net/api" */
* ) #[OAT\Get(
path: '/domains',
operationId: 'getAllDomains',
description: 'Returns a list of all domains on this server.',
summary: 'Listing all domains.',
// security: [
// 'Authorization' => [
//
// "read:api"
// ]
// ],
servers: [],
tags: ['Domains'],
responses: [
new OAT\Response(
response: 200,
description: 'OK'
),
new OAT\Response(
response: 401,
description: 'API key is missing or invalid.'
),
new OAT\Response(
response: 404,
description: 'Domain not found.'
)]
)]
public function handleAllDomainsGetRequest(): void
{
$domains = $this->domainRepository->findAll();
$resultDomain = [];
foreach ($domains as $singleDomain) {
$domain = [
'id' => $singleDomain->getId(),
'name' => $singleDomain->getName(),
'panel_id' => $singleDomain->getPanelId(),
'a' => $singleDomain->getA(),
'aaaa' => $singleDomain->getAaaa()
];
$resultDomain[] = $domain;
}
$this->result = $resultDomain;
}
/**
* @OA\Tag(name = "Server") * @OA\Tag(name = "Server")
* @OA\Get( * @OA\Get(
* path = "/ping", * path = "/ping",
@ -70,61 +138,7 @@ class RequestController
* } * }
* ) * )
* *
* @OA\SecurityScheme (name="bindAPISecurity",
* type="apiKey",
* description="description",
* name="X-API-Key",
* in="header",
* securityScheme="Authorization"
*
* )
* @SwaggerDefinition(
* securityDefinition = @SecurityDefinition(
* apiKeyAuthDefinitions = {
* @ApiKeyAuthDefinition(
* key = "X-API-Key", in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, name = "X-API-KEY"
* )
* }
* )
* )
* @OA\Tag(name = "Domains") * @OA\Tag(name = "Domains")
* @OA\Get(
* path="/domains",
* summary="Listing all domains.",
* description="desc",
* tags={"Domains"},
* @OA\Response(response="200", description="OK"),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* @OA\Response(response="404", description="Domain not found."),
* security={
* {"Authorization":{"read":"write"}}
* }
* )
* @OA\Post(
* path="/domains",
* summary="Create a domain.",
* description="Creates a new domain.",
* tags={"Domains"},
* @OA\Response(response="201", description="Created"),
* @OA\Response(response = "400", description = "Invalid request body."),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* @OA\Response(response="404", description="Domain not found."),
* security={
* {"Authorization":{"read":"write"}}
* }
* )
* @OA\Get(
* path="/domains/{name}",
* summary="Returns a single domain.",
* description="Returns information of a single domain specified by its domain name.",
* tags={"Domains"},
* @OA\Response(response="200", description="OK"),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* @OA\Response(response="404", description="Domain not found."),
* security={
* {"Authorization":{"read":"write"}}
* }
* )
* @OA\Put( * @OA\Put(
* path="/domains/{name}", * path="/domains/{name}",
* summary="Updates a domain.", * summary="Updates a domain.",
@ -149,9 +163,35 @@ class RequestController
* {"Authorization":{"read":"write"}} * {"Authorization":{"read":"write"}}
* } * }
* ) * )
*
* @return void * @return void
*/ */
#[OAT\Get(
path: '/domains/{name}',
operationId: 'getSingleDomain',
description: 'Returns information of a single domain specified by its domain name.',
summary: 'Returns a single domain.',
security: [
],
tags: ['Domains'],
parameters: [
new OAT\Parameter(name: 'name', in: 'path', required: true, schema: new OAT\Schema(type: 'string')),
],
responses: [
new OAT\Response(
response: 200,
description: 'OK'
),
new OAT\Response(
response: 401,
description: 'API key is missing or invalid.'
),
new OAT\Response(
response: 404,
description: 'Domain not found.'
)]
)]
public function processRequest() public function processRequest()
{ {
$command = $this->uri[2]; $command = $this->uri[2];
@ -253,19 +293,7 @@ class RequestController
public function handleDomainGetRequest(): void public function handleDomainGetRequest(): void
{ {
if (empty($this->uri[3])) { if (empty($this->uri[3])) {
$domains = $this->domainRepository->findAll(); $this->handleAllDomainsGetRequest();
$resultDomain = [];
foreach ($domains as $singleDomain) {
$domain = [
'id' => $singleDomain->getId(),
'name' => $singleDomain->getName(),
'panel_id' => $singleDomain->getPanelId(),
'a' => $singleDomain->getA(),
'aaaa' => $singleDomain->getAaaa()
];
$resultDomain[] = $domain;
}
$this->result = $resultDomain;
} else { } else {
if ($result = $this->domainRepository->findByName(name: $this->uri[3])) { if ($result = $this->domainRepository->findByName(name: $this->uri[3])) {
$domain = [ $domain = [
@ -288,8 +316,7 @@ class RequestController
/** /**
* @return void * @return void
*/ */
public public function handleDomainPostRequest(): void
function handleDomainPostRequest(): void
{ {
$name = $_POST['name'] ?? ''; $name = $_POST['name'] ?? '';
$panelID = intval(value: $_POST['panel_id'] ?? 0); $panelID = intval(value: $_POST['panel_id'] ?? 0);
@ -310,7 +337,8 @@ class RequestController
$this->status = "400 Bad request"; $this->status = "400 Bad request";
$this->message = "Domain: $name already exists."; $this->message = "Domain: $name already exists.";
} else { } else {
$result = $this->domainRepository->insert(name: $name, panelID: $panelID, a: $a, aaaa: $aaaa); $domain = new Domain(name: $name, panelID: $panelID, a: $a, aaaa: $aaaa);
$result = $this->domainRepository->insert(domain: $domain);
$this->status = "201 Created"; $this->status = "201 Created";
$this->message = $result; $this->message = $result;
} }
@ -334,7 +362,7 @@ class RequestController
$put[$key] = $value; $put[$key] = $value;
} }
$id = $put['id'] ?? 0; $id = $put['id'] ?? 0;
$name = $put['name'] ?? ""; $name = $put['name'] ?? '';
$panelID = $put['panel_id'] ?? ""; $panelID = $put['panel_id'] ?? "";
$a = $put['a'] ?? ""; $a = $put['a'] ?? "";
$aaaa = $put['aaaa'] ?? ""; $aaaa = $put['aaaa'] ?? "";
@ -356,7 +384,8 @@ class RequestController
$this->status = "400 Bad Request"; $this->status = "400 Bad Request";
$this->message = "At least one IP address is required."; $this->message = "At least one IP address is required.";
} else { } else {
$this->domainRepository->update(id: $id, name: $panelID, panelID: $name, a: $a, aaaa: $aaaa); $domain = new Domain(name: $panelID, id: $id, panelID: $name, a: $a, aaaa: $aaaa);
$this->domainRepository->update(domain: $domain);
$this->header = "201 Updated"; $this->header = "201 Updated";
$this->status = "201 Updated"; $this->status = "201 Updated";
$this->message = "201 Updated"; $this->message = "201 Updated";
@ -389,12 +418,13 @@ class RequestController
$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 (!$this->domainRepository->findByID(id: $id)) {
if (!$domain = $this->domainRepository->findByID(id: $id)) {
$this->header = "400 Bad Request"; $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(id: $id); $this->domainRepository->delete(domain: $domain);
$this->header = "204 No content."; $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.";

View File

@ -2,8 +2,6 @@
namespace App\Entity; namespace App\Entity;
use OpenApi\Attributes as OAT;
/** /**
* *
*/ */

View File

@ -4,6 +4,7 @@ namespace App\Repository;
use App\Controller\DatabaseConnection; use App\Controller\DatabaseConnection;
use App\Entity\Domain; use App\Entity\Domain;
use Monolog\Logger;
use PDO; use PDO;
use PDOException; use PDOException;
@ -12,7 +13,7 @@ use PDOException;
*/ */
class DomainRepository class DomainRepository
{ {
public function __construct(private DatabaseConnection $databaseConnection) public function __construct(private DatabaseConnection $databaseConnection, private array $config, private Logger $log)
{} {}
@ -58,6 +59,7 @@ class DomainRepository
$statement->bindParam(param: ':id', var: $id); $statement->bindParam(param: ':id', var: $id);
$statement->execute(); $statement->execute();
if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) { if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
return new Domain(name: $result['name'], panelID: $result['panel_id'], a: $result['a'], aaaa: $result['aaaa']); return new Domain(name: $result['name'], panelID: $result['panel_id'], a: $result['a'], aaaa: $result['aaaa']);
} else { } else {
return false; return false;
@ -85,7 +87,7 @@ class DomainRepository
$statement->bindParam(param: ':name', var: $name); $statement->bindParam(param: ':name', var: $name);
$statement->execute(); $statement->execute();
if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) { if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
return new Domain(name: $result['name'], panelID: $result['panel_id'], a: $result['a'], aaaa: $result['aaaa']); return new Domain(name: $result['name'], id: $result['id'], panelID: $result['panel_id'], a: $result['a'], aaaa: $result['aaaa']);
} else { } else {
return false; return false;
@ -97,23 +99,28 @@ class DomainRepository
} }
/** /**
* @param String $name * @param \App\Entity\Domain $domain
* @param int $panelID
* @param String $a
* @param String $aaaa
* *
* @return string|false * @return string|false
*/ */
public function insert(string $name, int $panelID, string $a, string $aaaa): bool|string public function insert(Domain $domain): bool|string
{ {
print("here"); if ($this->config['debug']) {
$domainName = $domain->getName();
$this->log->debug(message: "insert($domainName)");
}
$sql = " $sql = "
INSERT INTO " . DatabaseConnection::TABLE_DOMAINS . " (name, panel_id, a, aaaa) INSERT INTO " . DatabaseConnection::TABLE_DOMAINS . " (name, panel_id, a, aaaa)
VALUES (:name, :panel_id, :a, :aaaa)"; VALUES (:name, :panel_id, :a, :aaaa)";
try { try {
$name = $domain->getName();
$panelID = $domain->getPanelID();
$a = $domain->getA();
$aaaa = $domain->getAaaa();
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql); $statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->bindParam(param: ':name', var: $name); $statement->bindParam(param: ':name', var: $name);
$statement->bindParam(param: ':panel_id', var: $panelID); $statement->bindParam(param: ':panel_id', var: $panelID);
@ -129,17 +136,18 @@ class DomainRepository
/** /**
* @param Int $id * @param \App\Entity\Domain $domain
* @param String $name
* @param int $panelID
* @param String $a
* @param String $aaaa
* *
* @return false|int * @return false|int
*/ */
public function update(int $id, string $name, int $panelID, string $a, string $aaaa): bool|int public function update(Domain $domain): bool|int
{ {
$current = $this->findByID(id: $id); if ($this->config['debug']) {
$domainName = $domain->getName();
$this->log->debug(message: "update($domainName)");
}
$current = $this->findByID(id: $domain->getId());
/* doesn't work /* doesn't work
$statement = " $statement = "
@ -151,10 +159,10 @@ class DomainRepository
aaaa=COALESCE(:aaaa, aaaa)"; aaaa=COALESCE(:aaaa, aaaa)";
*/ */
if (empty($name)) { if (empty($domain->getName())) {
$name = $current['name']; $name = $current['name'];
} }
if (empty($panelID)) { if (empty($domain->getPanelID())) {
$panelID = $current['panel_id']; $panelID = $current['panel_id'];
} }
$panelID = intval(value: $panelID); $panelID = intval(value: $panelID);
@ -191,18 +199,24 @@ class DomainRepository
/** /**
* @param $id * @param \App\Entity\Domain $domain
* *
* @return int * @return int
*/ */
public function delete($id): int public function delete(Domain $domain): int
{ {
if ($this->config['debug']) {
$domainName = $domain->getName();
$this->log->debug(message: "delete($domainName)");
}
$sql = " $sql = "
DELETE FROM " . DatabaseConnection::TABLE_DOMAINS . " DELETE FROM " . DatabaseConnection::TABLE_DOMAINS . "
WHERE id = :id"; WHERE id = :id";
try { try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql); $statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$id = $domain->getId();
$statement->bindParam(param: 'id', var: $id); $statement->bindParam(param: 'id', var: $id);
$statement->execute(); $statement->execute();

View File

@ -13,7 +13,8 @@ use PDOException;
class NameserverRepository class NameserverRepository
{ {
public function __construct(private DatabaseConnection $databaseConnection) public function __construct(private DatabaseConnection $databaseConnection)
{} {
}
/** /**
@ -93,20 +94,21 @@ class NameserverRepository
/** /**
* @param String $name * @param \App\Entity\Nameserver $nameserver
* @param String $a
* @param String $aaaa
* @param String $apikey
* *
* @return string|false * @return string|false
*/ */
public function insert(string $name, string $a, string $aaaa, String $apikey): bool|string public function insert(Nameserver $nameserver): bool|string
{ {
$sql = " $sql = "
INSERT INTO " . DatabaseConnection::TABLE_NAMESERVERS . " (name, a, aaaa, apikey) INSERT INTO " . DatabaseConnection::TABLE_NAMESERVERS . " (name, a, aaaa, apikey)
VALUES (:name, :a, :aaaa, :apikey)"; VALUES (:name, :a, :aaaa, :apikey)";
try { try {
$name = $nameserver->getName();
$a = $nameserver->getA();
$aaaa = $nameserver->getAaaa();
$apikey = $nameserver->getApikey();
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql); $statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->bindParam(param: ':name', var: $name); $statement->bindParam(param: ':name', var: $name);
$statement->bindParam(param: ':a', var: $a); $statement->bindParam(param: ':a', var: $a);
@ -130,7 +132,7 @@ class NameserverRepository
* *
* @return false|int * @return false|int
*/ */
public function update(int $id, string $name, string $a, string $aaaa, String $apikey): bool|int public function update(int $id, string $name, string $a, string $aaaa, string $apikey): bool|int
{ {
$current = $this->findByID(id: $id); $current = $this->findByID(id: $id);
@ -210,7 +212,7 @@ class NameserverRepository
* *
* @return int * @return int
*/ */
public function getLongestEntry(String $field): int public function getLongestEntry(string $field): int
{ {
$sql = " $sql = "
SELECT MAX(LENGTH(" . $field . ")) as length FROM " . DatabaseConnection::TABLE_NAMESERVERS; SELECT MAX(LENGTH(" . $field . ")) as length FROM " . DatabaseConnection::TABLE_NAMESERVERS;
@ -218,7 +220,7 @@ class NameserverRepository
try { try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql); $statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->execute(); $statement->execute();
$result = $statement->fetch(); $result = $statement->fetch();
return $result['length']; return $result['length'];
} catch (PDOException $e) { } catch (PDOException $e) {
exit($e->getMessage()); exit($e->getMessage());

View File

@ -26,7 +26,7 @@ class DomainRepositoryTest extends TestCase
private string $localZonesDir; private string $localZonesDir;
private string $namedConfLocalFile; private string $namedConfLocalFile;
private $log; private Logger $log;
/** /**
* @param int|string $dataName * @param int|string $dataName
@ -38,7 +38,7 @@ class DomainRepositoryTest extends TestCase
{ {
parent::__construct(name: $name, data: $data, dataName: $dataName); parent::__construct(name: $name, data: $data, dataName: $dataName);
$dateFormat = "Y:m:d H:i:s"; $dateFormat = "Y-m-d H:i:s";
$output = "%datetime% %channel%.%level_name% %message%\n"; // %context% %extra% $output = "%datetime% %channel%.%level_name% %message%\n"; // %context% %extra%
$formatter = new LineFormatter(format: $output, dateFormat: $dateFormat); $formatter = new LineFormatter(format: $output, dateFormat: $dateFormat);
@ -61,6 +61,13 @@ class DomainRepositoryTest extends TestCase
$containerBuilder = new ContainerBuilder(); $containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([ $containerBuilder->addDefinitions([
DatabaseConnection::class => autowire()->constructorParameter(parameter: 'config', value: $config), DatabaseConnection::class => autowire()->constructorParameter(parameter: 'config', value: $config),
DomainController::class => autowire()
->constructorParameter(parameter: 'config', value: $config)
->constructorParameter(parameter: 'log', value: $this->log),
DomainRepository::class => autowire()
->constructorParameter(parameter: 'config', value: $config)
->constructorParameter(parameter: 'log', value: $this->log),
]); ]);
$this->container = $containerBuilder->build(); $this->container = $containerBuilder->build();
@ -89,7 +96,9 @@ class DomainRepositoryTest extends TestCase
$this->domainRepository->insert(domain: $domain); $this->domainRepository->insert(domain: $domain);
$this->domainController->createZoneFile(domain: $domain); $this->domainController->createZoneFile(domain: $domain);
// now get the persisted domain with id
$domainTest = $this->domainRepository->findByName(name: 'inserttest.org'); $domainTest = $this->domainRepository->findByName(name: 'inserttest.org');
$this->assertIsNotBool(actual: $domainTest); $this->assertIsNotBool(actual: $domainTest);
$this->assertEquals(expected: 'inserttest.org', actual: $domainTest->getName()); $this->assertEquals(expected: 'inserttest.org', actual: $domainTest->getName());
@ -111,7 +120,7 @@ class DomainRepositoryTest extends TestCase
// clean up // clean up
$this->domainRepository->delete(id: $domainTest->getId()); $this->domainRepository->delete(domain: $domainTest);
} }
@ -132,7 +141,7 @@ class DomainRepositoryTest extends TestCase
// domain is valid and created // domain is valid and created
// now delete and check for cleanup // now delete and check for cleanup
$this->domainRepository->delete(id: $domainTest->getId()); $this->domainRepository->delete(domain: $domainTest);
$this->domainController->deleteZone(domain: $domainTest); $this->domainController->deleteZone(domain: $domainTest);