| 3 |
liveuser |
1 |
<?php
|
|
|
2 |
namespace Ratchet\Http;
|
|
|
3 |
use Ratchet\ConnectionInterface;
|
|
|
4 |
use Ratchet\MessageComponentInterface;
|
|
|
5 |
use Psr\Http\Message\RequestInterface;
|
|
|
6 |
|
|
|
7 |
/**
|
|
|
8 |
* A middleware to ensure JavaScript clients connecting are from the expected domain.
|
|
|
9 |
* This protects other websites from open WebSocket connections to your application.
|
|
|
10 |
* Note: This can be spoofed from non-web browser clients
|
|
|
11 |
*/
|
|
|
12 |
class OriginCheck implements HttpServerInterface {
|
|
|
13 |
use CloseResponseTrait;
|
|
|
14 |
|
|
|
15 |
/**
|
|
|
16 |
* @var \Ratchet\MessageComponentInterface
|
|
|
17 |
*/
|
|
|
18 |
protected $_component;
|
|
|
19 |
|
|
|
20 |
public $allowedOrigins = [];
|
|
|
21 |
|
|
|
22 |
/**
|
|
|
23 |
* @param MessageComponentInterface $component Component/Application to decorate
|
|
|
24 |
* @param array $allowed An array of allowed domains that are allowed to connect from
|
|
|
25 |
*/
|
|
|
26 |
public function __construct(MessageComponentInterface $component, array $allowed = []) {
|
|
|
27 |
$this->_component = $component;
|
|
|
28 |
$this->allowedOrigins += $allowed;
|
|
|
29 |
}
|
|
|
30 |
|
|
|
31 |
/**
|
|
|
32 |
* {@inheritdoc}
|
|
|
33 |
*/
|
|
|
34 |
public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) {
|
|
|
35 |
$header = (string)$request->getHeader('Origin')[0];
|
|
|
36 |
$origin = parse_url($header, PHP_URL_HOST) ?: $header;
|
|
|
37 |
|
|
|
38 |
if (!in_array($origin, $this->allowedOrigins)) {
|
|
|
39 |
return $this->close($conn, 403);
|
|
|
40 |
}
|
|
|
41 |
|
|
|
42 |
return $this->_component->onOpen($conn, $request);
|
|
|
43 |
}
|
|
|
44 |
|
|
|
45 |
/**
|
|
|
46 |
* {@inheritdoc}
|
|
|
47 |
*/
|
|
|
48 |
function onMessage(ConnectionInterface $from, $msg) {
|
|
|
49 |
return $this->_component->onMessage($from, $msg);
|
|
|
50 |
}
|
|
|
51 |
|
|
|
52 |
/**
|
|
|
53 |
* {@inheritdoc}
|
|
|
54 |
*/
|
|
|
55 |
function onClose(ConnectionInterface $conn) {
|
|
|
56 |
return $this->_component->onClose($conn);
|
|
|
57 |
}
|
|
|
58 |
|
|
|
59 |
/**
|
|
|
60 |
* {@inheritdoc}
|
|
|
61 |
*/
|
|
|
62 |
function onError(ConnectionInterface $conn, \Exception $e) {
|
|
|
63 |
return $this->_component->onError($conn, $e);
|
|
|
64 |
}
|
|
|
65 |
}
|