Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add view data as user in auth users + refactor UI for role impersonation (#45358)

Joshen Lim87e8c59405ce
diff --git a/apps/studio/components/interfaces/Auth/RLSTester/useTestQueryRLS.ts b/apps/studio/components/interfaces/Auth/RLSTester/useTestQueryRLS.ts
index e90163582f2..a1e70a8d3c2 100644
--- a/apps/studio/components/interfaces/Auth/RLSTester/useTestQueryRLS.ts
+++ b/apps/studio/components/interfaces/Auth/RLSTester/useTestQueryRLS.ts
@@ -11,9 +11,9 @@ import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { wrapWithRoleImpersonation } from '@/lib/role-impersonation'
import {
- getImpersonatedUser,
isRoleImpersonationEnabled,
useGetImpersonatedRoleState,
+ useImpersonatedUser,
useRoleImpersonationStateSnapshot,
} from '@/state/role-impersonation-state'
@@ -35,6 +35,7 @@ export const useTestQueryRLS = () => {
const getImpersonatedRoleState = useGetImpersonatedRoleState()
const impersonatedRoleState = getImpersonatedRoleState()
+ const user = useImpersonatedUser()
const [isLoading, setIsLoading] = useState(false)
@@ -82,7 +83,6 @@ export const useTestQueryRLS = () => {
onParseQuery: (results?: ParseQueryResults) => void
}) => {
if (!project) return console.error('Project is required')
- const user = getImpersonatedUser(impersonatedRoleState)
if (option === 'authenticated' && !user) {
return toast('Select which user to test as before running the query')
diff --git a/apps/studio/components/interfaces/Auth/Users/Users.utils.tsx b/apps/studio/components/interfaces/Auth/Users/Users.utils.tsx
index be90587aeb4..8b332a47fbb 100644
--- a/apps/studio/components/interfaces/Auth/Users/Users.utils.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/Users.utils.tsx
@@ -1,4 +1,5 @@
import dayjs from 'dayjs'
+import { SqlEditor, TableEditor } from 'icons'
import { Copy, Trash, UserIcon } from 'lucide-react'
import { Column, useRowSelection } from 'react-data-grid'
import {
@@ -260,6 +261,7 @@ export const formatUserColumns = ({
visibleColumns = [],
setSortByValue,
onSelectDeleteUser,
+ onSelectImpersonateUser,
}: {
specificFilterColumn: string
columns: UsersTableColumn[]
@@ -268,6 +270,7 @@ export const formatUserColumns = ({
visibleColumns?: string[]
setSortByValue: (val: string) => void
onSelectDeleteUser: (user: User) => void
+ onSelectImpersonateUser: (user: User, destination: 'sql' | 'table-editor') => Promise<void>
}) => {
const columnOrder = config.map((c) => c.id) ?? columns.map((c) => c.id)
@@ -402,7 +405,33 @@ export const formatUserColumns = ({
<Copy size={12} />
<span>Copy {col.id === 'id' ? col.name : col.name.toLowerCase()}</span>
</ContextMenuItem_Shadcn_>
+
+ <ContextMenuSeparator_Shadcn_ />
+
+ <ContextMenuItem_Shadcn_
+ className="gap-x-2"
+ onFocusCapture={(e) => e.stopPropagation()}
+ onSelect={() => {
+ if (user) onSelectImpersonateUser(user, 'table-editor')
+ }}
+ >
+ <TableEditor size={12} />
+ <span>View data as user</span>
+ </ContextMenuItem_Shadcn_>
+
+ <ContextMenuItem_Shadcn_
+ className="gap-x-2"
+ onFocusCapture={(e) => e.stopPropagation()}
+ onSelect={() => {
+ if (user) onSelectImpersonateUser(user, 'sql')
+ }}
+ >
+ <SqlEditor size={12} />
+ <span>Run SQL as user</span>
+ </ContextMenuItem_Shadcn_>
+
<ContextMenuSeparator_Shadcn_ />
+
<ContextMenuItem_Shadcn_
className="gap-x-2"
onFocusCapture={(e) => e.stopPropagation()}
diff --git a/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx b/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx
index 5118c7f4413..66513b1fa94 100644
--- a/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx
@@ -1,5 +1,5 @@
-import { USER_SEARCH_INDEXES } from '@supabase/pg-meta'
import type { OptimizedSearchColumns } from '@supabase/pg-meta'
+import { USER_SEARCH_INDEXES } from '@supabase/pg-meta'
import { keepPreviousData, useQueryClient } from '@tanstack/react-query'
import AwesomeDebouncePromise from 'awesome-debounce-promise'
import { LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'
@@ -13,6 +13,7 @@ import {
X,
} from 'lucide-react'
import Link from 'next/link'
+import { useRouter } from 'next/router'
import { parseAsArrayOf, parseAsString, parseAsStringEnum, useQueryState } from 'nuqs'
import { UIEvent, useEffect, useMemo, useRef, useState } from 'react'
import DataGrid, { Column, DataGridHandle, Row } from 'react-data-grid'
@@ -74,6 +75,7 @@ import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganizati
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { PROJECT_STATUS } from '@/lib/constants/infrastructure'
import { cleanPointerEventsNoneOnBody, isAtBottom } from '@/lib/helpers'
+import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'
const SORT_BY_VALUE_COUNT_THRESHOLD = 10_000
const IMPROVED_SEARCH_COUNT_THRESHOLD = 10_000
@@ -87,6 +89,7 @@ order by timestamp desc
limit 100`
export const UsersV2 = () => {
+ const router = useRouter()
const queryClient = useQueryClient()
const { ref: projectRef } = useParams()
const {
@@ -95,6 +98,8 @@ export const UsersV2 = () => {
isError: isProjectError,
} = useSelectedProjectQuery()
const { data: selectedOrg } = useSelectedOrganizationQuery()
+ const roleImpersonationState = useRoleImpersonationStateSnapshot()
+
const gridRef = useRef<DataGridHandle>(null)
const xScroll = useRef<number>(0)
const { mutate: sendEvent } = useSendEventMutation()
@@ -356,6 +361,22 @@ export const UsersV2 = () => {
setSortByValue(value)
}
+ const onSelectImpersonateUser = async (user: User, destination: 'sql' | 'table-editor') => {
+ await roleImpersonationState.setRole({
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'native',
+ user,
+ aal: 'aal1',
+ })
+
+ if (destination === 'sql') {
+ router.push(`/project/${projectRef}/sql`)
+ } else {
+ router.push(`/project/${projectRef}/editor`)
+ }
+ }
+
const handleScroll = (event: UIEvent<HTMLDivElement>) => {
const isScrollingHorizontally = xScroll.current !== event.currentTarget.scrollLeft
xScroll.current = event.currentTarget.scrollLeft
@@ -446,6 +467,7 @@ export const UsersV2 = () => {
visibleColumns: selectedColumns,
setSortByValue: updateSortByValue,
onSelectDeleteUser: setSelectedUserToDelete,
+ onSelectImpersonateUser,
})
setColumns(columns)
if (columns.length < userTableColumns.length) {
@@ -685,6 +707,7 @@ export const UsersV2 = () => {
visibleColumns: value,
setSortByValue: updateSortByValue,
onSelectDeleteUser: setSelectedUserToDelete,
+ onSelectImpersonateUser,
})
setSelectedColumns(value)
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
index 15325768331..04123c4ebc8 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
@@ -450,7 +450,10 @@ export const EdgeFunctionTesterSheet = ({ visible, onClose }: EdgeFunctionTester
<RoleImpersonationStateContextProvider
key={`role-impersonation-state-${projectRef}`}
>
- <RoleImpersonationPopover disallowAuthenticatedOption />
+ <RoleImpersonationPopover
+ disallowAuthenticatedOption
+ header="Run edge function as a role"
+ />
</RoleImpersonationStateContextProvider>
<Button
type="primary"
diff --git a/apps/studio/components/interfaces/GraphQL/GraphiQL.tsx b/apps/studio/components/interfaces/GraphQL/GraphiQL.tsx
index f53ebd4eb84..5039cb49713 100644
--- a/apps/studio/components/interfaces/GraphQL/GraphiQL.tsx
+++ b/apps/studio/components/interfaces/GraphQL/GraphiQL.tsx
@@ -289,8 +289,8 @@ const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
className={
activeSecondaryEditor === 'variables' &&
editorToolsResize.hiddenElement !== 'second'
- ? 'active text-sm'
- : 'text-sm'
+ ? 'active !text-sm'
+ : '!text-sm'
}
onClick={handleToolsTabClick}
data-name="variables"
@@ -303,8 +303,8 @@ const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
className={
activeSecondaryEditor === 'headers' &&
editorToolsResize.hiddenElement !== 'second'
- ? 'active text-sm'
- : 'text-sm'
+ ? 'active !text-sm'
+ : '!text-sm'
}
onClick={handleToolsTabClick}
data-name="headers"
@@ -318,8 +318,8 @@ const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
className={
activeSecondaryEditor === 'role-impersonation' &&
editorToolsResize.hiddenElement !== 'second'
- ? 'active text-sm'
- : 'text-sm'
+ ? 'active !text-sm'
+ : '!text-sm'
}
onClick={handleToolsTabClick}
data-name="role-impersonation"
@@ -357,7 +357,10 @@ const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
<div ref={editorToolsResize.secondRef}>
<section
- className="graphiql-editor-tool text-sm"
+ className={cn(
+ 'graphiql-editor-tool !text-sm',
+ activeSecondaryEditor === 'role-impersonation' ? '!p-0' : '!pt-0'
+ )}
aria-label={activeSecondaryEditor === 'variables' ? 'Variables' : 'Headers'}
>
<VariableEditor
@@ -370,11 +373,11 @@ const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
{canReadJWTSecret && (
<div
className={cn(
- 'graphiql-editor px-1',
- activeSecondaryEditor !== 'role-impersonation' && 'hidden'
+ 'graphiql-editor',
+ activeSecondaryEditor !== 'role-impersonation' ? 'px-1 hidden' : ''
)}
>
- <RoleImpersonationSelector padded={false} />
+ <RoleImpersonationSelector />
</div>
)}
</section>
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
index 27e266b58fa..7e5df2e25bd 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
@@ -8,6 +8,7 @@ import type { User } from '@/data/auth/users-infinite-query'
import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'
export interface RoleImpersonationPopoverProps {
+ header?: string
serviceRoleLabel?: string
variant?: 'regular' | 'connected-on-right' | 'connected-on-left' | 'connected-on-both'
align?: 'center' | 'start' | 'end'
@@ -15,6 +16,7 @@ export interface RoleImpersonationPopoverProps {
}
export const RoleImpersonationPopover = ({
+ header,
serviceRoleLabel,
variant = 'regular',
align = 'end',
@@ -24,7 +26,7 @@ export const RoleImpersonationPopover = ({
const [isOpen, setIsOpen] = useState(false)
- const currentRole = state.role?.role ?? serviceRoleLabel ?? 'service role'
+ const currentRole = state.role?.role ?? serviceRoleLabel ?? 'postgres'
return (
<Popover_Shadcn_ open={isOpen} onOpenChange={setIsOpen}>
@@ -60,6 +62,7 @@ export const RoleImpersonationPopover = ({
</PopoverTrigger_Shadcn_>
<PopoverContent_Shadcn_ className="p-0 overflow-hidden w-min" side="bottom" align={align}>
<RoleImpersonationSelector
+ header={header}
serviceRoleLabel={serviceRoleLabel}
disallowAuthenticatedOption={disallowAuthenticatedOption}
/>
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx
index a4337904c4a..e8ba1f0fb31 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx
@@ -3,6 +3,7 @@ import { cn } from 'ui'
export interface RoleImpersonationRadioProps<T extends string> {
label?: string
+ description?: string
value: T
isSelected: boolean | 'partially'
onSelectedChange: (value: T) => void
@@ -11,6 +12,7 @@ export interface RoleImpersonationRadioProps<T extends string> {
export function RoleImpersonationRadio<T extends string>({
label,
+ description,
value,
isSelected,
onSelectedChange,
@@ -62,8 +64,10 @@ export function RoleImpersonationRadio<T extends string>({
isSelected && 'text-foreground'
)}
>
- {label ?? value} role
+ {label ?? value}
</span>
+
+ {description && <p className="text-foreground-lighter text-xs">{description}</p>}
</label>
)
}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
index 5e230e30658..07bb8d10bb5 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
@@ -185,12 +185,12 @@ export const UserImpersonationSelector = () => {
<>
<div className="px-5 py-3">
<p className="text-foreground text-sm">
- {displayName ? `Impersonating ${displayName}` : 'Impersonate a User'}
+ {displayName ? `Impersonating ${displayName}` : 'Impersonate a user'}
</p>
- <p className="text-sm text-foreground-light">
+ <p className="text-sm text-foreground-light mb-1">
{!impersonatingUser && !isExternalAuthImpersonating
- ? "Select a user to respect your database's Row-Level Security policies for that particular user."
- : "Results will respect your database's Row-Level Security policies for this user."}
+ ? "Select a user to respect your database's RLS policies for that particular user."
+ : "Results will respect your database's RLS policies for this user."}
</p>
{impersonatingUser && (
@@ -460,7 +460,7 @@ const BaseImpersonatingRow = ({
</div>
<Button type="default" onClick={onClick} disabled={isLoading} loading={isLoading}>
- {isImpersonating ? 'Stop impersonating' : 'Impersonate'}
+ {isImpersonating ? 'Stop' : 'Impersonate'}
</Button>
</div>
)
@@ -556,7 +556,7 @@ const UserRow = ({ user, onClick, isImpersonating = false, isLoading = false }:
</div>
<Button type="default" onClick={() => onClick(user)} disabled={isLoading} loading={isLoading}>
- {isImpersonating ? 'Stop impersonating' : 'Impersonate'}
+ {isImpersonating ? 'Stop' : 'Impersonate'}
</Button>
</div>
)
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
index 7a9544119df..ff2ece12ede 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
@@ -1,22 +1,24 @@
import { useState } from 'react'
-import { cn, DropdownMenuSeparator } from 'ui'
+import { Badge, Card, CardContent, CardHeader, CardTitle } 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
- padded?: boolean
disallowAuthenticatedOption?: boolean
title?: string
}
export const RoleImpersonationSelector = ({
- serviceRoleLabel,
- padded = true,
+ header = 'Impersonate a database role',
+ serviceRoleLabel = 'Postgres',
disallowAuthenticatedOption = false,
}: RoleImpersonationSelectorProps) => {
const state = useRoleImpersonationStateSnapshot()
@@ -58,10 +60,14 @@ export const RoleImpersonationSelector = ({
}
return (
- <>
- <div className={cn('flex flex-col gap-3', padded ? 'p-5' : 'pb-5')}>
- <p className="text-foreground text-base">Database role settings</p>
-
+ <Card className="border-none">
+ <CardHeader className="flex-row items-center justify-between py-3 space-y-0">
+ <CardTitle>{header}</CardTitle>
+ <DocsButton
+ href={`${DOCS_URL}/guides/database/postgres/row-level-security#authenticated-and-unauthenticated-roles`}
+ />
+ </CardHeader>
+ <CardContent className="flex flex-col gap-y-4">
<form
onSubmit={(e) => {
// don't allow form submission
@@ -74,24 +80,29 @@ export const RoleImpersonationSelector = ({
isSelected={selectedOption === 'service_role'}
onSelectedChange={onSelectedChange}
label={serviceRoleLabel}
+ description="Superuser"
icon={<ServiceRoleIcon isSelected={selectedOption === 'service_role'} />}
/>
<RoleImpersonationRadio
value="anon"
+ label="Anonymous"
isSelected={selectedOption === 'anon'}
onSelectedChange={onSelectedChange}
+ description="Not logged in"
icon={<AnonIcon isSelected={selectedOption === 'anon'} />}
/>
{!disallowAuthenticatedOption && (
<RoleImpersonationRadio
value="authenticated"
+ label="Authenticated"
isSelected={
selectedOption === 'authenticated' &&
(isAuthenticatedOptionFullySelected || 'partially')
}
onSelectedChange={onSelectedChange}
+ description="Specific logged in user"
icon={<AuthenticatedIcon isSelected={selectedOption === 'authenticated'} />}
/>
)}
@@ -99,38 +110,48 @@ export const RoleImpersonationSelector = ({
</form>
{selectedOption === 'service_role' && (
- <p className="text-foreground-light text-sm">
- <span className="text-foreground">The default Postgres/superuser role</span>
- <br />
- This has admin privileges and will bypass Row Level Security (RLS) policies.
- </p>
+ <div>
+ <p className="text-sm">
+ Full admin access
+ <Badge className="ml-2">Default</Badge>
+ </p>
+ <p className="text-foreground-light text-sm">
+ The <code className="text-code-inline">postgres</code> role, which bypasses all Row
+ Level Security (RLS) policies.
+ </p>
+ </div>
)}
{selectedOption === 'anon' && (
- <p className="text-foreground-light text-sm">
- <span className="text-foreground">For "anonymous access"</span>
- <br />
- This is the role which the API (PostgREST) will use when a user is not logged in. <br />
- It will respect Row Level Security (RLS) policies.
- </p>
+ <div>
+ <p className="text-sm">For unauthenticated access</p>
+ <p className="text-foreground-light text-sm">
+ The <code className="text-code-inline">anon</code> role, which the API (PostgREST)
+ uses when a user is not logged in.
+ <br />
+ Row Level Security (RLS) policies apply.
+ </p>
+ </div>
)}
{selectedOption === 'authenticated' && (
- <p className="text-foreground-light text-sm">
- <span className="text-foreground">For "authenticated access"</span>
- <br />
- This is the role which the API (PostgREST) will use when a user is logged in. <br />
- It will respect Row Level Security (RLS) policies.
- </p>
+ <div>
+ <p className="text-sm">For authenticated access</p>
+ <p className="text-foreground-light text-sm">
+ The <code className="text-code-inline">authenticated</code> role, which the API
+ (PostgREST) uses when a user is logged in.
+ <br />
+ Row Level Security (RLS) policies apply.
+ </p>
+ </div>
)}
- </div>
+ </CardContent>
{selectedOption === 'authenticated' && (
- <>
- <DropdownMenuSeparator />
+ <CardContent className="p-0">
<UserImpersonationSelector />
- </>
+ </CardContent>
)}
- </>
+ </Card>
)
}
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
index d3178712ab0..7d1b484838f 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
@@ -204,6 +204,7 @@ export const UtilityActions = ({
)}
<RoleImpersonationPopover
serviceRoleLabel="postgres"
+ header="Run SQL query as a role"
variant={IS_PLATFORM ? 'connected-on-both' : 'connected-on-right'}
/>
<SqlRunButton
diff --git a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
index 18e8d915ec0..733de5bfd7b 100644
--- a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
@@ -487,7 +487,7 @@ export const GridHeaderActions = ({ table, isRefetching }: GridHeaderActionsProp
</Popover_Shadcn_>
)}
- <RoleImpersonationPopover serviceRoleLabel="postgres" />
+ <RoleImpersonationPopover header="View data as a role" align="center" />
{doesHaveAutoGeneratedAPIDocs && (
<APIDocsButton section={['entities', table.name]} source="table_editor" />
diff --git a/apps/studio/components/layouts/Tabs/NewTab.tsx b/apps/studio/components/layouts/Tabs/NewTab.tsx
index e4c4a8450fe..63682f8cbd9 100644
--- a/apps/studio/components/layouts/Tabs/NewTab.tsx
+++ b/apps/studio/components/layouts/Tabs/NewTab.tsx
@@ -6,7 +6,12 @@ import Link from 'next/link'
import { useRouter } from 'next/router'
import { toast } from 'sonner'
import {
+ Badge,
Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
cn,
SQL_ICON,
Tabs_Shadcn_,
@@ -27,9 +32,17 @@ import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganizati
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useIsProtectedSchema } from '@/hooks/useProtectedSchemas'
import { useProfile } from '@/lib/profile'
+import {
+ useImpersonatedAAL,
+ useImpersonatedExternalAuth,
+ useImpersonatedUser,
+ useIsImpersonatingAnon,
+ useRoleImpersonationStateSnapshot,
+} from '@/state/role-impersonation-state'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
import { useTableEditorStateSnapshot } from '@/state/table-editor'
import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
+import { type ResponseError } from '@/types'
export function NewTab() {
const router = useRouter()
@@ -47,6 +60,12 @@ export function NewTab() {
const [templates] = partition(SQL_TEMPLATES, { type: 'template' })
const [quickstarts] = partition(SQL_TEMPLATES, { type: 'quickstart' })
+ const roleState = useRoleImpersonationStateSnapshot()
+ const impersonatingAnon = useIsImpersonatingAnon()
+ const impersonatedUser = useImpersonatedUser()
+ const impersonatedExternalUser = useImpersonatedExternalAuth()
+ const impersonatedAAL = useImpersonatedAAL()
+
const { mutate: sendEvent } = useSendEventMutation()
const { can: canCreateSQLSnippet } = useAsyncCheckPermissions(
PermissionAction.CREATE,
@@ -112,21 +131,54 @@ export function NewTab() {
})
router.push(`/project/${ref}/sql/${snippet.id}`)
- } catch (error: any) {
- toast.error(`Failed to create new query: ${error.message}`)
+ } catch (error) {
+ toast.error(`Failed to create new query: ${(error as ResponseError).message}`)
}
}
return (
<div className="bg-surface-100 h-full overflow-y-auto py-12">
<div className="mx-auto max-w-2xl flex flex-col gap-10 px-10">
+ {(!!impersonatedUser || !!impersonatedExternalUser || impersonatingAnon) && (
+ <Card>
+ <CardHeader className="py-2 px-3 flex-row items-center justify-between w-full space-y-0">
+ <CardTitle className="text-foreground-light">Currently impersonating as</CardTitle>
+ <Button
+ type="default"
+ className="font-sans"
+ onClick={() => roleState.setRole(undefined)}
+ >
+ Stop
+ </Button>
+ </CardHeader>
+ <CardContent className="py-2 px-3 text-sm flex items-center justify-between">
+ <div className="flex items-center gap-x-2">
+ {impersonatingAnon ? (
+ <p>Anonymous</p>
+ ) : (
+ <p>{impersonatedUser?.email ?? impersonatedExternalUser}</p>
+ )}
+ {impersonatedAAL && <Badge>{impersonatedAAL.toUpperCase()}</Badge>}
+ </div>
+ {impersonatingAnon && <p className="text-foreground-lighter">Not logged-in</p>}
+ {!!impersonatedUser && (
+ <p>
+ ID: <code className="text-code-inline">{impersonatedUser.id}</code>
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ )}
+
<div className="grid grid-cols-2 gap-4">
{actions.map((item, i) => (
<ActionCard key={`action-card-${i}`} {...item} />
))}
</div>
+
<RecentItems />
</div>
+
{editor === 'sql' && (
<div className="flex flex-col gap-4 mx-auto py-10">
<Tabs_Shadcn_ defaultValue="templates">
diff --git a/apps/studio/state/role-impersonation-state.tsx b/apps/studio/state/role-impersonation-state.tsx
index 5cc2b9f522f..67e48395435 100644
--- a/apps/studio/state/role-impersonation-state.tsx
+++ b/apps/studio/state/role-impersonation-state.tsx
@@ -126,7 +126,13 @@ export function isRoleImpersonationEnabled(impersonationRole?: ImpersonationRole
return impersonationRole?.type === 'postgrest'
}
-export const getImpersonatedUser = (state: RoleImpersonationState) => {
+export const useIsImpersonatingAnon = () => {
+ const state = useRoleImpersonationStateSnapshot()
+ return state.role?.type === 'postgrest' && state.role.role === 'anon'
+}
+
+export const useImpersonatedUser = () => {
+ const state = useRoleImpersonationStateSnapshot()
return state.role?.type === 'postgrest' &&
state.role.role === 'authenticated' &&
state.role.userType === 'native'
@@ -134,7 +140,8 @@ export const getImpersonatedUser = (state: RoleImpersonationState) => {
: undefined
}
-export const getImpersonatedExternalAuth = (state: RoleImpersonationState) => {
+export const useImpersonatedExternalAuth = () => {
+ const state = useRoleImpersonationStateSnapshot()
return state.role?.type === 'postgrest' &&
state.role.role === 'authenticated' &&
state.role.userType === 'external' &&
@@ -142,3 +149,13 @@ export const getImpersonatedExternalAuth = (state: RoleImpersonationState) => {
? state.role.externalAuth.sub
: undefined
}
+
+export const useImpersonatedAAL = () => {
+ const state = useRoleImpersonationStateSnapshot()
+ return (
+ state.role?.type === 'postgrest' &&
+ state.role.role === 'authenticated' &&
+ state.role.userType === 'external' &&
+ state.role.aal
+ )
+}