- Added CORS preflight handling

This commit is contained in:
Dave Mc Nicoll 2025-09-12 19:38:53 +00:00
parent 5d6d7ff49c
commit c5ec582bd1
3 changed files with 56 additions and 0 deletions

View File

@ -53,6 +53,7 @@ return [
},
Lean\ApplicationStrategy\NotFoundDecoratorInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\NotFoundDecorator::class),
Lean\ApplicationStrategy\MethodNotAllowedInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\MethodNotAllowedDecorator::class),
Lean\Api\Factory\MessageFactoryInterface::class => DI\autowire(Lean\Api\Lib\Message::class),
Lean\Api\Factory\DebugFormFactoryInterface::class => DI\autowire(Lean\Api\Factory\DebugFormFactory::class),
# League\Route\Strategy\ApplicationStrategy::class => DI\autowire(Lean\Api\ApplicationStrategy::class),

View File

@ -0,0 +1,29 @@
<?php
namespace Lean\Api\ApplicationStrategy;
use DI\Attribute\Inject;
use Lean\ApplicationStrategy;
use Lean\Factory\HttpFactoryInterface;
use Picea\Picea;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class MethodNotAllowedDecorator implements \Lean\ApplicationStrategy\MethodNotAllowedInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getMethod() === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Credentials: true');
exit(0);
}
return $handler->handle($request);;
}
}

26
src/Middleware/CORS.php Normal file
View File

@ -0,0 +1,26 @@
<?php
namespace Lean\Api\Middleware;
use Laminas\Diactoros\Response\JsonResponse;
use Lean\Factory\HttpFactory;
use Picea\Ui\Method\FormHandler;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Lean\Api\{Factory\DebugFormFactoryInterface, Form, Entity};
class CORS implements MiddlewareInterface {
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
var_dump($request->getMethod() );
if ($request->getMethod() === "option") {
die("an option :)");
}
return $handler->handle($request);
}
}