40 lines
1.2 KiB
PHP
40 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Middleware;
|
|
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Psr\Http\Server\MiddlewareInterface;
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
|
use Slim\Psr7\Response;
|
|
|
|
class CorsMiddleware implements MiddlewareInterface
|
|
{
|
|
private const ALLOWED_ORIGIN = 'http://localhost:5173';
|
|
|
|
public function process(
|
|
ServerRequestInterface $request,
|
|
RequestHandlerInterface $handler,
|
|
): ResponseInterface {
|
|
if ($request->getMethod() === 'OPTIONS') {
|
|
return $this->withCorsHeaders(new Response(204));
|
|
}
|
|
|
|
return $this->withCorsHeaders($handler->handle($request));
|
|
}
|
|
|
|
private function withCorsHeaders(ResponseInterface $response): ResponseInterface
|
|
{
|
|
return $response
|
|
->withHeader('Access-Control-Allow-Origin', self::ALLOWED_ORIGIN)
|
|
->withHeader('Access-Control-Allow-Credentials', 'true')
|
|
->withHeader(
|
|
'Access-Control-Allow-Headers',
|
|
'Content-Type, Authorization',
|
|
)
|
|
->withHeader(
|
|
'Access-Control-Allow-Methods',
|
|
'GET, POST, OPTIONS',
|
|
);
|
|
}
|
|
}
|