You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

38 lines
1.0 KiB

package auth
import (
"context"
"net/http"
"strings"
)
type contextKey string
const UsernameKey contextKey = "username"
func AdminOnly(secret []byte) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Authorization")
if header == "" || !strings.HasPrefix(header, "Bearer ") {
writeUnauthorized(w, "missing authorization header")
return
}
tokenStr := strings.TrimPrefix(header, "Bearer ")
claims, err := ValidateToken(tokenStr, secret)
if err != nil {
writeUnauthorized(w, "invalid or expired token")
return
}
sub, _ := (*claims)["sub"].(string)
ctx := context.WithValue(r.Context(), UsernameKey, sub)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func writeUnauthorized(w http.ResponseWriter, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"` + msg + `"}`))
}