Skip to content

Commit 5a78f8d

Browse files
committed
Fix: websocket requests were not authenticated
1 parent 6e7285d commit 5a78f8d

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

websocket.go

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package web
22

33
import (
4+
"encoding/json"
45
"net/http"
56

67
"github.com/gorilla/websocket"
@@ -24,14 +25,33 @@ var upgrader = websocket.Upgrader{
2425

2526
func (s *Server) socketHandler(endpointHandle SocketHandle, options HandleOptions) httprouter.Handle {
2627
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
28+
var userData interface{}
29+
30+
if options.AuthenticateMethod != nil {
31+
userData = options.AuthenticateMethod(r)
32+
if isUserdataNil(userData) {
33+
if options.UnauthorizedMethod == nil {
34+
s.log.Warn("Rejected authenticated request")
35+
w.Header().Set("Content-Type", "application/json")
36+
w.WriteHeader(http.StatusUnauthorized)
37+
json.NewEncoder(w).Encode(Error{401, "Unauthorized"})
38+
return
39+
}
40+
41+
options.UnauthorizedMethod(w, r)
42+
return
43+
}
44+
}
45+
2746
conn, err := upgrader.Upgrade(w, r, nil)
2847
if err != nil {
2948
s.log.Error("Error upgrading client for websocket connection: %s", err.Error())
3049
return
3150
}
3251
endpointHandle(Request{
33-
Params: ps,
34-
log: s.log,
52+
Params: ps,
53+
UserData: userData,
54+
log: s.log,
3555
}, WSConn{
3656
c: conn,
3757
})

0 commit comments

Comments
 (0)