Skip to content

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

Chore/user management v2 part 3b (#29656)

Joshen Lim17bd786cb4c4
diff --git a/apps/studio/components/interfaces/Auth/Users/UserHeader.tsx b/apps/studio/components/interfaces/Auth/Users/UserHeader.tsx
new file mode 100644
index 00000000000..f89dd866a12
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Users/UserHeader.tsx
@@ -0,0 +1,62 @@
+import { Copy } from 'lucide-react'
+
+import CopyButton from 'components/ui/CopyButton'
+import { User } from 'data/auth/users-query'
+import { cn } from 'ui'
+import { PANEL_PADDING } from './UserPanel'
+import { getDisplayName } from './Users.utils'
+
+export const UserHeader = ({ user }: { user: User }) => {
+ const displayName = getDisplayName(user)
+ const hasDisplayName = displayName !== '-'
+
+ const isPhoneAuth = user.phone !== null
+ const isAnonUser = user.is_anonymous
+
+ return (
+ <div className={cn(PANEL_PADDING)}>
+ {isPhoneAuth ? (
+ <div className="flex items-center gap-x-1">
+ <p>{user.phone}</p>
+ <CopyButton
+ iconOnly
+ type="text"
+ icon={<Copy />}
+ className="px-1"
+ text={user?.phone ?? ''}
+ />
+ </div>
+ ) : isAnonUser ? (
+ <>
+ <p>Anonymous user</p>
+ <div className="flex items-center gap-x-1">
+ <p className="text-foreground-light text-sm">{user.id}</p>
+ <CopyButton
+ iconOnly
+ type="text"
+ icon={<Copy />}
+ className="px-1"
+ text={user?.id ?? ''}
+ />
+ </div>
+ </>
+ ) : (
+ <>
+ {hasDisplayName && <p>{displayName}</p>}
+ <div className="flex items-center gap-x-1">
+ <p className={cn(hasDisplayName ? 'text-foreground-light text-sm' : 'text-foreground')}>
+ {user.email}
+ </p>
+ <CopyButton
+ iconOnly
+ type="text"
+ icon={<Copy />}
+ className="px-1"
+ text={user?.email ?? ''}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/Users/UserLogs.tsx b/apps/studio/components/interfaces/Auth/Users/UserLogs.tsx
new file mode 100644
index 00000000000..6e5636ca8a8
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Users/UserLogs.tsx
@@ -0,0 +1,157 @@
+import dayjs from 'dayjs'
+import { RefreshCw } from 'lucide-react'
+import Link from 'next/link'
+import { useEffect } from 'react'
+
+import { useParams } from 'common'
+import { LOGS_TABLES } from 'components/interfaces/Settings/Logs/Logs.constants'
+import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
+import { User } from 'data/auth/users-query'
+import useLogsPreview from 'hooks/analytics/useLogsPreview'
+import { Button, cn, CriticalIcon, Separator } from 'ui'
+import { Admonition } from 'ui-patterns'
+import { UserHeader } from './UserHeader'
+import { PANEL_PADDING } from './UserPanel'
+
+interface UserLogsProps {
+ user: User
+}
+
+export const UserLogs = ({ user }: UserLogsProps) => {
+ const { ref } = useParams()
+
+ const {
+ logData: authLogs,
+ isSuccess: isSuccessAuthLogs,
+ isLoading: isLoadingAuthLogs,
+ filters,
+ refresh,
+ setFilters,
+ } = useLogsPreview({
+ projectRef: ref as string,
+ table: LOGS_TABLES.auth,
+ filterOverride: { search_query: user.id },
+ limit: 5,
+ })
+
+ useEffect(() => {
+ if (user.id) setFilters({ ...filters, search_query: user.id })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [user.id])
+
+ return (
+ <div>
+ <UserHeader user={user} />
+
+ <Separator />
+
+ <div className={cn('flex flex-col gap-y-3', PANEL_PADDING)}>
+ <div>
+ <p>Authentication logs</p>
+ <p className="text-sm text-foreground-light">
+ Latest logs from authentication for this user in the past hour
+ </p>
+ </div>
+
+ {/* [Joshen] This whole thing here i reckon we can shift to a component, if in the future we wanna add more user logs */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center">
+ <Button
+ type={'status_code' in filters ? 'default' : 'secondary'}
+ className="rounded-r-none border-r-0"
+ disabled={isLoadingAuthLogs}
+ onClick={() => setFilters({ search_query: user.id })}
+ >
+ Show all
+ </Button>
+ <div className="border-button border border-l-0 py-3" />
+ <Button
+ type={'status_code' in filters ? 'secondary' : 'default'}
+ className="rounded-l-none border-l-0"
+ disabled={isLoadingAuthLogs}
+ onClick={() =>
+ setFilters({
+ search_query: user.id,
+ status_code: { client_error: true, server_error: true },
+ })
+ }
+ >
+ Error only
+ </Button>
+ </div>
+ <Button
+ type="default"
+ loading={isLoadingAuthLogs}
+ disabled={isLoadingAuthLogs}
+ icon={<RefreshCw />}
+ onClick={() => refresh()}
+ >
+ Refresh
+ </Button>
+ </div>
+
+ {isLoadingAuthLogs && !isSuccessAuthLogs ? (
+ <GenericSkeletonLoader />
+ ) : authLogs.length === 0 ? (
+ <Admonition
+ type="note"
+ title="No authentication logs available for this user"
+ description="Auth events such as logging in will be shown here"
+ />
+ ) : (
+ <div>
+ <div className="border border-b-0 rounded-t divide-y">
+ {authLogs.map((log) => {
+ const status = ((log.status ?? '-') as any).toString()
+ const formattedTime = dayjs(log.timestamp).format('DD MMM HH:mm:ss')
+ const is400 = status.startsWith('4')
+ const is500 = status.startsWith('5')
+
+ return (
+ <div
+ key={log.id}
+ className="flex items-center transition font-mono px-2 py-1.5 bg-surface-100 divide-x"
+ >
+ <p className="text-xs text-foreground-light min-w-[120px] w-[120px] px-1">
+ {formattedTime}
+ </p>
+ <div className="flex items-center text-xs text-foreground-light h-[22px] min-w-[70px] w-[70px] px-2">
+ <div
+ className={cn(
+ 'flex items-center justify-center gap-x-1',
+ !!log.status && 'border px-1 py-0.5 rounded',
+ is400
+ ? 'text-warning border-warning bg-warning-300'
+ : is500
+ ? 'text-destructive border-destructive bg-destructive-300'
+ : ''
+ )}
+ >
+ {(is400 || is500) && (
+ <CriticalIcon
+ hideBackground
+ className={cn(is400 && 'text-warning-600')}
+ />
+ )}
+ {status}
+ </div>
+ </div>
+ <p className="text-xs text-foreground-light px-2 truncate">{`${log.path} | ${log.msg}`}</p>
+ </div>
+ )
+ })}
+ </div>
+ <Button
+ block
+ asChild
+ type="outline"
+ className="transition rounded-t-none text-foreground-light hover:text-foreground"
+ >
+ <Link href={`/project/${ref}/logs/auth-logs?s=${user.id}`}>See more logs</Link>
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx b/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
index 66e2bf42511..0facbc23093 100644
--- a/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
@@ -14,7 +14,9 @@ import { useUserDeleteMutation } from 'data/auth/user-delete-mutation'
import { useUserResetPasswordMutation } from 'data/auth/user-reset-password-mutation'
import { useUserSendMagicLinkMutation } from 'data/auth/user-send-magic-link-mutation'
import { useUserSendOTPMutation } from 'data/auth/user-send-otp-mutation'
+import { useUserUpdateMutation } from 'data/auth/user-update-mutation'
import { User } from 'data/auth/users-query'
+import { useProjectApiQuery } from 'data/config/project-api-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { BASE_PATH } from 'lib/constants'
import { timeout } from 'lib/helpers'
@@ -22,11 +24,10 @@ import { Button, cn, Separator } from 'ui'
import { Admonition } from 'ui-patterns/admonition'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { PROVIDERS_SCHEMAS } from '../AuthProvidersFormValidation'
-import { PANEL_PADDING } from './UserPanel'
-import { getDisplayName, providerIconMap } from './Users.utils'
import { BanUserModal } from './BanUserModal'
-import { useUserUpdateMutation } from 'data/auth/user-update-mutation'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { UserHeader } from './UserHeader'
+import { PANEL_PADDING } from './UserPanel'
+import { providerIconMap } from './Users.utils'
const DATE_FORMAT = 'DD MMM, YYYY HH:mm'
const CONTAINER_CLASS = cn(
@@ -41,11 +42,8 @@ interface UserOverviewProps {
export const UserOverview = ({ user, onDeleteSuccess }: UserOverviewProps) => {
const { ref: projectRef } = useParams()
- const displayName = getDisplayName(user)
- const hasDisplayName = displayName !== '-'
const isEmailAuth = user.email !== null
const isPhoneAuth = user.phone !== null
- const isAnonUser = user.is_anonymous
const isBanned = user.banned_until !== null
const providers = (user.raw_app_meta_data?.providers ?? []).map((provider: string) => {
@@ -171,54 +169,7 @@ export const UserOverview = ({ user, onDeleteSuccess }: UserOverviewProps) => {
return (
<>
<div>
- <div className={cn(PANEL_PADDING)}>
- {isPhoneAuth ? (
- <div className="flex items-center gap-x-1">
- <p>{user.phone}</p>
- <CopyButton
- iconOnly
- type="text"
- icon={<Copy />}
- className="px-1"
- text={user?.phone ?? ''}
- />
- </div>
- ) : isAnonUser ? (
- <>
- <p>Anonymous user</p>
- <div className="flex items-center gap-x-1">
- <p className="text-foreground-light text-sm">{user.id}</p>
- <CopyButton
- iconOnly
- type="text"
- icon={<Copy />}
- className="px-1"
- text={user?.id ?? ''}
- />
- </div>
- </>
- ) : (
- <>
- {hasDisplayName && <p>{displayName}</p>}
- <div className="flex items-center gap-x-1">
- <p
- className={cn(
- hasDisplayName ? 'text-foreground-light text-sm' : 'text-foreground'
- )}
- >
- {user.email}
- </p>
- <CopyButton
- iconOnly
- type="text"
- icon={<Copy />}
- className="px-1"
- text={user?.email ?? ''}
- />
- </div>
- </>
- )}
- </div>
+ <UserHeader user={user} />
{isBanned ? (
<Admonition
diff --git a/apps/studio/components/interfaces/Auth/Users/UserPanel.tsx b/apps/studio/components/interfaces/Auth/Users/UserPanel.tsx
index f4b8e2ef67b..724ce52de08 100644
--- a/apps/studio/components/interfaces/Auth/Users/UserPanel.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UserPanel.tsx
@@ -13,6 +13,7 @@ import {
TabsTrigger_Shadcn_,
} from 'ui'
import { UserOverview } from './UserOverview'
+import { UserLogs } from './UserLogs'
interface UserPanelProps {
selectedUser?: User
@@ -22,7 +23,7 @@ interface UserPanelProps {
export const PANEL_PADDING = 'px-5 py-5'
export const UserPanel = ({ selectedUser, onClose }: UserPanelProps) => {
- const [view, setView] = useState<'overview' | 'raw'>('overview')
+ const [view, setView] = useState<'overview' | 'raw' | 'logs'>('overview')
return (
<>
@@ -46,6 +47,12 @@ export const UserPanel = ({ selectedUser, onClose }: UserPanelProps) => {
>
Overview
</TabsTrigger_Shadcn_>
+ <TabsTrigger_Shadcn_
+ value="logs"
+ className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"
+ >
+ Logs
+ </TabsTrigger_Shadcn_>
<TabsTrigger_Shadcn_
value="raw"
className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"
@@ -59,6 +66,12 @@ export const UserPanel = ({ selectedUser, onClose }: UserPanelProps) => {
>
{selectedUser && <UserOverview user={selectedUser} onDeleteSuccess={onClose} />}
</TabsContent_Shadcn_>
+ <TabsContent_Shadcn_
+ value="logs"
+ className={cn('mt-0 flex-grow min-h-0 overflow-y-auto')}
+ >
+ {selectedUser && <UserLogs user={selectedUser} />}
+ </TabsContent_Shadcn_>
<TabsContent_Shadcn_
value="raw"
className={cn('mt-0 flex-grow min-h-0 overflow-y-auto', PANEL_PADDING)}
diff --git a/apps/studio/components/interfaces/Auth/Users/Users.utils.tsx b/apps/studio/components/interfaces/Auth/Users/Users.utils.tsx
index bc5fbcdde4b..54ace3d0262 100644
--- a/apps/studio/components/interfaces/Auth/Users/Users.utils.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/Users.utils.tsx
@@ -117,6 +117,7 @@ const phoneProviders = providers.phone.map((x) => {
export function getDisplayName(user: User, fallback = '-'): string {
const {
+ custom_claims,
displayName,
display_name,
fullName,
@@ -132,14 +133,53 @@ export function getDisplayName(user: User, fallback = '-'): string {
first_name,
} = user.raw_user_meta_data ?? {}
- const last = familyName || family_name || surname || lastName || last_name
- const first = givenName || given_name || firstName || first_name
+ const {
+ displayName: ccDisplayName,
+ display_name: cc_display_name,
+ fullName: ccFullName,
+ full_name: cc_full_name,
+ familyName: ccFamilyName,
+ family_name: cc_family_name,
+ givenName: ccGivenName,
+ given_name: cc_given_name,
+ surname: ccSurname,
+ lastName: ccLastName,
+ last_name: cc_last_name,
+ firstName: ccFirstName,
+ first_name: cc_first_name,
+ } = custom_claims ?? {}
+
+ const last =
+ familyName ||
+ family_name ||
+ surname ||
+ lastName ||
+ last_name ||
+ ccFamilyName ||
+ cc_family_name ||
+ ccSurname ||
+ ccLastName ||
+ cc_last_name
+
+ const first =
+ givenName ||
+ given_name ||
+ firstName ||
+ first_name ||
+ ccGivenName ||
+ cc_given_name ||
+ ccFirstName ||
+ cc_first_name
return (
displayName ||
display_name ||
+ ccDisplayName ||
+ cc_display_name ||
fullName ||
full_name ||
+ ccFullName ||
+ cc_full_name ||
(first && last && `${first} ${last}`) ||
fallback
)
@@ -172,7 +212,7 @@ export function getAvatarUrl(user: User): string | undefined {
profileImageURL ||
profile_image_url) as string | undefined
- return SUPPORTED_CSP_AVATAR_URLS.some((x) => url?.startsWith(x)) ? url : undefined
+ return SUPPORTED_CSP_AVATAR_URLS.some((x) => (url ?? '').startsWith(x)) ? url : undefined
}
export const formatUserColumns = ({
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
index 946c9c32017..d8ffa517b39 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
@@ -135,7 +135,7 @@ const genWhereStatement = (table: LogsTableName, filters: Filters) => {
}
}
-export const genDefaultQuery = (table: LogsTableName, filters: Filters) => {
+export const genDefaultQuery = (table: LogsTableName, filters: Filters, limit: number = 100) => {
const where = genWhereStatement(table, filters)
const joins = genCrossJoinUnnests(table)
const orderBy = 'order by timestamp desc'
@@ -150,7 +150,7 @@ from edge_logs
${joins}
${where}
${orderBy}
-limit 100;
+limit ${limit};
`
}
return `select id, identifier, timestamp, event_message, request.method, request.path, response.status_code
@@ -158,7 +158,7 @@ limit 100;
${joins}
${where}
${orderBy}
- limit 100
+ limit ${limit}
`
case 'postgres_logs':
@@ -169,14 +169,14 @@ from postgres_logs
${joins}
${where}
${orderBy}
-limit 100
+limit ${limit}
`
}
return `select identifier, postgres_logs.timestamp, id, event_message, parsed.error_severity from ${table}
${joins}
${where}
${orderBy}
- limit 100
+ limit ${limit}
`
case 'function_logs':
@@ -184,7 +184,7 @@ limit 100
${joins}
${where}
${orderBy}
- limit 100
+ limit ${limit}
`
case 'auth_logs':
@@ -192,7 +192,7 @@ limit 100
${joins}
${where}
${orderBy}
- limit 100
+ limit ${limit}
`
case 'function_edge_logs':
@@ -200,16 +200,16 @@ limit 100
${joins}
${where}
${orderBy}
- limit 100
+ limit ${limit}
`
case 'supavisor_logs':
- return `select id, ${table}.timestamp, event_message from ${table} ${joins} ${where} ${orderBy} limit 100`
+ return `select id, ${table}.timestamp, event_message from ${table} ${joins} ${where} ${orderBy} limit ${limit}`
default:
return `select id, ${table}.timestamp, event_message from ${table}
${where}
${orderBy}
- limit 100
+ limit ${limit}
`
}
}
diff --git a/apps/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx b/apps/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
index acee66e0bd2..309954a6cb7 100644
--- a/apps/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
+++ b/apps/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
@@ -69,7 +69,7 @@ export const LogsPreviewer = ({
setFilters,
refresh,
setParams,
- } = useLogsPreview(projectRef as string, table, filterOverride)
+ } = useLogsPreview({ projectRef, table, filterOverride })
const { showUpgradePrompt, setShowUpgradePrompt } = useUpgradePrompt(
params.iso_timestamp_start as string
diff --git a/apps/studio/hooks/analytics/useLogsPreview.tsx b/apps/studio/hooks/analytics/useLogsPreview.tsx
index 30b14092d2d..e3b61acfeb3 100644
--- a/apps/studio/hooks/analytics/useLogsPreview.tsx
+++ b/apps/studio/hooks/analytics/useLogsPreview.tsx
@@ -31,6 +31,7 @@ interface LogsPreviewHook {
logData: LogData[]
error: string | Object | null
newCount: number
+ isSuccess: boolean
isLoading: boolean
isLoadingOlder: boolean
filters: Filters
@@ -42,11 +43,17 @@ interface LogsPreviewHook {
setFilters: (filters: Filters | ((previous: Filters) => Filters)) => void
setParams: Dispatch<SetStateAction<LogsEndpointParams>>
}
-function useLogsPreview(
- projectRef: string,
- table: LogsTableName,
+function useLogsPreview({
+ projectRef,
+ table,
+ filterOverride,
+ limit,
+}: {
+ projectRef: string
+ table: LogsTableName
filterOverride?: Filters
-): LogsPreviewHook {
+ limit?: number
+}): LogsPreviewHook {
const defaultHelper = getDefaultHelper(PREVIEWER_DATEPICKER_HELPERS)
const [latestRefresh, setLatestRefresh] = useState<string>(new Date().toISOString())
@@ -55,7 +62,7 @@ function useLogsPreview(
const [params, setParams] = useState<LogsEndpointParams>({
project: projectRef,
- sql: genDefaultQuery(table, filters),
+ sql: genDefaultQuery(table, filters, limit),
iso_timestamp_start: defaultHelper.calcFrom(),
iso_timestamp_end: defaultHelper.calcTo(),
})
@@ -68,10 +75,9 @@ function useLogsPreview(
refresh()
}, [JSON.stringify(filters)])
- const queryParamsKey = genQueryParams(params as any)
-
const {
data,
+ isSuccess,
isLoading,
isRefetching,
error: rqError,
@@ -79,7 +85,7 @@ function useLogsPreview(
isFetchingNextPage,
refetch,
} = useInfiniteQuery(
- ['projects', projectRef, 'logs', queryParamsKey],
+ ['projects', projectRef, 'logs', params],
({ signal, pageParam }) => {
const uri = `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${genQueryParams({
...params,
@@ -171,7 +177,7 @@ function useLogsPreview(
)
const refresh = async () => {
- const generatedSql = genDefaultQuery(table, filters)
+ const generatedSql = genDefaultQuery(table, filters, limit)
setParams((prev) => ({ ...prev, sql: generatedSql }))
setLatestRefresh(new Date().toISOString())
refreshEventChart()
@@ -207,6 +213,7 @@ function useLogsPreview(
return {
newCount,
logData,
+ isSuccess,
isLoading: isLoading || isRefetching,
isLoadingOlder: isFetchingNextPage,
error: error || eventChartError,