39 lines
818 B
PHP
39 lines
818 B
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace Web2Print\Middleware;
|
||
|
|
|
||
|
|
class AuthMiddleware
|
||
|
|
{
|
||
|
|
private array $config;
|
||
|
|
|
||
|
|
public function __construct(array $config)
|
||
|
|
{
|
||
|
|
$this->config = $config;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function authenticate(): bool
|
||
|
|
{
|
||
|
|
$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
|
||
|
|
|
||
|
|
if (empty($apiKey)) {
|
||
|
|
$this->sendError(401, 'API key missing');
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!in_array($apiKey, $this->config['api_keys'], true)) {
|
||
|
|
$this->sendError(403, 'Invalid API key');
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
private function sendError(int $code, string $message): void
|
||
|
|
{
|
||
|
|
http_response_code($code);
|
||
|
|
header('Content-Type: application/json');
|
||
|
|
echo json_encode(['error' => $message]);
|
||
|
|
exit;
|
||
|
|
}
|
||
|
|
}
|