File size: 4,785 Bytes
5f32fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Support\Chatbot\ChatbotHelper;
use Closure;
use Exception;
use Illuminate\Http\Response;

class CorsMiddleware
{
    use WithChatbotMiddleware;

    public const CHATBOT_EMBED_URI = '/chatbot-api/embed';

    public const CHATBOT_TOKEN_URI = '/chatbot-api/token';

    private array $tokenData;

    public function handle($request, Closure $next)
    {
        $this->setRequest($request);

        if ($this->isChatbotTokenRequest()) {
            return $this->handleChatbotTokenRequest($next);
        }

        if ($this->isChatbotRequest()) {
            return $this->handleChatbotRequest($next);
        }

        if ($this->isChatbotMessageRequest()) {
            return $this->handleChatbotMessageRequest($next);
        }

        return $next($this->request());
    }

    private function handleChatbotTokenRequest($next)
    {
        if (! $this->checkDomain(false)) {
            return response('Unauthorized', 403);
        }

        return $this->responseWithCorsHeaders($next);
    }

    private function handleChatbotRequest($next)
    {

        if (! $this->checkAppKey()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        if (! $this->checkDomain()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        if (! $this->checkToken()) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $this->loginUser();

        return $this->responseWithCorsHeaders($next);
    }

    private function handleChatbotMessageRequest($next)
    {
        if (! $this->checkAppKey(true)) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        if (! $this->checkDomain()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        if (! $this->checkToken(true)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $this->loginUser();

        return $this->streamedResponseWithCorsHeaders($next);
    }

    private function responseWithCorsHeaders($next)
    {
        /** @var Response $response */
        $response = $next($this->request());

        return $response->withHeaders($this->getCorsHeaders());
    }

    private function streamedResponseWithCorsHeaders($next)
    {
        /** @var Response $response */
        $response = $next($this->request());

        $corsHeaders = $this->getCorsHeaders();

        foreach ($corsHeaders as $key => $value) {
            $response->headers->set($key, $value);
        }

        $response->headers->set('Content-Type', 'text/event-stream');
        $response->headers->set('Cache-Control', 'no-cache');
        $response->headers->set('Connection', 'keep-alive');

        return $response;
    }

    private function checkToken(bool $fromInput = false): bool
    {
        if ($fromInput) {
            $this->request()->headers->set('Authorization', 'Bearer ' . $this->request()->input('token'));
        }

        $token = $this->getToken();

        if (! $token) {
            return false;
        }

        try {
            $data = ChatbotHelper::validateJWT($token);

            if (! $data) {
                return false;
            }

            if ($data['sub'] !== $this->getAppKey()) {
                return false;
            }

            if ($data['exp'] < time()) {
                return false;
            }

            if ($data['nbf'] > time()) {
                return false;
            }

            if ($data['aud'] !== $this->getOriginDomain()) {
                return false;
            }

            if ($data['iss'] !== $this->request()->getHost()) {
                return false;
            }

            $this->setTokenData($data);

            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function setTokenData(array $data): void
    {
        $this->tokenData = $data;
    }

    private function isChatbotTokenRequest(): bool
    {
        $request = $this->request();

        return $request->isMethod('POST') &&
            str()->startsWith($request->getRequestUri(), '/chatbot-api/token');
    }

    private function isChatbotRequest(): bool
    {
        $request = $this->request();

        return $request->isMethod('POST') &&
            str()->startsWith($request->getRequestUri(), '/chatbot-api') &&
            $request->hasHeader('X-MagicAI-Chatbot');
    }

    private function isChatbotMessageRequest(): bool
    {
        $request = $this->request();

        return $request->isMethod('GET') &&
            str()->startsWith($request->getRequestUri(), '/chatbot-api/chatbot-send');
    }
}