Skip to content

Commit 3f11922

Browse files
Added query auth middleware
1 parent 6cec347 commit 3f11922

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

api/middleware/middleware.go

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,49 @@ func AuthenticationMiddleware(next http.HandlerFunc) http.HandlerFunc {
4242
/* authenticate the request through JWT */
4343
username, sessionID, err := token.ExtractDataFromRequest(r)
4444
if err != nil {
45-
zap.L().Error("Error during authentication",
45+
zap.L().Info("Error during authentication",
4646
zap.Error(err),
4747
)
48+
http.Error(w, "Authentication Failed", http.StatusInternalServerError)
49+
return
50+
}
51+
52+
/* set the header with the username */
53+
r.Header.Set("X-User", username)
54+
55+
/* pass username and sessionID as context */
56+
ctx := context.WithValue(r.Context(), ContextKeyUsername, username)
57+
ctx = context.WithValue(ctx, ContextKeySessionID, sessionID)
58+
59+
/* return the handler */
60+
next(w, r.WithContext(ctx))
61+
})
62+
}
63+
64+
/*
65+
authentication middleware for http requests with query
66+
return username and sessionID with context
67+
*/
68+
func AuthenticationQueryMiddleware(next http.HandlerFunc) http.HandlerFunc {
69+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
70+
/* get the HTTP query */
71+
query := r.URL.Query()
72+
73+
/* get the token query */
74+
tokenQ := query.Get("token")
75+
if tokenQ == "" {
76+
zap.L().Info("Query authentication without token value")
77+
http.Error(w, "Missing 'token' query parameter value", http.StatusBadRequest)
78+
return
79+
}
80+
81+
/* extract username and sessionID from the token */
82+
username, sessionID, err := token.GetDataFromJWT(tokenQ)
83+
if err != nil {
84+
zap.L().Info("Error during authentication",
85+
zap.Error(err),
86+
)
87+
http.Error(w, "Authentication Failed", http.StatusInternalServerError)
4888
return
4989
}
5090

0 commit comments

Comments
 (0)