index.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. require __DIR__ . '/../vendor/autoload.php';
  3. $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  4. $file = __DIR__ . $path;
  5. if (php_sapi_name() === 'cli-server' && is_file($file)) {
  6. return false;
  7. }
  8. if (class_exists(Dotenv\Dotenv::class) && file_exists(__DIR__ . '/../.env')) {
  9. Dotenv\Dotenv::createImmutable(
  10. dirname(__DIR__),
  11. null,
  12. true
  13. )->safeLoad();
  14. }
  15. error_reporting(E_ALL);
  16. use FrameworkX\App;
  17. use Middlewares\HmacAuthMiddleware;
  18. use Middlewares\JWTAuthMiddleware;
  19. use Middlewares\CorsMiddleware;
  20. use Psr\Http\Message\ServerRequestInterface;
  21. use React\Http\Message\Response;
  22. $app = new App();
  23. // Instancia os middlewares
  24. $authHmac = new HmacAuthMiddleware();
  25. $authJwt = new JWTAuthMiddleware();
  26. $cors = new CorsMiddleware();
  27. // Função para envolver rotas com CORS
  28. $withCors = function ($handler) use ($cors) {
  29. return function (ServerRequestInterface $request) use ($handler, $cors) {
  30. return $cors($request, $handler);
  31. };
  32. };
  33. // Função para lidar apenas com requisições OPTIONS
  34. $handleOptions = function (ServerRequestInterface $request) {
  35. $corsHeaders = [
  36. 'Access-Control-Allow-Origin' => '*',
  37. 'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
  38. 'Access-Control-Allow-Headers' => '*',
  39. 'Access-Control-Allow-Credentials' => 'true'
  40. ];
  41. return new Response(200, array_filter($corsHeaders));
  42. };
  43. // Rotas com CORS aplicado
  44. $app->get('/hmachelloworld', $withCors($authHmac), \Controllers\HelloController::class);
  45. $app->options('/hmachelloworld', $handleOptions);
  46. $app->get('/jwthelloworld', $withCors($authJwt), \Controllers\HelloController::class);
  47. $app->options('/jwthelloworld', $handleOptions);
  48. $app->post('/login', $withCors(\Controllers\LoginController::class));
  49. $app->options('/login', $handleOptions);
  50. $app->post('/register', $withCors(\Controllers\RegisterController::class));
  51. $app->options('/register', $handleOptions);
  52. $app->run();