Parcourir la source

Merge branch 'master' of ssh://git.mixtech.dev.br:22622/Bar/bartender

Fernando il y a 5 mois
Parent
commit
383aa282f6
4 fichiers modifiés avec 137 ajouts et 4 suppressions
  1. 53 0
      middlewares/CorsControl.php
  2. 43 0
      package-lock.json
  3. 5 0
      package.json
  4. 36 4
      public/index.php

+ 53 - 0
middlewares/CorsControl.php

@@ -0,0 +1,53 @@
+<?php
+
+namespace Middlewares;
+
+use Psr\Http\Message\ServerRequestInterface;
+use React\Http\Message\Response;
+
+class CorsControl
+{
+    public function __invoke(ServerRequestInterface $request, $next)
+    {
+        // 1) Configurações CORS completamente abertas:
+        $corsHeaders = [
+            'Access-Control-Allow-Origin'      => '0.0.0.0',
+            'Access-Control-Allow-Methods'     => 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
+            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With, Accept, Origin',
+            'Access-Control-Allow-Credentials' => 'true',
+            'Access-Control-Max-Age'           => '86400', // cache de preflight por 24h
+        ];
+
+        // 2) Responde direto a preflight
+        if ($request->getMethod() === 'OPTIONS') {
+            return new Response(204, $corsHeaders);
+        }
+
+        // 3) Se o “next” vier como string (nome de classe), instancia‑o:
+        if (is_string($next) && class_exists($next)) {
+            $instance = new $next();
+
+            // se tiver __invoke, use-o
+            if (is_callable($instance)) {
+                $next = $instance;
+            }
+            // caso seu controller siga outro padrão PSR-15, adapte aqui:
+            // elseif (method_exists($instance, 'handle')) {
+            //     $next = [$instance, 'handle'];
+            // }
+            else {
+                throw new \RuntimeException("Controller “{$next}” não é callable");
+            }
+        }
+
+        // 4) Chama o próximo handler (agora garantidamente callable)
+        $response = $next($request);
+
+        // 5) Injeta os headers CORS na resposta
+        foreach ($corsHeaders as $h => $v) {
+            $response = $response->withHeader($h, $v);
+        }
+
+        return $response;
+    }
+}

+ 43 - 0
package-lock.json

@@ -0,0 +1,43 @@
+{
+  "name": "bartender",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "": {
+      "dependencies": {
+        "cors": "^2.8.5"
+      }
+    },
+    "node_modules/cors": {
+      "version": "2.8.5",
+      "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
+      "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
+      "license": "MIT",
+      "dependencies": {
+        "object-assign": "^4",
+        "vary": "^1"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/object-assign": {
+      "version": "4.1.1",
+      "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+      "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/vary": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+      "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    }
+  }
+}

+ 5 - 0
package.json

@@ -0,0 +1,5 @@
+{
+  "dependencies": {
+    "cors": "^2.8.5"
+  }
+}

+ 36 - 4
public/index.php

@@ -17,20 +17,52 @@ if (class_exists(Dotenv\Dotenv::class) && file_exists(__DIR__ . '/../.env')) {
 }
 
 error_reporting(E_ALL);
+ini_set('display_errors', 1); // Para depuração
+ini_set('display_startup_errors', 1);
 
 use FrameworkX\App;
 use Middlewares\HmacAuthMiddleware;
 use Middlewares\JWTAuthMiddleware;
+use Middlewares\CorsControl;
+use Psr\Http\Message\ServerRequestInterface;
+use React\Http\Message\Response;
 
 $app = new App();
+
+// Instancia os middlewares
 $authHmac = new HmacAuthMiddleware();
 $authJwt = new JWTAuthMiddleware();
+$cors = new CorsControl();
+
+// Função para envolver rotas com CORS
+$withCors = function ($handler) use ($cors) {
+    return function (ServerRequestInterface $request) use ($handler, $cors) {
+        return $cors($request, $handler);
+    };
+};
+
+// Função para lidar com requisições OPTIONS
+$handleOptions = function (ServerRequestInterface $request) {
+    $corsHeaders = [
+        'Access-Control-Allow-Origin' => '*',
+        'Access-Control-Allow-Methods' => '*',
+        'Access-Control-Allow-Headers' => '*'
+    ];
+    return new Response(200, $corsHeaders);
+};
+
+// Rotas com CORS aplicado
+$app->get('/hmachelloworld', $withCors($authHmac), \Controllers\HelloController::class);
+$app->options('/hmachelloworld', $handleOptions);
+
+$app->get('/jwthelloworld', $withCors($authJwt), \Controllers\HelloController::class);
+$app->options('/jwthelloworld', $handleOptions);
 
-$app->get('/hmachelloworld', $authHmac,\Controllers\HelloController::class);
-$app->get('/jwthelloworld', $authJwt,\Controllers\HelloController::class);
+$app->post('/login', $withCors(\Controllers\LoginController::class));
+$app->options('/login', $handleOptions);
 
-$app->post('/login', \Controllers\LoginController::class);
-$app->post('/register', \Controllers\RegisterController::class);
+$app->post('/register', $withCors(\Controllers\RegisterController::class));
+$app->options('/register', $handleOptions);
 
 $app->get('/category', \Controllers\CategoryController::class);
 $app->post('/category', \Controllers\CategoryController::class);