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 + `"}`)) }