package middleware import ( "context" "net/http" "strings" "api_es/internal/utils" ) type contextKey string const ( UserIDKey contextKey = "userID" UserEmailKey contextKey = "userEmail" UserRoleKey contextKey = "userRole" ) func AuthMiddleware(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 required", http.StatusUnauthorized) return } tokenString := strings.Replace(authHeader, "Bearer ", "", 1) if tokenString == "" { http.Error(w, "Invalid token", http.StatusUnauthorized) return } // Здесь нужно использовать ваш JWT утилити jwtUtil := utils.NewJWTUtil("your-secret-key") claims, err := jwtUtil.ValidateToken(tokenString) if err != nil { http.Error(w, "Invalid token", http.StatusUnauthorized) return } ctx := context.WithValue(r.Context(), UserIDKey, claims.UserID) ctx = context.WithValue(ctx, UserEmailKey, claims.Email) ctx = context.WithValue(ctx, UserRoleKey, claims.Role) next.ServeHTTP(w, r.WithContext(ctx)) }) } func AdminMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { role, ok := r.Context().Value(UserRoleKey).(string) if !ok || role != "admin" { http.Error(w, "Admin access required", http.StatusForbidden) return } next.ServeHTTP(w, r) }) }