From e67afc401b51d4c00cf0557287373737c14e98f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=91cze=20Bence?= Date: Fri, 2 Aug 2024 01:28:37 +0200 Subject: [PATCH] implement cors --- src/Response/HttpResponse.php | 55 +++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/Response/HttpResponse.php b/src/Response/HttpResponse.php index 307a956..6e39d0b 100644 --- a/src/Response/HttpResponse.php +++ b/src/Response/HttpResponse.php @@ -55,6 +55,11 @@ class HttpResponse public function render(): void { + $this->handleCors(); + if ($this->method === 'options') { + return; + } + $match = $this->routeCollection->match($this->method, $this->parsedUrl['path']); if ($match === null) { $this->render404(); @@ -110,6 +115,56 @@ class HttpResponse } } + private function handleCors(): void + { + $origin = $this->request->header('Origin'); + if (!$origin) { + return; + } + + if (isset($this->appConfig['cors']['allow_origins'])) { + if (in_array($origin, $this->appConfig['cors']['allow_origins']) || in_array('*', $this->appConfig['cors']['allow_origins'])) { + header("Access-Control-Allow-Origin: {$origin}"); + } + } + + if (!empty($this->appConfig['cors']['allow_credentials'])) { + header('Access-Control-Allow-Credentials: true'); + } + + if ($this->method !== 'options') { + return; + } + + if (isset($this->appConfig['cors']['allow_headers'])) { + $headers = explode(',', $this->request->header('Access-Control-Request-Headers')); + if (in_array('*', $this->appConfig['cors']['allow_headers'])) { + $allow_headers = $headers; + } else { + $allow_headers = array_intersect($this->appConfig['cors']['allow_headers'], $headers); + } + + if (count($allow_headers) > 0) { + header('Access-Control-Allow-Headers: ' . join(', ', $allow_headers)); + } + } + + if (isset($this->appConfig['cors']['allow_methods'])) { + if (in_array('*', $this->appConfig['cors']['allow_methods'])) { + $allow_methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT']; + } else { + $allow_methods = $this->appConfig['cors']['allow_methods']; + } + + if (count($allow_methods) > 0) { + header('Access-Control-Allow-Methods: ' . join(', ', $allow_methods)); + } + } + + $max_age = $this->appConfig['cors']['max_age'] ?? 600; + header("Access-Control-Max-Age: {$max_age}"); + } + private function redirectToLogin(): void { $this->request->session()->set('redirect_after_login', $this->rawUrl); -- 2.45.2