core/internal/middleware/admin_auth.go (view raw)
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 middleware import ( "context" "net/http" "strings" "github.com/wbrijesh/identity/internal/auth" ) func AdminAuthMiddleware(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, "Authorization header is required", http.StatusUnauthorized) return } bearerToken := strings.Split(authHeader, " ") if len(bearerToken) != 2 || strings.ToLower(bearerToken[0]) != "bearer" { http.Error(w, "Invalid authorization header format", http.StatusUnauthorized) return } tokenString := bearerToken[1] adminID, err := auth.ValidateAdminJWT(tokenString) if err != nil { http.Error(w, "Invalid or expired token", http.StatusUnauthorized) return } // Add the admin to the request context ctx := context.WithValue(r.Context(), "adminID", adminID) next.ServeHTTP(w, r.WithContext(ctx)) }) } |