Files
emails/api/common/Middleware/Auth.php

62 lines
2.0 KiB
PHP
Raw Normal View History

2022-11-25 20:52:52 -03:00
<?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;
2023-06-12 21:14:07 -04:00
use ProVM\Common\Exception\Request\Auth\Unauthorized;
use ProVM\Common\Service\Auth as Service;
2022-11-25 20:52:52 -03:00
class Auth
{
2023-06-12 21:14:07 -04:00
public function __construct(ResponseFactoryInterface $factory, LoggerInterface $logger, protected Service $service)
2022-11-25 20:52:52 -03:00
{
$this->setResponseFactory($factory);
$this->setLogger($logger);
}
protected ResponseFactoryInterface $factory;
protected LoggerInterface $logger;
public function getResponseFactory(): ResponseFactoryInterface
{
return $this->factory;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function setResponseFactory(ResponseFactoryInterface $factory): Auth
{
$this->factory = $factory;
return $this;
}
public function setLogger(LoggerInterface $logger): Auth
{
$this->logger = $logger;
return $this;
}
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getMethod() === 'OPTIONS') {
return $handler->handle($request);
}
2023-06-12 21:14:07 -04:00
try {
if ($this->service->validate($request)) {
return $handler->handle($request);
2022-11-25 20:52:52 -03:00
}
2023-06-12 21:14:07 -04:00
} catch (Unauthorized $e) {
$response = $this->getResponseFactory()->createResponse($e->getCode());
$response->getBody()->write(json_encode(['error' => $e->getCode(), 'message' => $e->getMessage()]));
2022-11-25 20:52:52 -03:00
}
2023-06-12 21:14:07 -04:00
$response = $this->getResponseFactory()->createResponse(413);
$response->getBody()->write(\Safe\json_encode(['error' => 413, 'message' => 'Incorrect token']));
2022-11-25 20:52:52 -03:00
return $response
->withHeader('Content-Type', 'application/json');
}
2023-06-12 21:14:07 -04:00
}