1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BeyondCode\LaravelWebSockets\Server; |
4
|
|
|
|
5
|
|
|
use Ratchet\ConnectionInterface; |
6
|
|
|
use Ratchet\Http\CloseResponseTrait; |
7
|
|
|
use Ratchet\Http\HttpServerInterface; |
8
|
|
|
use Psr\Http\Message\RequestInterface; |
9
|
|
|
use Ratchet\MessageComponentInterface; |
10
|
|
|
|
11
|
|
|
class OriginCheck implements HttpServerInterface |
12
|
|
|
{ |
13
|
|
|
use CloseResponseTrait; |
14
|
|
|
|
15
|
|
|
/** @var \Ratchet\MessageComponentInterface */ |
16
|
|
|
protected $_component; |
17
|
|
|
|
18
|
|
|
protected $allowedOrigins = []; |
19
|
|
|
|
20
|
|
|
public function __construct(MessageComponentInterface $component, array $allowedOrigins = []) |
21
|
|
|
{ |
22
|
|
|
$this->_component = $component; |
23
|
|
|
|
24
|
|
|
$this->allowedOrigins = $allowedOrigins; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function onOpen(ConnectionInterface $connection, RequestInterface $request = null) |
28
|
|
|
{ |
29
|
|
|
if ($request->hasHeader('Origin')) { |
|
|
|
|
30
|
|
|
$this->verifyOrigin($connection, $request); |
|
|
|
|
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
return $this->_component->onOpen($connection, $request); |
|
|
|
|
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function onMessage(ConnectionInterface $from, $msg) |
37
|
|
|
{ |
38
|
|
|
return $this->_component->onMessage($from, $msg); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function onClose(ConnectionInterface $connection) |
42
|
|
|
{ |
43
|
|
|
return $this->_component->onClose($connection); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function onError(ConnectionInterface $connection, \Exception $e) |
47
|
|
|
{ |
48
|
|
|
return $this->_component->onError($connection, $e); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
protected function verifyOrigin(ConnectionInterface $connection, RequestInterface $request) |
52
|
|
|
{ |
53
|
|
|
$header = (string) $request->getHeader('Origin')[0]; |
54
|
|
|
$origin = parse_url($header, PHP_URL_HOST) ?: $header; |
55
|
|
|
|
56
|
|
|
if (! empty($this->allowedOrigins) && ! in_array($origin, $this->allowedOrigins)) { |
57
|
|
|
return $this->close($connection, 403); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe: