Fixed API

This commit is contained in:
Maximilian Giller 2020-12-30 21:22:18 +01:00
parent ab1514ffc9
commit dd39bb6450
3 changed files with 30 additions and 4 deletions

View file

@ -14,6 +14,11 @@ abstract class ApiBranch {
function execute ($authenticationRequired = true) { function execute ($authenticationRequired = true) {
$params = $this->getParams(); $params = $this->getParams();
$currentType = currentRequestType();
if ($currentType === RequestType::OPTIONS) {
respondStatus(200);
}
if ($authenticationRequired) { if ($authenticationRequired) {
$auth = new Authenticator(); $auth = new Authenticator();
if (!$auth->isAuthenticated($params)) { if (!$auth->isAuthenticated($params)) {
@ -22,16 +27,23 @@ abstract class ApiBranch {
} }
} }
$currentType = currentRequestType(); if ($currentType === RequestType::GET) {
if($currentType === RequestType::GET) {
$this->get($params); $this->get($params);
} else if ($currentType === RequestType::POST) { } else if ($currentType === RequestType::POST) {
$this->post($params); $this->post($params);
} }
if ($currentType === RequestType::GET) {
$this->get($params);
} else if ($currentType === RequestType::POST) {
$this->post($params);
} else {
respondStatus(405);
}
} }
private function getParams() { private function getParams() {
$content = json_decode(file_get_contents('php://input'), true); $content = json_decode(file_get_contents('php://input'), true);
if ($content == NULL) $content = array();
return new ParamCleaner(array_merge($content, $_REQUEST, $_SESSION, $_FILES)); return new ParamCleaner(array_merge($content, $_REQUEST, $_SESSION, $_FILES));
} }
} }

View file

@ -6,6 +6,7 @@ abstract class RequestType extends BasicEnum {
const POST = "POST"; const POST = "POST";
const PUT = "PUT"; const PUT = "PUT";
const DELETE = "DELETE"; const DELETE = "DELETE";
const OPTIONS = "OPTIONS";
} }
function currentRequestType () { function currentRequestType () {

View file

@ -1,16 +1,29 @@
<?php <?php
require_once(__DIR__."/jsonBuilder.inc.php"); require_once(__DIR__."/jsonBuilder.inc.php");
function defaultHeader()
{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: X-PINGOTHER, Content-Type");
header("Access-Control-Max-Age: 86400");
}
function respondJson(JsonBuilder $builder) { function respondJson(JsonBuilder $builder) {
defaultHeader();
header('Content-type: application/json'); header('Content-type: application/json');
echo($builder->getJson()); echo($builder->getJson());
} }
function respondHtml(string $html) { function respondHtml(string $html)
{
defaultHeader();
print($html); print($html);
} }
function respondStatus(int $statusCode, string $message = "") { function respondStatus(int $statusCode, string $message = "")
{
defaultHeader();
http_response_code($statusCode); http_response_code($statusCode);
die($message); die($message);
} }