94 lines
3.0 KiB
PHP
94 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace Lean\Api\Lib;
|
|
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
|
use Ulmus\Api\Stream\Stream;
|
|
|
|
class RenderCORS
|
|
{
|
|
public function __construct(
|
|
protected ServerRequestInterface $request,
|
|
public string|array $origin = "http://localhost,https://localhost",
|
|
public bool $allowCredentials = true,
|
|
public string|array $methods = [ "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", ],
|
|
public string|array $headers = [ "Content-Type", "Authorization", "X-Requested-With" ],
|
|
) {
|
|
if (is_string($this->origin)) {
|
|
$this->origin = explode(',', $this->origin);
|
|
}
|
|
}
|
|
|
|
public function renderHeader(ServerRequestInterface $request) : void
|
|
{
|
|
$matched = $this->matchOrigin($this->request->getServerParams()['HTTP_ORIGIN'] ?? null, $this->origin);
|
|
|
|
if (! $matched) {
|
|
return;
|
|
}
|
|
|
|
$render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e));
|
|
|
|
header('Access-Control-Allow-Origin: ' . $matched);
|
|
header(sprintf('Access-Control-Allow-Methods: %s', $render($this->methods)));
|
|
header(sprintf('Access-Control-Allow-Headers: %s', $render($this->headers)));
|
|
header('Access-Control-Allow-Credentials: ' . ($this->allowCredentials ? 'true' : 'false'));
|
|
}
|
|
|
|
public function fromResponse(ResponseInterface $response, bool $emptyResponse = false) : ResponseInterface
|
|
{
|
|
$matched = $this->matchOrigin($this->request->getServerParams()['HTTP_ORIGIN'] ?? null, $this->origin);
|
|
|
|
if (! $matched) {
|
|
return $response;
|
|
}
|
|
|
|
$render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e));
|
|
|
|
$response = $response
|
|
->withHeader('Access-Control-Allow-Origin', $matched)
|
|
->withHeader('Access-Control-Allow-Methods', $render($this->methods))
|
|
->withHeader('Access-Control-Allow-Headers', $render($this->headers))
|
|
->withHeader('Access-Control-Allow-Credentials', $this->allowCredentials ? 'true' : 'false');
|
|
|
|
if ($emptyResponse) {
|
|
$response = $response->withBody(Stream::fromMemory())->withStatus(200);
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
|
|
function matchOrigin(?string $origin, string|array $allowList): ?string
|
|
{
|
|
if ($origin === null || $origin === '') {
|
|
return null;
|
|
}
|
|
|
|
foreach ((array) $allowList as $rule) {
|
|
if ($rule === '*') {
|
|
return '*';
|
|
}
|
|
|
|
// Regex rule: "/.../"
|
|
if (is_string($rule) && strlen($rule) >= 2 && $rule[0] === '/' && substr($rule, -1) === '/') {
|
|
if (@preg_match($rule, $origin) === 1) {
|
|
return $origin;
|
|
}
|
|
|
|
continue;
|
|
}
|
|
|
|
// Exact match
|
|
if (is_string($rule) && hash_equals($rule, $origin)) {
|
|
return $origin;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
}
|
|
|