import { keepPreviousData } from '@tanstack/react-query' import { useDebounce } from '@uidotdev/usehooks' import { ChevronsUpDownIcon, Loader2Icon, UserIcon, XIcon } from 'lucide-react' import { useMemo, useState } from 'react' import { toast } from 'sonner' import { Button, cn, Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, Input, InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, Popover, PopoverContent, PopoverTrigger, ToggleGroup, ToggleGroupItem, } from 'ui' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' import { InfoTooltip } from 'ui-patterns/info-tooltip' import { getDisplayName } from '../Auth/Users/Users.utils' import { AlertError } from '@/components/ui/AlertError' import { InlineLink } from '@/components/ui/InlineLink' import { User, useUsersInfiniteQuery } from '@/data/auth/users-infinite-query' import { useCustomAccessTokenHookDetails } from '@/hooks/misc/useCustomAccessTokenHookDetails' import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject' import { DOCS_URL } from '@/lib/constants' import type { StudioError } from '@/lib/errors/studio-errors' import type { RoleImpersonationController } from '@/state/role-impersonation-state' type AuthenticatorAssuranceLevels = 'aal1' | 'aal2' type UserSource = 'user' | 'external' type UserImpersonationSelectorProps = { state: RoleImpersonationController disabled?: boolean onUserImpersonationCleared?: () => void } export const UserImpersonationSelector = ({ state, disabled = false, onUserImpersonationCleared, }: UserImpersonationSelectorProps) => { const [searchText, setSearchText] = useState('') const [aal, setAal] = useState(() => state.role?.type === 'postgrest' && state.role.role === 'authenticated' ? (state.role.aal ?? 'aal1') : 'aal1' ) const [externalUserId, setExternalUserId] = useState('') const [additionalClaims, setAdditionalClaims] = useState('') const [isUserComboboxOpen, setIsUserComboboxOpen] = useState(false) const [selectedSource, setSelectedSource] = useState(() => state.role?.type === 'postgrest' && state.role.role === 'authenticated' && state.role.userType === 'external' ? 'external' : 'user' ) const [isImpersonateLoading, setIsImpersonateLoading] = useState(false) const debouncedSearchText = useDebounce(searchText, 300) const { data: project } = useSelectedProjectQuery() const { data, isSuccess, isPending: isLoading, isError, error, isFetching, isPlaceholderData, } = useUsersInfiniteQuery( { projectRef: project?.ref, connectionString: project?.connectionString, keywords: debouncedSearchText.trim().toLocaleLowerCase(), }, { placeholderData: keepPreviousData } ) const users = useMemo(() => data?.pages.flatMap((page) => page.result) ?? [], [data?.pages]) const isSearching = isPlaceholderData && isFetching const impersonatingUser = state.role?.type === 'postgrest' && state.role.role === 'authenticated' && state.role.userType === 'native' && state.role.user ? state.role.user : undefined const impersonatingExternalUser = state.role?.type === 'postgrest' && state.role.role === 'authenticated' && state.role.userType === 'external' && state.role.externalAuth ? state.role.externalAuth : undefined const displayName = impersonatingUser ? getDisplayName( impersonatingUser, impersonatingUser.email ?? impersonatingUser.phone ?? impersonatingUser.id ?? 'Unknown' ) : impersonatingExternalUser?.sub const isUserSelected = Boolean(displayName) const customAccessTokenHookDetails = useCustomAccessTokenHookDetails(project?.ref) async function impersonateUser(user: User) { setIsImpersonateLoading(true) if (customAccessTokenHookDetails?.type === 'https') { toast.info( 'Please note that HTTPS custom access token hooks are not yet supported in the dashboard.' ) } try { await state.setRole( { type: 'postgrest', role: 'authenticated', userType: 'native', user, aal, }, customAccessTokenHookDetails ) } catch (error) { toast.error(`Failed to impersonate user: ${(error as StudioError).message}`) } finally { setIsImpersonateLoading(false) } } async function impersonateExternalUser() { setIsImpersonateLoading(true) let parsedClaims = {} try { parsedClaims = additionalClaims ? JSON.parse(additionalClaims) : {} } catch { toast.error('Invalid JSON in additional claims') setIsImpersonateLoading(false) return } try { await state.setRole( { type: 'postgrest', role: 'authenticated', userType: 'external', externalAuth: { sub: externalUserId, additionalClaims: parsedClaims }, aal, }, customAccessTokenHookDetails ) } catch (error) { toast.error(`Failed to impersonate user: ${(error as StudioError).message}`) } finally { setIsImpersonateLoading(false) } } async function changeSelectedSource(value: UserSource) { if (!isUserSelected) { setSelectedSource(value) return } try { await state.setRole(undefined) setSelectedSource(value) onUserImpersonationCleared?.() } catch (error) { toast.error(`Failed to stop impersonating user: ${(error as StudioError).message}`) } } async function changeAal(value: AuthenticatorAssuranceLevels) { const previousAal = aal setAal(value) if ( state.role?.type !== 'postgrest' || state.role.role !== 'authenticated' || !isUserSelected ) { return } try { await state.setRole({ ...state.role, aal: value }, customAccessTokenHookDetails) } catch (error) { setAal(previousAal) toast.error(`Failed to update MFA assurance level: ${(error as StudioError).message}`) } } return (
Users Project users come from Supabase Auth. External users let you test RLS policies with providers such as Clerk or Auth0. } > { if (value === 'user' || value === 'external') void changeSelectedSource(value) }} variant="default" size="tiny" aria-label="User source" className="w-full" > Project External { await state.setRole(undefined) onUserImpersonationCleared?.() }} isUserComboboxOpen={isUserComboboxOpen} setIsUserComboboxOpen={setIsUserComboboxOpen} searchText={searchText} setSearchText={setSearchText} isLoading={isLoading} isSearching={isSearching} isError={isError} error={error} isSuccess={isSuccess} users={users} impersonateUser={impersonateUser} externalUserId={externalUserId} setExternalUserId={setExternalUserId} impersonateExternalUser={impersonateExternalUser} /> {selectedSource === 'external' && !isUserSelected && ( setAdditionalClaims(event.target.value)} /> )} MFA level AAL1 verifies users via standard login methods, while AAL2 adds a second authentication factor. If you are not using MFA, leave this on AAL1. Learn more in the{' '} MFA guide. } > { if (value === 'aal1' || value === 'aal2') void changeAal(value) }} variant="default" size="tiny" aria-label="MFA assurance level" className="w-full" > AAL1 AAL2
) } type ImpersonationControlProps = { selectedSource: UserSource displayName?: string isImpersonateLoading: boolean stopImpersonating: () => void isUserComboboxOpen: boolean setIsUserComboboxOpen: (open: boolean) => void searchText: string setSearchText: (value: string) => void isLoading: boolean isSearching: boolean isError: boolean error: StudioError | null isSuccess: boolean users: User[] impersonateUser: (user: User) => Promise externalUserId: string setExternalUserId: (value: string) => void impersonateExternalUser: () => Promise } const ImpersonationControl = ({ selectedSource, displayName, isImpersonateLoading, stopImpersonating, isUserComboboxOpen, setIsUserComboboxOpen, searchText, setSearchText, isLoading, isSearching, isError, error, isSuccess, users, impersonateUser, externalUserId, setExternalUserId, impersonateExternalUser, }: ImpersonationControlProps) => { if (displayName) { return (
{displayName}
) } if (selectedSource === 'external') { return ( setExternalUserId(event.target.value)} /> Apply ) } return ( {(isLoading || isSearching) && (
Loading users…
)} {isError && } {isSuccess && !isSearching && users.length === 0 && ( No users found )} {isSuccess && !isSearching && users.length > 0 && ( {users.map((user) => { const emailOrPhone = user.email || user.phone const userDisplayName = getDisplayName(user, '') return ( { void impersonateUser(user) setIsUserComboboxOpen(false) }} className="gap-2" > {emailOrPhone || userDisplayName || user.id} {userDisplayName && userDisplayName !== emailOrPhone && ( {userDisplayName} )} ) })} )}
) }