implement cors

This commit is contained in:
Bence Pőcze 2024-08-02 01:28:37 +02:00
parent e59d627080
commit a5debfc781
Signed by: bence
GPG Key ID: DC5BD6E95A333E6D

View File

@ -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,47 @@ class HttpResponse
}
}
private function handleCors(): void
{
if (isset($this->appConfig['cors']['allow_origins'])) {
$origin = $this->request->header('Origin');
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);
}
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'];
}
header('Access-Control-Allow-Methods: ' . join(', ', $allow_methods));
}
if (isset($this->appConfig['cors']['max_age'])) {
header("Access-Control-Max-Age: {$this->appConfig['cors']['max_age']}");
}
}
private function redirectToLogin(): void
{
$this->request->session()->set('redirect_after_login', $this->rawUrl);