first commit
This commit is contained in:
46
app/middleware/Cors.php
Normal file
46
app/middleware/Cors.php
Normal file
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
namespace app\middleware;
|
||||
|
||||
use Webman\Http\Request;
|
||||
use Webman\Http\Response;
|
||||
use Webman\MiddlewareInterface;
|
||||
|
||||
class Cors implements MiddlewareInterface
|
||||
{
|
||||
public function process(Request $request, callable $handler): Response
|
||||
{
|
||||
$origin = (string)$request->header('origin', '');
|
||||
$allow = trim((string)(getenv('CORS_ALLOW_ORIGINS') ?: '*'));
|
||||
$allowOrigin = '';
|
||||
|
||||
if ($allow === '*') {
|
||||
$allowOrigin = '*';
|
||||
} else {
|
||||
$allowList = array_values(array_filter(array_map('trim', explode(',', $allow))));
|
||||
if ($origin !== '' && in_array($origin, $allowList, true)) {
|
||||
$allowOrigin = $origin;
|
||||
}
|
||||
}
|
||||
|
||||
$headers = [
|
||||
'Access-Control-Allow-Methods' => 'GET,POST,PUT,PATCH,DELETE,OPTIONS',
|
||||
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With',
|
||||
'Access-Control-Max-Age' => '86400',
|
||||
];
|
||||
|
||||
if ($allowOrigin !== '') {
|
||||
$headers['Access-Control-Allow-Origin'] = $allowOrigin;
|
||||
if ($allowOrigin !== '*') {
|
||||
$headers['Access-Control-Allow-Credentials'] = 'true';
|
||||
}
|
||||
}
|
||||
|
||||
if (strtoupper($request->method()) === 'OPTIONS') {
|
||||
return response('', 204)->withHeaders($headers);
|
||||
}
|
||||
|
||||
$response = $handler($request);
|
||||
return $response->withHeaders($headers);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user