-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.go
More file actions
36 lines (30 loc) · 989 Bytes
/
middleware.go
File metadata and controls
36 lines (30 loc) · 989 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main
import (
"context"
"net/http"
"strings"
)
func (tm *TaskManager) authorize(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
tm.counterRejection.WithLabelValues("missing_key").Inc()
return
}
if !strings.HasPrefix(authHeader, "Bearer ") {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
tm.counterRejection.WithLabelValues("invalid_header").Inc()
return
}
strKey := authHeader[7:]
verificationResult := tm.keyVerifier.Verify(strKey)
if !verificationResult.Success {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
tm.counterRejection.WithLabelValues(verificationResult.FailureReason).Inc()
return
}
ctx := context.WithValue(r.Context(), keyNameContextKey, verificationResult.KeyName)
next.ServeHTTP(w, r.WithContext(ctx))
})
}