diff --git a/lib/Rest.php b/lib/Rest.php index 07a49fe..d2f5f0d 100644 --- a/lib/Rest.php +++ b/lib/Rest.php @@ -90,6 +90,7 @@ public static function handleRoutes(): void $route->setParams($matches); $route->validateRequestMethod(); + $route->validateApiKey(); $route->validatePermission(); $route->validateParams(); $route->executeCallback(); diff --git a/lib/RestRoute.php b/lib/RestRoute.php index aa7b18b..680ca7b 100644 --- a/lib/RestRoute.php +++ b/lib/RestRoute.php @@ -23,6 +23,9 @@ class RestRoute /** @var array The validations */ protected array $validations; + /** @var string|null The API Key */ + protected string|null $apiKey; + /** @var array The allowed request methods */ private array $allowedMethods = [ 'GET', @@ -42,6 +45,7 @@ public function __construct(array $args) $this->setMethods(); $this->setCallback(); $this->setValidations(); + $this->setApiKey(); $this->setPermission(); } @@ -176,6 +180,35 @@ public function setValidations(): void $this->validations = $this->args['validations']; } + /** + * Sets the api key. + */ + public function setApiKey(): void + { + if (!isset($this->args['api_key']) || empty($this->args['api_key'])) { + $this->apiKey = null; + return; + } + + $this->apiKey = (string) $this->args['api_key']; + } + + /** + * Validates the API key. + * + * @throws rex_exception|JsonException + */ + public function validateApiKey(): void + { + if (null !== $this->apiKey) { + $apiKey = rex::getRequest()->headers->get('API-KEY'); + + if ($apiKey !== $this->apiKey) { + $this->sendError('Invalid API key', rex_response::HTTP_FORBIDDEN); + } + } + } + /** * Validates the permission. *