websocket: send not authenticated error

This commit is contained in:
Chen-I Lim 2021-02-02 13:17:34 -08:00
parent a56cf03e0c
commit c2894693ea
2 changed files with 28 additions and 4 deletions

View file

@ -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()

View file

@ -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}`)