Skip to content

Commit

Permalink
Fix: websocket requests were not authenticated
Browse files Browse the repository at this point in the history
  • Loading branch information
ecnepsnai committed Dec 30, 2020
1 parent 6e7285d commit 5a78f8d
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions websocket.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package web

import (
"encoding/json"
"net/http"

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

func (s *Server) socketHandler(endpointHandle SocketHandle, options HandleOptions) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var userData interface{}

if options.AuthenticateMethod != nil {
userData = options.AuthenticateMethod(r)
if isUserdataNil(userData) {
if options.UnauthorizedMethod == nil {
s.log.Warn("Rejected authenticated request")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(Error{401, "Unauthorized"})
return
}

options.UnauthorizedMethod(w, r)
return
}
}

conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
s.log.Error("Error upgrading client for websocket connection: %s", err.Error())
return
}
endpointHandle(Request{
Params: ps,
log: s.log,
Params: ps,
UserData: userData,
log: s.log,
}, WSConn{
c: conn,
})
Expand Down

0 comments on commit 5a78f8d

Please # to comment.