71 lines
2.1 KiB
PHP
71 lines
2.1 KiB
PHP
<?php
|
|
namespace ProVM\Common\Middleware;
|
|
|
|
use Psr\Http\Message\ResponseFactoryInterface;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
class Auth
|
|
{
|
|
public function __construct(ResponseFactoryInterface $factory, LoggerInterface $logger, string $api_key)
|
|
{
|
|
$this->setResponseFactory($factory);
|
|
$this->setLogger($logger);
|
|
$this->setAPIKey($api_key);
|
|
}
|
|
|
|
protected ResponseFactoryInterface $factory;
|
|
protected LoggerInterface $logger;
|
|
protected string $api_key;
|
|
|
|
public function getResponseFactory(): ResponseFactoryInterface
|
|
{
|
|
return $this->factory;
|
|
}
|
|
public function getLogger(): LoggerInterface
|
|
{
|
|
return $this->logger;
|
|
}
|
|
public function getAPIKey(): string
|
|
{
|
|
return $this->api_key;
|
|
}
|
|
|
|
public function setResponseFactory(ResponseFactoryInterface $factory): Auth
|
|
{
|
|
$this->factory = $factory;
|
|
return $this;
|
|
}
|
|
public function setLogger(LoggerInterface $logger): Auth
|
|
{
|
|
$this->logger = $logger;
|
|
return $this;
|
|
}
|
|
public function setAPIKey(string $key): Auth
|
|
{
|
|
$this->api_key = $key;
|
|
return $this;
|
|
}
|
|
|
|
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
|
{
|
|
if ($request->getMethod() === 'OPTIONS') {
|
|
return $handler->handle($request);
|
|
}
|
|
$auths = $request->getHeader('Authorization');
|
|
foreach ($auths as $auth) {
|
|
if (str_contains($auth, 'Bearer')) {
|
|
$key = str_replace('Bearer ', '', $auth);
|
|
if (sha1($this->getAPIKey()) === $key) {
|
|
return $handler->handle($request);
|
|
}
|
|
}
|
|
}
|
|
$response = $this->getResponseFactory()->createResponse(401);
|
|
$response->getBody()->write(\Safe\json_encode(['error' => 401, 'message' => 'Incorrect token']));
|
|
return $response
|
|
->withHeader('Content-Type', 'application/json');
|
|
}
|
|
} |