From c2894693ea87f11b96cf45079fbcb2f4019bf41d Mon Sep 17 00:00:00 2001 From: Chen-I Lim Date: Tue, 2 Feb 2021 13:17:34 -0800 Subject: [PATCH] websocket: send not authenticated error --- server/ws/websockets.go | 19 +++++++++++++++++++ webapp/src/octoListener.ts | 13 +++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/server/ws/websockets.go b/server/ws/websockets.go index d7a4a2b02..ac90073e9 100644 --- a/server/ws/websockets.go +++ b/server/ws/websockets.go @@ -31,6 +31,11 @@ type UpdateMsg struct { Block model.Block `json:"block"` } +// ErrorMsg is sent on errors +type ErrorMsg struct { + Error string `json:"error"` +} + // WebsocketCommand is an incoming command from the client. type WebsocketCommand struct { Action string `json:"action"` @@ -156,6 +161,7 @@ func (ws *Server) authenticateListener(wsSession *websocketSession, token string func (ws *Server) addListener(wsSession *websocketSession, blockIDs []string) { if !wsSession.isAuthenticated { log.Printf("addListener: NOT AUTHENTICATED") + sendError(wsSession.client, "not authenticated") return } @@ -191,6 +197,7 @@ func (ws *Server) removeListener(client *websocket.Conn) { func (ws *Server) removeListenerFromBlocks(wsSession *websocketSession, blockIDs []string) { if !wsSession.isAuthenticated { log.Printf("removeListenerFromBlocks: NOT AUTHENTICATED") + sendError(wsSession.client, "not authenticated") return } @@ -217,6 +224,18 @@ func (ws *Server) removeListenerFromBlocks(wsSession *websocketSession, blockIDs ws.mu.Unlock() } +func sendError(conn *websocket.Conn, message string) { + errorMsg := ErrorMsg{ + Error: message, + } + + err := conn.WriteJSON(errorMsg) + if err != nil { + log.Printf("sendError error: %v", err) + conn.Close() + } +} + // getListeners returns the listeners to a blockID's changes. func (ws *Server) getListeners(blockID string) []*websocket.Conn { ws.mu.Lock() diff --git a/webapp/src/octoListener.ts b/webapp/src/octoListener.ts index 4db56ce64..335c922a2 100644 --- a/webapp/src/octoListener.ts +++ b/webapp/src/octoListener.ts @@ -11,9 +11,9 @@ type WSCommand = { // These are messages from the server type WSMessage = { - action: string - blockId: string - block: IBlock + action?: string + block?: IBlock + error?: string } type OnChangeHandler = (blocks: IBlock[]) => void @@ -92,10 +92,15 @@ class OctoListener { try { const message = JSON.parse(e.data) as WSMessage + if (message.error) { + Utils.logError(`Listener websocket error: ${message.error}`) + return + } + switch (message.action) { case 'UPDATE_BLOCK': Utils.log(`OctoListener update block: ${message.block?.id}`) - this.queueUpdateNotification(message.block) + this.queueUpdateNotification(message.block!) break default: Utils.logError(`Unexpected action: ${message.action}`)