Skip to content

Commit 12334fc

Browse files
committed
fix: unable to establish WebSocket connection in Chrome
1 parent 0b622db commit 12334fc

4 files changed

Lines changed: 53 additions & 10 deletions

File tree

internal/server/router/socket/setup.go

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66

77
"github.com/anyshake/observer/internal/hardware"
88
"github.com/anyshake/observer/internal/hardware/explorer"
9-
"github.com/anyshake/observer/internal/server/middleware/auth_jwt"
109
"github.com/anyshake/observer/internal/server/response"
1110
"github.com/anyshake/observer/pkg/logger"
1211
"github.com/anyshake/observer/pkg/message"
@@ -18,15 +17,16 @@ import (
1817

1918
func Setup(routerGroup *gin.RouterGroup, timeSource *timesource.Source, hardware hardware.IHardware, jwtMiddleware gin.HandlerFunc) {
2019
s := socket{
21-
messageBus: message.NewBus[explorer.EventHandler](LOG_PREFIX, 65535),
22-
historyBuffer: make([]buffer, 0, HISTORY_BUFFER_SIZE),
20+
messageBus: message.NewBus[explorer.EventHandler](LOG_PREFIX, 65535),
21+
historyBuffer: make([]buffer, 0, HISTORY_BUFFER_SIZE),
22+
tokenValidator: newTokenValidator(jwtMiddleware),
2323
}
2424
hardware.Subscribe(LOG_PREFIX, func(t time.Time, di *explorer.DeviceConfig, dv *explorer.DeviceVariable, cd []explorer.ChannelData) {
2525
s.messageBus.Publish(t, di, dv, cd)
2626
s.storeHistory(t, di, cd)
2727
})
2828

29-
routerGroup.GET("/socket", auth_jwt.NewWebsocketAuthAdapter(), jwtMiddleware, func(ctx *gin.Context) {
29+
routerGroup.GET("/socket", func(ctx *gin.Context) {
3030
upgrader := websocket.Upgrader{
3131
ReadBufferSize: 1024,
3232
WriteBufferSize: 1024,
@@ -91,8 +91,22 @@ func (s *socket) sendHistory(conn *websocket.Conn, timeSource *timesource.Source
9191

9292
func (s *socket) handleWebSocket(_ *gin.Context, conn *websocket.Conn, timeSource *timesource.Source) {
9393
clientID := conn.RemoteAddr().String()
94+
logger.GetLogger(LOG_PREFIX).Infof("%s - client connected, waiting for authentication", clientID)
95+
96+
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
97+
_, tokenBytes, err := conn.ReadMessage()
98+
conn.SetReadDeadline(time.Time{})
99+
if err != nil {
100+
logger.GetLogger(LOG_PREFIX).Warnf("%s - authentication timeout or read error: %v", clientID, err)
101+
return
102+
}
103+
if !s.tokenValidator(string(tokenBytes)) {
104+
logger.GetLogger(LOG_PREFIX).Warnf("%s - authentication failed", clientID)
105+
return
106+
}
107+
94108
subscribedAt := time.Now()
95-
logger.GetLogger(LOG_PREFIX).Infof("%s - client subscribed to message bus", clientID)
109+
logger.GetLogger(LOG_PREFIX).Infof("%s - authenticated and subscribed to message bus", clientID)
96110

97111
callbackFn := func(t time.Time, di *explorer.DeviceConfig, dv *explorer.DeviceVariable, cd []explorer.ChannelData) {
98112
data := map[string]any{

internal/server/router/socket/types.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ type buffer struct {
1818
}
1919

2020
type socket struct {
21-
mu sync.Mutex
22-
messageBus message.Bus[explorer.EventHandler]
23-
historyBuffer []buffer
21+
mu sync.Mutex
22+
messageBus message.Bus[explorer.EventHandler]
23+
tokenValidator func(string) bool
24+
historyBuffer []buffer
2425
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package socket
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/gin-gonic/gin"
7+
)
8+
9+
type noopResponseWriter struct {
10+
header http.Header
11+
code int
12+
}
13+
14+
func (n *noopResponseWriter) Header() http.Header { return n.header }
15+
func (n *noopResponseWriter) Write(b []byte) (int, error) { return len(b), nil }
16+
func (n *noopResponseWriter) WriteHeader(code int) { n.code = code }
17+
18+
func newTokenValidator(middlewareFn gin.HandlerFunc) func(string) bool {
19+
return func(tokenStr string) bool {
20+
w := &noopResponseWriter{header: make(http.Header)}
21+
c, _ := gin.CreateTestContext(w)
22+
req, _ := http.NewRequest(http.MethodGet, "/", nil)
23+
req.Header.Set("Authorization", "Bearer "+tokenStr)
24+
c.Request = req
25+
middlewareFn(c)
26+
return !c.IsAborted()
27+
}
28+
}

web/src/src/views/RealTime/index.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,6 @@ const RealTime = () => {
9696

9797
const { readyState, sendMessage } = useSocket(
9898
{
99-
protocols: [`Bearer#${getCredential().token.replace(/=/g, '')}`],
10099
url: getSocketApiUrl(),
101100
onData: ({ data }) => {
102101
const { channel_data, sample_rate, record_time, current_time } = data;
@@ -132,9 +131,10 @@ const RealTime = () => {
132131
);
133132
useEffect(() => {
134133
if (readyState === 1) {
134+
sendMessage(getCredential().token);
135135
sendMessage('client hello');
136136
}
137-
}, [readyState, sendMessage]);
137+
}, [readyState, sendMessage, getCredential]);
138138

139139
const getInitialLayout = useCallback(
140140
(id: string, index: number) => {

0 commit comments

Comments
 (0)