Skip to content
This repository was archived by the owner on Feb 10, 2025. It is now read-only.

Commit 5a82de6

Browse files
committed
fix: add more proper CORS implementation
1 parent b588d8f commit 5a82de6

File tree

3 files changed

+55
-22
lines changed

3 files changed

+55
-22
lines changed

App/Middlewares/CorsMiddleware.php

+40-8
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,53 @@
55
use Psr\Http\Message\ResponseInterface;
66
use Psr\Http\Message\ServerRequestInterface;
77
use Psr\Http\Server\RequestHandlerInterface;
8+
use Slim\Http\Factory\DecoratedResponseFactory;
9+
use Slim\Http\Response;
10+
use Slim\Psr7\Factory\ResponseFactory;
11+
use Slim\Psr7\Factory\StreamFactory;
12+
use Psr\Container\ContainerInterface;
813

914
class CorsMiddleware
1015
{
16+
public function __construct(
17+
private ContainerInterface $container
18+
)
19+
{
20+
}
21+
1122
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
1223
{
13-
$response = $handler->handle($request);
14-
$response = $response
15-
->withHeader('Access-Control-Allow-Origin', '*')
16-
->withHeader('Access-Control-Allow-Methods', 'POST, PUT, GET, OPTIONS')
17-
->withHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Authorization');
24+
$allowedOrigins = [
25+
$this->container->get('services')['web_endpoint'],
26+
$this->container->get('services')['admin_endpoint']
27+
];
28+
if (!$request->hasHeader('Origin')) {
29+
// do not treat this request with CORS
30+
return $handler->handle($request);
31+
}
32+
$origin = $request->getHeader('Origin')[0];
33+
if (in_array($origin, $allowedOrigins) === False) {
34+
// this origin is not allowed, skip CORS
35+
return $handler->handle($request);
36+
}
1837

19-
if ($request->getMethod() == "OPTIONS") {
20-
return $response->withJson(true);
38+
if ($request->getMethod() === "OPTIONS") {
39+
$response = (new DecoratedResponseFactory(new ResponseFactory(), new StreamFactory()))->createResponse();
40+
return $this
41+
->alterResponse($origin, $response)
42+
->withJson(true);
2143
}
44+
45+
$response = $handler->handle($request);
46+
47+
return $this->alterResponse($origin, $response);
48+
}
2249

23-
return $response;
50+
private function alterResponse(string $origin, ResponseInterface $response): Response
51+
{
52+
return $response
53+
->withHeader('Access-Control-Allow-Origin', $origin)
54+
->withHeader('Access-Control-Allow-Methods', 'POST, PUT, GET, OPTIONS')
55+
->withHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Authorization');
2456
}
2557
}

App/Middlewares/JWTMiddleware.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public function __construct(
2626
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler)
2727
{
2828
$response = (new DecoratedResponseFactory(new ResponseFactory(), new StreamFactory()))->createResponse();
29-
29+
3030
if (!$request->hasHeader('Authorization')) {
3131
return $response->withStatus(401)->withJson([
3232
'success' => false,

App/routes.php

+14-13
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44

55
use Slim\Routing\RouteCollectorProxy;
66

7-
function addRoutes(\Slim\App $app)
7+
function addRoutes(\Slim\App $app): void
88
{
9-
$app->add(new Middlewares\CorsMiddleware());
9+
$container = $app->getContainer();
10+
$app->add(new Middlewares\CorsMiddleware($container));
1011

1112
$app->get('/', [Controllers\PagesController::class, 'getHome']);
1213
$app->get('/ping', [Controllers\PagesController::class, 'getPing']);
@@ -16,28 +17,28 @@ function addRoutes(\Slim\App $app)
1617
$app->post('/newsletter/event', [Controllers\NewsletterController::class, 'postEvent']);
1718

1819
$app->map(['POST', 'OPTIONS'], '/graphql', [Controllers\GraphQlController::class, 'newRequest'])
19-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
20+
->add(new Middlewares\JWTMiddleware($container));
2021

2122
// STRIPE
2223
$app->map(['POST', 'OPTIONS'], '/stripe/create', [Controllers\Payment\StripeController::class, 'postCreateSession'])
23-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
24+
->add(new Middlewares\JWTMiddleware($container));
2425
$app->map(['POST', 'OPTIONS'], '/stripe/execute', [Controllers\Payment\StripeController::class, 'postExecute']);
2526

2627
// PAYPAL
2728
$app->map(['POST', 'OPTIONS'], '/paypal/get-url', [Controllers\Payment\PaypalController::class, 'postGetUrl'])
28-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
29+
->add(new Middlewares\JWTMiddleware($container));
2930
//$app->get('/paypal/execute', [Controllers\Payment\PaypalController::class, 'postExecute']);
3031
$app->map(['POST', 'OPTIONS'], '/paypal/execute', [Controllers\Payment\PaypalController::class, 'postExecute']);
3132

32-
$app->group('/account', function (RouteCollectorProxy $group) use ($app) {
33+
$app->group('/account', function (RouteCollectorProxy $group) use ($container) {
3334
$group->get('/login', [Controllers\AccountController::class, 'getLogin']);
3435
$group->get('/register', [Controllers\AccountController::class, 'getLogin']);
3536
$group->get('/login-desktop', [Controllers\AccountController::class, 'getLoginDesktop']);
3637
$group->post('/login-desktop', [Controllers\AccountController::class, 'postLoginDesktop'])
37-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
38+
->add(new Middlewares\JWTMiddleware($container));
3839

3940
$group->map(['GET', 'OPTIONS'], '/info', [Controllers\AccountController::class, 'getInfo'])
40-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
41+
->add(new Middlewares\JWTMiddleware($container));
4142

4243
$group->map(['POST', 'OPTIONS'], '/execute', [Controllers\AccountController::class, 'execute']);
4344
});
@@ -46,7 +47,7 @@ function addRoutes(\Slim\App $app)
4647
$group->map(['GET', 'OPTIONS'], '[/]', [Controllers\DashboardController::class, 'getDashboard']);
4748
$group->map(['POST', 'OPTIONS'], '/upload', [Controllers\UploadController::class, 'postUpload']);
4849
$group->map(['GET', 'OPTIONS'], '/delete', [Controllers\DashboardController::class, 'getDelete']);
49-
})->add(new Middlewares\JWTMiddleware($app->getContainer()));
50+
})->add(new Middlewares\JWTMiddleware($container));
5051

5152
$app->group('/shop', function (RouteCollectorProxy $group) {
5253
$group->get('/address', [Controllers\ShopController::class, 'getQueryAddress'])
@@ -66,17 +67,17 @@ function addRoutes(\Slim\App $app)
6667
// });
6768

6869
$app->get('/cache/shop/generate', [Controllers\PagesController::class, 'generateShopCache'])
69-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
70+
->add(new Middlewares\JWTMiddleware($container));
7071
$app->get('/websocket/connexions', [Controllers\PagesController::class, 'getWebSocketConnexions'])
71-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
72+
->add(new Middlewares\JWTMiddleware($container));
7273
$app->get('/test-send-email-event', [Controllers\PagesController::class, 'testSendEmailEvent'])
73-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
74+
->add(new Middlewares\JWTMiddleware($container));
7475

7576
$app->get('/countries/{locale}', [Controllers\CountriesController::class, 'getCountries']);
7677

7778
$app->get('/health', [Controllers\HealthController::class, 'getHealth']);
7879
$app->get('/dangerously-truncate-table', [Controllers\IntegrationTestController::class, 'getDangerouslyTruncateTables']);
7980
$app->get('/jwt', [Controllers\IntegrationTestController::class, 'getUserToken'])
80-
->add(new Middlewares\JWTMiddleware($app->getContainer()));
81+
->add(new Middlewares\JWTMiddleware($container));
8182

8283
}

0 commit comments

Comments
 (0)