import { useState } from 'react' import { Badge, Card, CardContent, CardHeader, CardTitle, cn } from 'ui' import { AnonIcon, AuthenticatedIcon, ServiceRoleIcon } from './Icons' import { RoleImpersonationRadio } from './RoleImpersonationRadio' import { UserImpersonationSelector } from './UserImpersonationSelector' import { DocsButton } from '@/components/ui/DocsButton' import { DOCS_URL } from '@/lib/constants' import { PostgrestRole } from '@/lib/role-impersonation' import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state' export interface RoleImpersonationSelectorProps { header?: string serviceRoleLabel?: string disallowAuthenticatedOption?: boolean title?: string orientation?: 'horizontal' | 'vertical' } export const RoleImpersonationSelector = ({ header = 'Impersonate a database role', serviceRoleLabel = 'Postgres', disallowAuthenticatedOption = false, orientation = 'horizontal', }: RoleImpersonationSelectorProps) => { const isVertical = orientation === 'vertical' const state = useRoleImpersonationStateSnapshot() const [selectedOption, setSelectedOption] = useState(() => { if ( state.role?.type === 'postgrest' && (state.role.role === 'anon' || state.role.role === 'authenticated') ) { return state.role.role } return 'service_role' }) const isAuthenticatedOptionFullySelected = Boolean( selectedOption === 'authenticated' && state.role?.type === 'postgrest' && state.role.role === 'authenticated' && (('user' in state.role && state.role.user) || ('externalAuth' in state.role && state.role.externalAuth)) // Check for either auth type ) function onSelectedChange(value: PostgrestRole) { if (value === 'service_role') { // do not set a role for service role // as the default role is the "service role" state.setRole(undefined) } if (value === 'anon') { state.setRole({ type: 'postgrest', role: value, }) } setSelectedOption(value) } return ( {header}
{ // don't allow form submission e.preventDefault() }} >
} fullWidth={isVertical} /> } fullWidth={isVertical} /> {!disallowAuthenticatedOption && ( } fullWidth={isVertical} /> )}
{selectedOption === 'service_role' && (

Full admin access Default

The postgres role, which bypasses all Row Level Security (RLS) policies.

)} {selectedOption === 'anon' && (

For unauthenticated access

The anon role, which the API (PostgREST) uses when a user is not logged in.
Row Level Security (RLS) policies apply.

)} {selectedOption === 'authenticated' && (

For authenticated access

The authenticated role, which the API (PostgREST) uses when a user is logged in.
Row Level Security (RLS) policies apply.

)}
{selectedOption === 'authenticated' && ( )}
) }