Skip to content

Commit

Permalink
feat: adds the possibility to use an api key
Browse files Browse the repository at this point in the history
  • Loading branch information
ascky-thorben committed Dec 9, 2023
1 parent 5d86ef6 commit 011e7a1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/Rest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public static function handleRoutes(): void

$route->setParams($matches);
$route->validateRequestMethod();
$route->validateApiKey();
$route->validatePermission();
$route->validateParams();
$route->executeCallback();
Expand Down
33 changes: 33 additions & 0 deletions lib/RestRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -42,6 +45,7 @@ public function __construct(array $args)
$this->setMethods();
$this->setCallback();
$this->setValidations();
$this->setApiKey();
$this->setPermission();
}

Expand Down Expand Up @@ -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.
*
Expand Down

0 comments on commit 011e7a1

Please sign in to comment.