allow api interaction via kind-of-RESTful style via api.php?/module/command/

Signed-off-by: Michael Kaufmann <d00p@froxlor.org>
This commit is contained in:
Michael Kaufmann 2022-04-17 20:59:25 +02:00
parent d1dda00a1c
commit 58c646f59e
No known key found for this signature in database
GPG Key ID: 08A83830520FCECB
2 changed files with 68 additions and 45 deletions

View File

@ -23,7 +23,7 @@ require __DIR__ . '/lib/tables.inc.php';
// Return response
try {
echo (new Api)->handle(@file_get_contents('php://input'));
echo (new Api)->formatMiddleware(@file_get_contents('php://input'))->handle();
} catch (Exception $e) {
echo \Froxlor\Api\Response::jsonErrorResponse($e->getMessage(), $e->getCode());
}

View File

@ -1,4 +1,5 @@
<?php
namespace Froxlor\Api;
use Exception;
@ -23,6 +24,8 @@ class Api
{
protected array $headers;
protected $request = null;
/**
* Api constructor.
*
@ -42,14 +45,34 @@ class Api
}
}
/**
* @param mixed $request
*
* @return Api
*/
public function formatMiddleware($request): Api
{
// check auf RESTful api call
$this->request = $request;
$uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_QUERY);
// map /module/command to internal request array if match
if (!empty($uri) && preg_match("/^\/([a-z]+)\/([a-z]+)\/?/", $uri, $matches)) {
$request = [];
$request['command'] = ucfirst($matches[1]) . '.' . $matches[2];
$request['params'] = !empty($this->request) ? json_decode($this->request, true) : null;
$this->request = json_encode($request);
}
return $this;
}
/**
* Handle incoming api request to our backend.
*
* @param mixed $request
* @throws Exception
*/
public function handle($request)
public function handle()
{
$request = $this->request;
// validate content
$request = \Froxlor\Api\FroxlorRPC::validateRequest($request);
$request = (new AntiXSS())->xss_clean(