| 1 | <?php |
||
| 8 | */ |
||
| 9 | class OriginComponent |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * @var false|resource |
||
| 13 | */ |
||
| 14 | private $client; |
||
| 15 | |||
| 16 | |||
| 17 | /** |
||
| 18 | * @var ServerConfig |
||
| 19 | */ |
||
| 20 | private ServerConfig $config; |
||
|
|
|||
| 21 | |||
| 22 | /** |
||
| 23 | * OriginComponent constructor. |
||
| 24 | * @param ServerConfig $config |
||
| 25 | * @param false|resource $client |
||
| 26 | */ |
||
| 27 | public function __construct(ServerConfig $config, $client) |
||
| 28 | { |
||
| 29 | $this->config = $config; |
||
| 30 | $this->client = $client; |
||
| 31 | } |
||
| 32 | |||
| 33 | /** |
||
| 34 | * Checks if there is a compatible origin header came from client |
||
| 35 | * @param string $headers |
||
| 36 | * @return bool |
||
| 37 | * @throws \Exception |
||
| 38 | */ |
||
| 39 | public function checkOrigin(string $headers): bool |
||
| 40 | { |
||
| 41 | preg_match('/Origin\:\s(.*?)\s/', $headers, $matches); |
||
| 42 | if (empty($matches[1])) { |
||
| 43 | $this->sendAndClose('No Origin header found.'); |
||
| 44 | return false; |
||
| 45 | } |
||
| 46 | |||
| 47 | $originHost = $matches[1]; |
||
| 48 | $allowedOrigins = $this->config->getOrigins(); |
||
| 49 | if (in_array($originHost, $allowedOrigins, true) === false) { |
||
| 50 | $this->sendAndClose('Host ' . $originHost . ' is not allowed to pass access control as origin.'); |
||
| 51 | return false; |
||
| 52 | } |
||
| 53 | |||
| 54 | return true; |
||
| 55 | } |
||
| 56 | |||
| 57 | /** |
||
| 67 | } |