Files
Arkie-Library-Backend/internal/handlers/middleware.go
2026-05-16 00:18:22 +08:00

42 lines
955 B
Go

package handlers
import (
"context"
"net/http"
"strings"
"github.com/arkie/ark-database/internal/auth"
)
type adminCtxKey string
const adminIDKey adminCtxKey = "admin_id"
func AdminAuth(secret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := r.Header.Get("Authorization")
if !strings.HasPrefix(strings.ToLower(h), "bearer ") {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
tok := strings.TrimSpace(h[7:])
claims, err := auth.ParseAdmin(secret, tok)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), adminIDKey, claims.AdminID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func adminIDFrom(r *http.Request) int {
v := r.Context().Value(adminIDKey)
if v == nil {
return 0
}
return v.(int)
}