From f66ab8dae2f3d0418759f81a3a64dc9517a62449 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 14 Apr 2024 15:17:31 +0200 Subject: Adding upstream version 1.10.2. Signed-off-by: Daniel Baumann --- .../Director/Web/Controller/Extension/RestApi.php | 114 +++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 library/Director/Web/Controller/Extension/RestApi.php (limited to 'library/Director/Web/Controller/Extension/RestApi.php') diff --git a/library/Director/Web/Controller/Extension/RestApi.php b/library/Director/Web/Controller/Extension/RestApi.php new file mode 100644 index 0000000..3158f49 --- /dev/null +++ b/library/Director/Web/Controller/Extension/RestApi.php @@ -0,0 +1,114 @@ +isApified; + } else { + return false; + } + } + + /** + * @return bool + */ + protected function sendNotFoundForRestApi() + { + /** @var \Icinga\Web\Request $request */ + $request = $this->getRequest(); + if ($request->isApiRequest()) { + $this->sendJsonError($this->getResponse(), 'Not found', 404); + return true; + } else { + return false; + } + } + + /** + * @return bool + */ + protected function sendNotFoundUnlessRestApi() + { + /** @var \Icinga\Web\Request $request */ + $request = $this->getRequest(); + if ($request->isApiRequest()) { + return false; + } else { + $this->sendJsonError($this->getResponse(), 'Not found', 404); + return true; + } + } + + /** + * @throws AuthenticationException + */ + protected function assertApiPermission() + { + if (! $this->hasPermission('director/api')) { + throw new AuthenticationException('You are not allowed to access this API'); + } + } + + /** + * @throws AuthenticationException + * @throws NotFoundError + */ + protected function checkForRestApiRequest() + { + /** @var \Icinga\Web\Request $request */ + $request = $this->getRequest(); + if ($request->isApiRequest()) { + $this->assertApiPermission(); + if (! $this->isApified()) { + throw new NotFoundError('No such API endpoint found'); + } + } + } + + /** + * @param Response $response + * @param $object + */ + protected function sendJson(Response $response, $object) + { + $response->setHeader('Content-Type', 'application/json', true); + echo json_encode($object, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n"; + } + + /** + * @param Response $response + * @param string $message + * @param int|null $code + */ + protected function sendJsonError(Response $response, $message, $code = null) + { + if ($code !== null) { + try { + $response->setHttpResponseCode((int) $code); + } catch (Zend_Controller_Response_Exception $e) { + throw new InvalidArgumentException($e->getMessage(), 0, $e); + } + } + + $this->sendJson($response, (object) ['error' => $message]); + } + + /** + * @return string + */ + protected function getLastJsonError() + { + return JsonException::getJsonErrorMessage(json_last_error()); + } +} -- cgit v1.2.3