Files
contabilidad/api/common/Middleware/Auth.php
2021-12-06 22:10:41 -03:00

30 lines
1.1 KiB
PHP

<?php
namespace Contabilidad\Common\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ResponseFactoryInterface as Factory;
use Contabilidad\Common\Service\Auth as Service;
class Auth {
protected Factory $factory;
protected Service $service;
public function __construct(Factory $factory, Service $service) {
$this->factory = $factory;
$this->service = $service;
}
public function __invoke(Request $request, Handler $handler): Response {
if ($request->getMethod() == 'OPTIONS') {
return $handler->handle($request);
}
if (!$this->service->isValid($request)) {
$response = $this->factory->createResponse(401);
$response->getBody()->write(json_encode(['message' => 'Invalid API KEY.']));
return $response
->withHeader('Content-Type', 'application/json');
}
return $handler->handle($request);
}
}