api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CorsMiddleware.php 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Tqdev\PhpCrudApi\Middleware;
  3. use Tqdev\PhpCrudApi\Controller\Responder;
  4. use Tqdev\PhpCrudApi\Record\ErrorCode;
  5. use Tqdev\PhpCrudApi\Request;
  6. use Tqdev\PhpCrudApi\Response;
  7. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  8. class CorsMiddleware extends Middleware
  9. {
  10. private function isOriginAllowed(String $origin, String $allowedOrigins): bool
  11. {
  12. $found = false;
  13. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  14. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  15. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  16. if (preg_match($regex, $origin)) {
  17. $found = true;
  18. break;
  19. }
  20. }
  21. return $found;
  22. }
  23. public function handle(Request $request): Response
  24. {
  25. $method = $request->getMethod();
  26. $origin = $request->getHeader('Origin');
  27. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  28. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  29. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  30. } elseif ($method == 'OPTIONS') {
  31. $response = new Response(Response::OK, '');
  32. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN');
  33. $response->addHeader('Access-Control-Allow-Headers', $allowHeaders);
  34. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  35. $response->addHeader('Access-Control-Allow-Methods', $allowMethods);
  36. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  37. $response->addHeader('Access-Control-Allow-Credentials', $allowCredentials);
  38. $maxAge = $this->getProperty('maxAge', '1728000');
  39. $response->addHeader('Access-Control-Max-Age', $maxAge);
  40. } else {
  41. $response = $this->next->handle($request);
  42. }
  43. if ($origin) {
  44. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  45. $response->addHeader('Access-Control-Allow-Credentials', $allowCredentials);
  46. $response->addHeader('Access-Control-Allow-Origin', $origin);
  47. }
  48. return $response;
  49. }
  50. }