@@ -189,14 +189,49 @@ class streamStat{
189189 std::string tags;
190190};
191191
192- void Controller::handleWebSocket (HTTP::Parser &H, Socket::Connection &C){
192+ void Controller::handleWebSocket (HTTP::Parser &H, Socket::Connection &C, bool authorized ){
193193 std::string logs = H.GetVar (" logs" );
194194 std::string accs = H.GetVar (" accs" );
195195 bool doStreams = H.GetVar (" streams" ).size ();
196196 HTTP::Parser req = H;
197197 H.Clean ();
198198 HTTP::Websocket W (C, req, H);
199199 if (!W){return ;}
200+
201+ if (authorized){
202+ W.sendFrame (" [\" auth\" , true]" );
203+ }else {
204+ W.sendFrame (" [\" auth\" , false]" );
205+ C.setBlocking (false );
206+ }
207+ uint64_t authTime = Util::bootMS ();
208+ while (!authorized && W){
209+ if (W.readFrame ()){
210+
211+ // only handle text frames
212+ if (W.frameType != 1 ){continue ;}
213+
214+ // Parse JSON and check command type
215+ JSON::Value command = JSON::fromString (W.data , W.data .size ());
216+ if (command.isArray () && command[0u ].asString () == " auth" ){
217+ tthread::lock_guard<tthread::mutex> guard (configMutex);
218+ JSON::Value req;
219+ req[" authorize" ] = command[1u ];
220+ authorized = authorize (req, req, C);
221+ W.sendFrame (" [\" auth\" , " +req[" authorize" ].toString ()+" ]" );
222+ }
223+ }
224+ Util::sleep (100 );
225+ if (Util::bootMS () > authTime + 10000 ){
226+ W.sendFrame (" [\" auth\" ,\" Too slow, sorry\" ]" );
227+ C.close ();
228+ }
229+ }
230+ if (!authorized || !W || !C){return ;}
231+ C.setBlocking (true );
232+
233+
234+
200235
201236 IPC::sharedPage shmLogs (SHM_STATE_LOGS, 1024 * 1024 );
202237 IPC::sharedPage shmAccs (SHM_STATE_ACCS, 1024 * 1024 );
@@ -364,15 +399,7 @@ int Controller::handleAPIConnection(Socket::Connection &conn){
364399 }
365400 // Catch websocket requests
366401 if (H.url == " /ws" ){
367- if (!authorized){
368- H.Clean ();
369- H.body = " Please login first or provide a valid token authentication." ;
370- H.SetHeader (" Server" , APPIDENT);
371- H.SendResponse (" 403" , " Not authorized" , conn);
372- H.Clean ();
373- continue ;
374- }
375- handleWebSocket (H, conn);
402+ handleWebSocket (H, conn, authorized);
376403 H.Clean ();
377404 continue ;
378405 }
0 commit comments