web-base/Core/API/Swagger.class.php

205 lines
6.3 KiB
PHP
Raw Permalink Normal View History

2022-02-20 16:53:26 +01:00
<?php
2022-11-18 18:06:46 +01:00
namespace Core\API;
2022-02-20 16:53:26 +01:00
2024-04-23 12:14:28 +02:00
use Core\API\Parameter\IntegerType;
use Core\API\Parameter\RegexType;
2022-11-18 18:06:46 +01:00
use Core\API\Parameter\StringType;
use Core\Objects\Context;
2022-02-20 16:53:26 +01:00
class Swagger extends Request {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, []);
2022-02-20 16:53:26 +01:00
$this->csrfTokenRequired = false;
}
2024-04-11 17:51:50 +02:00
protected function getCORS(): array {
return ["*"];
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2022-02-20 16:53:26 +01:00
header("Content-Type: application/x-yaml");
die($this->getDocumentation());
}
private function fetchPermissions(): array {
2023-01-16 21:47:23 +01:00
$req = new \Core\API\Permission\Fetch($this->context);
2022-02-20 16:53:26 +01:00
$this->success = $req->execute();
$permissions = [];
2023-01-16 21:47:23 +01:00
foreach ($req->getResult()["permissions"] as $permission) {
2022-02-20 16:53:26 +01:00
$permissions["/" . strtolower($permission["method"])] = $permission["groups"];
}
return $permissions;
}
private function canView(array $requiredGroups, Request $request): bool {
if (!$request->isPublic()) {
return false;
}
2022-06-20 19:52:31 +02:00
$currentUser = $this->context->getUser();
2023-01-16 21:47:23 +01:00
$isLoggedIn = $currentUser !== null;
if (($request->loginRequired() || !empty($requiredGroups)) && !$isLoggedIn) {
2022-02-20 16:53:26 +01:00
return false;
}
if (!empty($requiredGroups)) {
2022-06-20 19:52:31 +02:00
$userGroups = array_keys($currentUser?->getGroups() ?? []);
return !empty(array_intersect($requiredGroups, $userGroups));
2022-02-20 16:53:26 +01:00
}
return true;
}
2024-04-23 12:14:28 +02:00
private function getBodyName(\ReflectionClass $class): string {
$bodyName = $class->getShortName() . "Body";
$namespace = explode("\\", $class->getNamespaceName());
if (count($namespace) > 2) { // Core\API\XYZ or Site\API\XYZ
$bodyName = $namespace[2] . $bodyName;
}
return $bodyName;
}
2022-02-20 16:53:26 +01:00
private function getDocumentation(): string {
2022-06-20 19:52:31 +02:00
$settings = $this->context->getSettings();
2022-02-20 16:53:26 +01:00
$siteName = $settings->getSiteName();
$domain = parse_url($settings->getBaseUrl(), PHP_URL_HOST);
$protocol = getProtocol();
2022-02-20 16:53:26 +01:00
$permissions = $this->fetchPermissions();
$definitions = [];
$paths = [];
$tags = [];
// TODO: consumes and produces is not always the same, but it's okay for now
2022-02-20 16:53:26 +01:00
foreach (self::getApiEndpoints() as $endpoint => $apiClass) {
$body = null;
$requiredProperties = [];
2023-03-05 15:30:06 +01:00
$endpoint = "/$endpoint";
2022-06-20 19:52:31 +02:00
$apiObject = $apiClass->newInstance($this->context, false);
2022-02-20 16:53:26 +01:00
if (!$this->canView($permissions[strtolower($endpoint)] ?? [], $apiObject)) {
continue;
}
$tag = null;
if ($apiClass->getParentClass()->getName() !== Request::class) {
$parentClass = $apiClass->getParentClass()->getShortName();
if (endsWith($parentClass, "API")) {
$tag = substr($parentClass, 0, strlen($parentClass) - 3);
if (!in_array($tag, $tags)) {
$tags[] = $tag;
}
}
}
2024-04-23 12:14:28 +02:00
$bodyName = $this->getBodyName($apiClass);
2022-02-20 16:53:26 +01:00
$parameters = $apiObject->getDefaultParams();
if (!empty($parameters)) {
$body = [];
foreach ($apiObject->getDefaultParams() as $param) {
$body[$param->name] = [
"type" => $param->getSwaggerTypeName(),
"default" => $param->value
];
if ($param instanceof StringType && $param->maxLength > 0) {
$body[$param->name]["maxLength"] = $param->maxLength;
2024-04-23 12:14:28 +02:00
} else if ($param instanceof IntegerType) {
if ($param->minValue > PHP_INT_MIN) {
$body[$param->name]["minimum"] = $param->minValue;
}
if ($param->maxValue < PHP_INT_MAX) {
$body[$param->name]["maximum"] = $param->maxValue;
}
}
if ($param instanceof RegexType) {
$body[$param->name]["pattern"] = $param->pattern;
2022-02-20 16:53:26 +01:00
}
if ($body[$param->name]["type"] === "string" && ($format = $param->getSwaggerFormat())) {
$body[$param->name]["format"] = $format;
}
if (!$param->optional) {
$requiredProperties[] = $param->name;
}
}
$definitions[$bodyName] = [
"description" => "Body for $endpoint",
"properties" => $body
];
if (!empty($requiredProperties)) {
$definitions[$bodyName]["required"] = $requiredProperties;
}
}
$endPointDefinition = [
"post" => [
"tags" => [$tag ?? "Global"],
2024-04-23 12:14:28 +02:00
"summary" => $apiObject->getDescription(),
2022-02-20 16:53:26 +01:00
"produces" => ["application/json"],
"responses" => [
"200" => ["description" => "OK!"],
"400" => ["description" => "Parameter validation failed"],
2022-02-20 16:53:26 +01:00
"401" => ["description" => "Login or 2FA Authorization is required"],
"403" => ["description" => "CSRF-Token validation failed or insufficient permissions"],
"503" => ["description" => "Function is disabled"],
2022-02-20 16:53:26 +01:00
]
]
];
if ($apiObject->isDisabled()) {
$endPointDefinition["post"]["deprecated"] = true;
}
if ($body) {
$endPointDefinition["post"]["consumes"] = ["application/json", "application/x-www-form-urlencoded"];
2022-02-20 16:53:26 +01:00
$endPointDefinition["post"]["parameters"] = [[
"in" => "body",
"name" => "body",
"required" => !empty($requiredProperties),
2024-04-23 12:14:28 +02:00
"schema" => ["\$ref" => "#/definitions/$bodyName"]
2022-02-20 16:53:26 +01:00
]];
} else if ($apiObject->isMethodAllowed("GET")) {
$endPointDefinition["get"] = $endPointDefinition["post"];
unset($endPointDefinition["post"]);
}
$paths[$endpoint] = $endPointDefinition;
}
$yamlData = [
"swagger" => "2.0",
"info" => [
"description" => "This is the Backend API-Description of $siteName",
"version" => WEBBASE_VERSION,
"title" => $siteName,
"contact" => [ "email" => "webmaster@$domain" ],
],
"host" => $domain,
"basePath" => "/api",
"schemes" => ["$protocol"],
"tags" => $tags,
2022-02-20 16:53:26 +01:00
"paths" => $paths,
"definitions" => $definitions
];
2022-02-20 23:17:17 +01:00
return \yaml_emit($yamlData);
2024-04-23 12:14:28 +02:00
}
public static function getDescription(): string {
return "Returns the API-specification for this site. Endpoints, a user does not have access to, are hidden by default.";
}
2022-02-20 16:53:26 +01:00
2024-04-23 12:14:28 +02:00
public static function getDefaultPermittedGroups(): array {
return [];
2022-02-20 16:53:26 +01:00
}
}