2023-11-25 00:55:31 -03:00
|
|
|
<?php
|
|
|
|
namespace Incoviba\Middleware;
|
|
|
|
|
|
|
|
use Psr\Http\Message\ResponseFactoryInterface;
|
|
|
|
use Psr\Http\Message\ResponseInterface;
|
|
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
|
|
|
use Incoviba\Exception\MissingAuthorizationHeader;
|
2024-03-20 23:07:49 -03:00
|
|
|
use Incoviba\Service;
|
2023-11-25 00:55:31 -03:00
|
|
|
|
|
|
|
class API
|
|
|
|
{
|
2024-03-20 23:07:49 -03:00
|
|
|
public function __construct(protected ResponseFactoryInterface $responseFactory, protected Service\Login $loginService,
|
|
|
|
protected string $key) {}
|
2023-11-25 00:55:31 -03:00
|
|
|
|
|
|
|
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
$key = $this->getKey($request);
|
|
|
|
} catch (MissingAuthorizationHeader $exception) {
|
|
|
|
return $this->responseFactory->createResponse(401);
|
|
|
|
}
|
2024-03-20 23:07:49 -03:00
|
|
|
if ($this->validate($request, $key)) {
|
2023-11-25 00:55:31 -03:00
|
|
|
return $handler->handle($request);
|
|
|
|
}
|
|
|
|
return $this->responseFactory->createResponse(403);
|
|
|
|
}
|
|
|
|
protected function getKey(ServerRequestInterface $request): string
|
|
|
|
{
|
|
|
|
$auth_headers = $request->getHeader('Authorization');
|
|
|
|
foreach ($auth_headers as $header) {
|
|
|
|
if (str_contains($header, 'Bearer')) {
|
|
|
|
return substr($header, strlen('Bearer '));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
throw new MissingAuthorizationHeader();
|
|
|
|
}
|
2024-03-20 23:07:49 -03:00
|
|
|
protected function validate(ServerRequestInterface $request, $incoming_key): bool
|
2023-11-25 00:55:31 -03:00
|
|
|
{
|
2024-03-20 23:07:49 -03:00
|
|
|
if (str_contains($incoming_key, $this->loginService->getSeparator())) {
|
|
|
|
list($incoming_key, $selector, $token) = explode($this->loginService->getSeparator(), $incoming_key);
|
|
|
|
if (!$this->loginService->isIn()) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!$this->loginService->isIn() and !$this->validPermitted($request)) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-11-25 00:55:31 -03:00
|
|
|
return $incoming_key === md5($this->key);
|
|
|
|
}
|
2024-03-20 23:07:49 -03:00
|
|
|
protected function validPermitted(ServerRequestInterface $request): bool
|
|
|
|
{
|
|
|
|
$uri = $request->getUri();
|
|
|
|
$validPaths = [
|
|
|
|
'/api',
|
|
|
|
'/api/'
|
|
|
|
];
|
|
|
|
return in_array($uri->getPath(), $validPaths);
|
|
|
|
}
|
2023-11-25 00:55:31 -03:00
|
|
|
}
|