Completed
Pull Request — master (#140)
by
unknown
04:51 queued 03:19
created

Controller::__invoke()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
1
<?php
2
3
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
4
5
use Exception;
6
use Pusher\Pusher;
7
use Illuminate\Support\Arr;
8
use Illuminate\Http\Request;
9
use GuzzleHttp\Psr7\Response;
10
use Ratchet\ConnectionInterface;
11
use Illuminate\Http\JsonResponse;
12
use GuzzleHttp\Psr7\ServerRequest;
13
use Illuminate\Support\Collection;
14
use Ratchet\Http\HttpServerInterface;
15
use Psr\Http\Message\RequestInterface;
16
use BeyondCode\LaravelWebSockets\Apps\App;
17
use BeyondCode\LaravelWebSockets\QueryParameters;
18
use Symfony\Component\HttpKernel\Exception\HttpException;
19
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
20
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
21
22
abstract class Controller implements HttpServerInterface
23
{
24
    /** @var string */
25
    protected $requestBuffer = '';
26
27
    /** @var RequestInterface */
28
    protected $request;
29
30
    /** @var int */
31
    protected $contentLength;
32
33
    /** @var \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager */
34
    protected $channelManager;
35
36
    public function __construct(ChannelManager $channelManager)
37
    {
38
        $this->channelManager = $channelManager;
39
    }
40
41
    public function onOpen(ConnectionInterface $connection, RequestInterface $request = null)
42
    {
43
        $this->request = $request;
44
45
        $this->contentLength = $this->findContentLength($request->getHeaders());
0 ignored issues
show
Bug introduced by
It seems like $request is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
46
47
        $this->requestBuffer = (string) $request->getBody();
48
49
        if (! $this->verifyContentLength()) {
50
            return;
51
        }
52
53
        $this->handleRequest($connection);
54
    }
55
56
    protected function findContentLength(array $headers): int
57
    {
58
        return Collection::make($headers)->first(function ($values, $header) {
59
            return strtolower($header) === 'content-length';
60
        })[0] ?? 0;
61
    }
62
63
    public function onMessage(ConnectionInterface $from, $msg)
64
    {
65
        $this->requestBuffer .= $msg;
66
67
        if (! $this->verifyContentLength()) {
68
            return;
69
        }
70
71
        $this->handleRequest($from);
72
    }
73
74
    protected function verifyContentLength()
75
    {
76
        return strlen($this->requestBuffer) === $this->contentLength;
77
    }
78
79
    protected function handleRequest(ConnectionInterface $connection)
80
    {
81
        $serverRequest = (new ServerRequest(
82
            $this->request->getMethod(),
83
            $this->request->getUri(),
84
            $this->request->getHeaders(),
85
            $this->requestBuffer,
86
            $this->request->getProtocolVersion()
87
        ))->withQueryParams(QueryParameters::create($this->request)->all());
88
89
        $laravelRequest = Request::createFromBase((new HttpFoundationFactory)->createRequest($serverRequest));
90
91
        $this
92
            ->ensureValidAppId($laravelRequest->appId)
93
            ->ensureValidSignature($laravelRequest);
94
95
        $response = $this($laravelRequest);
96
97
        $connection->send(JsonResponse::create($response));
98
        $connection->close();
99
    }
100
101
    public function onClose(ConnectionInterface $connection)
102
    {
103
    }
104
105
    public function onError(ConnectionInterface $connection, Exception $exception)
106
    {
107
        if (! $exception instanceof HttpException) {
108
            return;
109
        }
110
111
        $response = new Response($exception->getStatusCode(), [
112
            'Content-Type' => 'application/json',
113
        ], json_encode([
114
            'error' => $exception->getMessage(),
115
        ]));
116
117
        $connection->send(\GuzzleHttp\Psr7\str($response));
118
119
        $connection->close();
120
    }
121
122
    public function ensureValidAppId(string $appId)
123
    {
124
        if (! App::findById($appId)) {
125
            throw new HttpException(401, "Unknown app id `{$appId}` provided.");
126
        }
127
128
        return $this;
129
    }
130
131
    protected function ensureValidSignature(Request $request)
132
    {
133
        /*
134
         * The `auth_signature` & `body_md5` parameters are not included when calculating the `auth_signature` value.
135
         *
136
         * The `appId`, `appKey` & `channelName` parameters are actually route parameters and are never supplied by the client.
137
         */
138
        $params = Arr::except($request->query(), ['auth_signature', 'body_md5', 'appId', 'appKey', 'channelName']);
0 ignored issues
show
Bug introduced by
It seems like $request->query() targeting Illuminate\Http\Concerns...ractsWithInput::query() can also be of type null or string; however, Illuminate\Support\Arr::except() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
139
140
        if ($request->getContent() !== '') {
141
            $params['body_md5'] = md5($request->getContent());
142
        }
143
144
        ksort($params);
145
146
        $signature = "{$request->getMethod()}\n/{$request->path()}\n".Pusher::array_implode('=', '&', $params);
147
148
        $authSignature = hash_hmac('sha256', $signature, App::findById($request->get('appId'))->secret);
149
150
        if ($authSignature !== $request->get('auth_signature')) {
151
            throw new HttpException(401, 'Invalid auth signature provided.');
152
        }
153
154
        return $this;
155
    }
156
157
    abstract public function __invoke(Request $request);
158
}
159