-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
31 lines (28 loc) · 743 Bytes
/
auth.go
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
package middleware
import (
"net/http"
"strings"
"github.com/rs/zerolog/log"
)
// APIKeyAuth middleware authorizes request using API key authorization.
func APIKeyAuth(key string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if key == "" {
log.Error().Msg("API key is empty")
w.WriteHeader(http.StatusUnauthorized)
return
}
authorization := r.Header.Get("Authorization")
parts := strings.Fields(authorization)
if len(parts) != 2 {
w.WriteHeader(http.StatusUnauthorized)
return
}
authMethod := strings.ToLower(parts[0])
if authMethod != "apikey" || parts[1] != key {
w.WriteHeader(http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
})
}