AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend): enable admin impersonation for server-side rendered requests (#11343)
Zamil Majdy711c4396423d
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/useAdminImpersonation.ts b/autogpt_platform/frontend/src/app/(platform)/admin/components/useAdminImpersonation.tsindex 2edcdc9e0f..330510be49 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/useAdminImpersonation.ts+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/useAdminImpersonation.ts@@ -1,8 +1,7 @@"use client";import { useState, useCallback } from "react";-import { environment } from "@/services/environment";-import { IMPERSONATION_STORAGE_KEY } from "@/lib/constants";+import { ImpersonationState } from "@/lib/impersonation";import { useToast } from "@/components/molecules/Toast/use-toast";interface AdminImpersonationState {@@ -18,22 +17,9 @@ interface AdminImpersonationActions {type AdminImpersonationHook = AdminImpersonationState &AdminImpersonationActions;-function getInitialImpersonationState(): string | null {- if (!environment.isClientSide()) {- return null;- }-- try {- return sessionStorage.getItem(IMPERSONATION_STORAGE_KEY);- } catch (error) {- console.error("Failed to read initial impersonation state:", error);- return null;- }-}-export function useAdminImpersonation(): AdminImpersonationHook {const [impersonatedUserId, setImpersonatedUserId] = useState<string | null>(- getInitialImpersonationState,+ ImpersonationState.get,);const { toast } = useToast();@@ -49,39 +35,34 @@ export function useAdminImpersonation(): AdminImpersonationHook {return;}- if (environment.isClientSide()) {- try {- sessionStorage.setItem(IMPERSONATION_STORAGE_KEY, userId);- setImpersonatedUserId(userId);- window.location.reload();- } catch (error) {- console.error("Failed to start impersonation:", error);- toast({- title: "Failed to start impersonation",- description:- error instanceof Error ? error.message : "Unknown error",- variant: "destructive",- });- }- }- },- [toast],- );-- const stopImpersonating = useCallback(() => {- if (environment.isClientSide()) {try {- sessionStorage.removeItem(IMPERSONATION_STORAGE_KEY);- setImpersonatedUserId(null);+ ImpersonationState.set(userId);+ setImpersonatedUserId(userId);window.location.reload();} catch (error) {- console.error("Failed to stop impersonation:", error);+ console.error("Failed to start impersonation:", error);toast({- title: "Failed to stop impersonation",+ title: "Failed to start impersonation",description: error instanceof Error ? error.message : "Unknown error",variant: "destructive",});}+ },+ [toast],+ );++ const stopImpersonating = useCallback(() => {+ try {+ ImpersonationState.clear();+ setImpersonatedUserId(null);+ window.location.reload();+ } catch (error) {+ console.error("Failed to stop impersonation:", error);+ toast({+ title: "Failed to stop impersonation",+ description: error instanceof Error ? error.message : "Unknown error",+ variant: "destructive",+ });}}, [toast]);diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.tsindex bec9c1749c..0955c0a6be 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts@@ -3,10 +3,8 @@ import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";import { createBrowserClient } from "@supabase/ssr";import type { SupabaseClient } from "@supabase/supabase-js";import { Key, storage } from "@/services/storage/local-storage";-import {- IMPERSONATION_HEADER_NAME,- IMPERSONATION_STORAGE_KEY,-} from "@/lib/constants";+import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";+import { ImpersonationState } from "@/lib/impersonation";import * as Sentry from "@sentry/nextjs";import type {AddUserCreditsResponse,@@ -1023,20 +1021,9 @@ export default class BackendAPI {"Content-Type": "application/json",};- if (environment.isClientSide()) {- try {- const impersonatedUserId = sessionStorage.getItem(- IMPERSONATION_STORAGE_KEY,- );- if (impersonatedUserId) {- headers[IMPERSONATION_HEADER_NAME] = impersonatedUserId;- }- } catch (_error) {- console.error(- "Admin impersonation: Failed to access sessionStorage:",- _error,- );- }+ const impersonatedUserId = ImpersonationState.get();+ if (impersonatedUserId) {+ headers[IMPERSONATION_HEADER_NAME] = impersonatedUserId;}const response = await fetch(url, {@@ -1062,7 +1049,22 @@ export default class BackendAPI {"./helpers");const url = buildServerUrl(path);- return await makeAuthenticatedRequest(method, url, payload);++ // For server-side requests, try to read impersonation from cookies+ const impersonationUserId = await ImpersonationState.getServerSide();+ const fakeRequest = impersonationUserId+ ? new Request(url, {+ headers: { "X-Act-As-User-Id": impersonationUserId },+ })+ : undefined;++ return await makeAuthenticatedRequest(+ method,+ url,+ payload,+ "application/json",+ fakeRequest,+ );}////////////////////////////////////////diff --git a/autogpt_platform/frontend/src/lib/impersonation.ts b/autogpt_platform/frontend/src/lib/impersonation.tsnew file mode 100644index 0000000000..47c92b89ed--- /dev/null+++ b/autogpt_platform/frontend/src/lib/impersonation.ts@@ -0,0 +1,167 @@+/**+ * Centralized admin impersonation utilities+ * Handles reading, writing, and managing impersonation state across tabs and server/client contexts+ */++import { IMPERSONATION_STORAGE_KEY } from "./constants";+import { environment } from "@/services/environment";++const COOKIE_NAME = "admin-impersonate-user-id";++/**+ * Cookie utility functions+ */+export const ImpersonationCookie = {+ /**+ * Set impersonation cookie with proper security attributes+ */+ set(userId: string): void {+ if (!environment.isClientSide()) return;++ const encodedUserId = encodeURIComponent(userId);+ document.cookie = `${COOKIE_NAME}=${encodedUserId}; path=/; SameSite=Lax; Secure`;+ },++ /**+ * Clear impersonation cookie+ */+ clear(): void {+ if (!environment.isClientSide()) return;++ document.cookie = `${COOKIE_NAME}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax; Secure`;+ },++ /**+ * Read impersonation cookie (client-side)+ */+ get(): string | null {+ if (!environment.isClientSide()) return null;++ try {+ const cookieValue = document.cookie+ .split("; ")+ .find((row) => row.startsWith(`${COOKIE_NAME}=`))+ ?.split("=")[1];++ return cookieValue ? decodeURIComponent(cookieValue) : null;+ } catch (error) {+ console.debug("Failed to read impersonation cookie:", error);+ return null;+ }+ },++ /**+ * Read impersonation cookie (server-side using Next.js cookies API)+ */+ async getServerSide(): Promise<string | null> {+ if (environment.isClientSide()) return null;++ try {+ const { cookies } = await import("next/headers");+ const cookieStore = await cookies();+ const impersonationCookie = cookieStore.get(COOKIE_NAME);+ return impersonationCookie?.value || null;+ } catch (error) {+ console.debug("Could not access server-side cookies:", error);+ return null;+ }+ },+};++/**+ * SessionStorage utility functions+ */+export const ImpersonationSession = {+ /**+ * Set impersonation in sessionStorage+ */+ set(userId: string): void {+ if (!environment.isClientSide()) return;++ try {+ sessionStorage.setItem(IMPERSONATION_STORAGE_KEY, userId);+ } catch (error) {+ console.error("Failed to set impersonation in sessionStorage:", error);+ }+ },++ /**+ * Get impersonation from sessionStorage+ */+ get(): string | null {+ if (!environment.isClientSide()) return null;++ try {+ return sessionStorage.getItem(IMPERSONATION_STORAGE_KEY);+ } catch (error) {+ console.error("Failed to read impersonation from sessionStorage:", error);+ return null;+ }+ },++ /**+ * Clear impersonation from sessionStorage+ */+ clear(): void {+ if (!environment.isClientSide()) return;++ try {+ sessionStorage.removeItem(IMPERSONATION_STORAGE_KEY);+ } catch (error) {+ console.error(+ "Failed to clear impersonation from sessionStorage:",+ error,+ );+ }+ },+};++/**+ * Main impersonation state management+ */+export const ImpersonationState = {+ /**+ * Get current impersonation user ID with cross-tab fallback+ * Checks sessionStorage first, then falls back to cookie for cross-tab support+ */+ get(): string | null {+ // First check sessionStorage (same tab)+ const sessionValue = ImpersonationSession.get();+ if (sessionValue) {+ return sessionValue;+ }++ // Fallback to cookie (cross-tab support)+ const cookieValue = ImpersonationCookie.get();+ if (cookieValue) {+ // Sync back to sessionStorage for consistency+ ImpersonationSession.set(cookieValue);+ return cookieValue;+ }++ return null;+ },++ /**+ * Set impersonation user ID in both sessionStorage and cookie+ */+ set(userId: string): void {+ ImpersonationSession.set(userId);+ ImpersonationCookie.set(userId);+ },++ /**+ * Clear impersonation from both sessionStorage and cookie+ */+ clear(): void {+ ImpersonationSession.clear();+ ImpersonationCookie.clear();+ },++ /**+ * Get impersonation user ID for server-side requests+ */+ async getServerSide(): Promise<string | null> {+ return await ImpersonationCookie.getServerSide();+ },+};