'use client'; import { useState, useTransition } from 'react'; import { zodResolver } from '@hookform/resolvers/zod'; import { useQuery } from '@tanstack/react-query'; import { useForm } from 'react-hook-form'; import { useSupabase } from '@kit/supabase/hooks/use-supabase'; import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert'; import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from '@kit/ui/alert-dialog'; import { Button } from '@kit/ui/button'; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from '@kit/ui/form'; import { If } from '@kit/ui/if'; import { Input } from '@kit/ui/input'; import { LoadingOverlay } from '@kit/ui/loading-overlay'; import { impersonateUserAction } from '../lib/server/admin-server-actions'; import { ImpersonateUserSchema } from '../lib/server/schema/admin-actions.schema'; export function AdminImpersonateUserDialog( props: React.PropsWithChildren<{ userId: string; }>, ) { const form = useForm({ resolver: zodResolver(ImpersonateUserSchema), defaultValues: { userId: props.userId, confirmation: '', }, }); const [tokens, setTokens] = useState<{ accessToken: string; refreshToken: string; }>(); const [isPending, startTransition] = useTransition(); const [error, setError] = useState(null); if (tokens) { return ( <> Setting up your session... ); } return ( {props.children} Impersonate User Are you sure you want to impersonate this user? You will be logged in as this user. To stop impersonating, log out. NB: If the user has 2FA enabled, you will not be able to impersonate them.
{ startTransition(async () => { try { const result = await impersonateUserAction(data); setTokens(result); } catch { setError(true); } }); })} > Error Failed to impersonate user. Please check the logs to understand what went wrong. ( Type CONFIRM to confirm Are you sure you want to impersonate this user? )} /> Cancel
); } function ImpersonateUserAuthSetter({ tokens, }: React.PropsWithChildren<{ tokens: { accessToken: string; refreshToken: string; }; }>) { useSetSession(tokens); return Setting up your session...; } function useSetSession(tokens: { accessToken: string; refreshToken: string }) { const supabase = useSupabase(); return useQuery({ queryKey: ['impersonate-user', tokens.accessToken, tokens.refreshToken], gcTime: 0, queryFn: async () => { await supabase.auth.signOut(); await supabase.auth.setSession({ refresh_token: tokens.refreshToken, access_token: tokens.accessToken, }); // use a hard refresh to avoid hitting cached pages window.location.replace('/home'); }, }); }