The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/user management v2 panel (#29468)
Joshen Lim6af9ff606199
diff --git a/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx b/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsxindex 8af5b8941b0..02d85706700 100644--- a/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx+++ b/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx@@ -1,7 +1,7 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { Check, ChevronUp, ExternalLink } from 'lucide-react'-import { useState } from 'react'+import { useEffect, useRef, useState } from 'react'import ReactMarkdown from 'react-markdown'import { toast } from 'sonner'@@ -12,6 +12,7 @@ import { useProjectApiQuery } from 'data/config/project-api-query'import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { BASE_PATH } from 'lib/constants'+import Link from 'next/link'import {Alert,Alert_Shadcn_,@@ -26,7 +27,6 @@ import {import { ProviderCollapsibleClasses } from './AuthProvidersForm.constants'import type { Provider } from './AuthProvidersForm.types'import FormField from './FormField'-import Link from 'next/link'export interface ProviderFormProps {config: components['schemas']['GoTrueConfigResponse']@@ -34,8 +34,9 @@ export interface ProviderFormProps {}const ProviderForm = ({ config, provider }: ProviderFormProps) => {+ const ref = useRef<HTMLButtonElement>(null)const [open, setOpen] = useState(false)- const { ref: projectRef } = useParams()+ const { ref: projectRef, provider: urlProvider } = useParams()const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()const doubleNegativeKeys = ['MAILER_AUTOCONFIRM', 'SMS_AUTOCONFIRM']@@ -182,6 +183,14 @@ const ProviderForm = ({ config, provider }: ProviderFormProps) => {)}+ useEffect(() => {+ if (urlProvider === provider.title.toLowerCase()) {+ setOpen(true)+ ref.current?.scrollIntoView({ behavior: 'smooth', block: 'start' })+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [urlProvider])+return (<Collapsibleopen={open}@@ -190,6 +199,7 @@ const ProviderForm = ({ config, provider }: ProviderFormProps) => {><Collapsible.Trigger asChild><button+ ref={ref}type="button"className="group flex w-full items-center justify-between rounded py-3 px-6 text-foreground">diff --git a/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx b/apps/studio/components/interfaces/Auth/Users/UserOverview.tsxnew file mode 100644index 00000000000..f5de6ec02d4--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx@@ -0,0 +1,500 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import dayjs from 'dayjs'+import { Check, Copy, Mail, ShieldOff, Trash, X } from 'lucide-react'+import Link from 'next/link'+import { ComponentProps, ReactNode, useEffect, useState } from 'react'+import { toast } from 'sonner'++import { useParams } from 'common'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import CopyButton from 'components/ui/CopyButton'+import { useAuthConfigQuery } from 'data/auth/auth-config-query'+import { useUserDeleteMFAFactorsMutation } from 'data/auth/user-delete-mfa-factors-mutation'+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 { User } from 'data/auth/users-query'+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { BASE_PATH } from 'lib/constants'+import { timeout } from 'lib/helpers'+import { Admonition, Button, cn, Separator } from 'ui'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { PROVIDERS_SCHEMAS } from '../AuthProvidersFormValidation'+import { PANEL_PADDING } from './UserPanel'+import { getDisplayName, providerIconMap } from './Users.utils'++const DATE_FORMAT = 'DD MMM, YYYY HH:mm'+const CONTAINER_CLASS = cn(+ 'bg-surface-100 border-default text-foreground flex items-center justify-between',+ 'gap-x-4 border px-5 py-4 text-sm first:rounded-tr first:rounded-tl last:rounded-br last:rounded-bl'+)++interface UserOverviewProps {+ user: User+ onDeleteSuccess: () => void+}++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 providers = (user.raw_app_meta_data?.providers ?? []).map((provider) => {+ return {+ name: provider,+ icon:+ provider === 'email'+ ? `${BASE_PATH}/img/icons/email-icon2.svg`+ : providerIconMap[provider]+ ? `${BASE_PATH}/img/icons/${providerIconMap[provider]}.svg`+ : undefined,+ }+ })++ const canSendMagicLink = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_magic_link')+ const canSendRecovery = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_recovery')+ const canSendOtp = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_otp')+ const canRemoveUser = useCheckPermissions(PermissionAction.TENANT_SQL_DELETE, 'auth.users')+ const canRemoveMFAFactors = useCheckPermissions(+ PermissionAction.TENANT_SQL_DELETE,+ 'auth.mfa_factors'+ )++ const [successAction, setSuccessAction] = useState<+ 'send_magic_link' | 'send_recovery' | 'send_otp'+ >()+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)+ const [isDeleteFactorsModalOpen, setIsDeleteFactorsModalOpen] = useState(false)++ const { data } = useAuthConfigQuery({ projectRef })+ const mailerOtpExpiry = data?.MAILER_OTP_EXP ?? 0+ const minutes = Math.floor(mailerOtpExpiry / 60)+ const seconds = Math.floor(mailerOtpExpiry % 60)+ const formattedExpiry = `${mailerOtpExpiry > 60 ? `${minutes} minute${minutes > 1 ? 's' : ''} ${seconds > 0 ? 'and' : ''} ` : ''}${seconds > 0 ? `${seconds} second${seconds > 1 ? 's' : ''}` : ''}`++ const { mutate: resetPassword, isLoading: isResettingPassword } = useUserResetPasswordMutation({+ onSuccess: (_, vars) => {+ setSuccessAction('send_recovery')+ toast.success(`Sent password recovery to ${vars.user.email}`)+ },+ onError: (err) => {+ toast.error(`Failed to send password recovery: ${err.message}`)+ },+ })+ const { mutate: sendMagicLink, isLoading: isSendingMagicLink } = useUserSendMagicLinkMutation({+ onSuccess: (_, vars) => {+ setSuccessAction('send_magic_link')+ toast.success(`Sent magic link to ${vars.user.email}`)+ },+ onError: (err) => {+ toast.error(`Failed to send magic link: ${err.message}`)+ },+ })+ const { mutate: sendOTP, isLoading: isSendingOTP } = useUserSendOTPMutation({+ onSuccess: (_, vars) => {+ setSuccessAction('send_otp')+ toast.success(`Sent OTP to ${vars.user.phone}`)+ },+ onError: (err) => {+ toast.error(`Failed to send OTP: ${err.message}`)+ },+ })+ const { mutate: deleteUser } = useUserDeleteMutation({+ onSuccess: () => {+ toast.success(`Successfully deleted ${user?.email}`)+ setIsDeleteModalOpen(false)+ onDeleteSuccess()+ },+ })+ const { mutate: deleteUserMFAFactors } = useUserDeleteMFAFactorsMutation({+ onSuccess: () => {+ toast.success("Successfully deleted the user's factors")+ setIsDeleteFactorsModalOpen(false)+ },+ })++ const handleDelete = async () => {+ await timeout(200)+ if (!projectRef) return console.error('Project ref is required')+ deleteUser({ projectRef, user })+ }++ const handleDeleteFactors = async () => {+ await timeout(200)+ if (!projectRef) return console.error('Project ref is required')+ deleteUserMFAFactors({ projectRef, userId: user.id as string })+ }++ useEffect(() => {+ if (successAction !== undefined) {+ const timer = setTimeout(() => setSuccessAction(undefined), 5000)+ return () => clearTimeout(timer)+ }+ }, [successAction])++ 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>++ {!!user.banned_until ? (+ <Admonition+ type="warning"+ label={`User banned until ${dayjs(user.banned_until).format(DATE_FORMAT)}`}+ className="border-r-0 border-l-0 rounded-none -mt-px [&_svg]:ml-0.5 mb-0"+ />+ ) : (+ <Separator />+ )}++ <div className={cn('flex flex-col', PANEL_PADDING)}>+ <RowData property="User UID" value={user.id} />+ <RowData+ property="Created at"+ value={user.created_at ? dayjs(user.created_at).format(DATE_FORMAT) : undefined}+ />+ <RowData+ property="Updated at"+ value={user.updated_at ? dayjs(user.updated_at).format(DATE_FORMAT) : undefined}+ />+ <RowData property="Invited at" value={user.invited_at} />+ <RowData property="Confirmation sent at" value={user.confirmation_sent_at} />+ <RowData+ property="Confirmed at"+ value={user.confirmed_at ? dayjs(user.confirmed_at).format(DATE_FORMAT) : undefined}+ />+ <RowData+ property="Last signed in"+ value={+ user.last_sign_in_at ? dayjs(user.last_sign_in_at).format(DATE_FORMAT) : undefined+ }+ />+ <RowData property="SSO" value={user.is_sso_user} />+ </div>++ <div className={cn('flex flex-col !pt-0', PANEL_PADDING)}>+ <p>Provider Information</p>+ <p className="text-sm text-foreground-light">The user has the following providers</p>+ </div>++ <div className={cn('flex flex-col -space-y-1 !pt-0', PANEL_PADDING)}>+ {providers.map((provider) => {+ const providerMeta = PROVIDERS_SCHEMAS.find(+ (x) => x.title.toLowerCase() === provider.name+ )+ const enabledProperty = Object.keys(providerMeta?.properties ?? {}).find((x) =>+ x.toLowerCase().endsWith('_enabled')+ )+ const providerName =+ provider.name === 'email' ? 'email' : providerMeta?.title ?? provider.name+ const isActive = data?.[enabledProperty as keyof typeof data] ?? false++ return (+ <div key={provider.name} className={cn(CONTAINER_CLASS, 'items-start justify-start')}>+ {provider.icon && (+ <img+ width={16}+ src={provider.icon}+ alt={`${provider.name} auth icon`}+ className={cn('mt-1.5', provider.name === 'github' ? 'dark:invert' : '')}+ />+ )}+ <div className="flex-grow mt-0.5">+ <p className="capitalize">{provider.name}</p>+ <p className="text-xs text-foreground-light">+ Signed in with a {providerName} account via OAuth+ </p>+ <Button asChild type="default" className="mt-2">+ <Link href={`/project/${projectRef}/auth/providers?provider=${provider.name}`}>+ Configure {providerName} provider+ </Link>+ </Button>+ </div>+ {isActive ? (+ <div className="flex items-center gap-1 rounded-full border border-brand-400 bg-brand-200 py-1 px-1 text-xs text-brand">+ <span className="rounded-full bg-brand p-0.5 text-xs text-brand-200">+ <Check strokeWidth={2} size={12} />+ </span>+ <span className="px-1">Enabled</span>+ </div>+ ) : (+ <div className="rounded-md border border-strong bg-surface-100 py-1 px-3 text-xs text-foreground-lighter">+ Disabled+ </div>+ )}+ </div>+ )+ })}+ </div>++ <Separator />++ <div className={cn('flex flex-col -space-y-1', PANEL_PADDING)}>+ {isEmailAuth && (+ <>+ <RowAction+ title="Reset password"+ description="Send a password recovery email to the user"+ button={{+ icon: <Mail />,+ text: 'Send password recovery',+ isLoading: isResettingPassword,+ disabled: !canSendRecovery,+ onClick: () => {+ if (projectRef) resetPassword({ projectRef, user })+ },+ }}+ success={+ successAction === 'send_recovery'+ ? {+ title: 'Password recovery sent',+ description: `The link in the email is valid for ${formattedExpiry}`,+ }+ : undefined+ }+ />+ <RowAction+ title="Send magic link"+ description="Passwordless login via email for the user"+ button={{+ icon: <Mail />,+ text: 'Send magic link',+ isLoading: isSendingMagicLink,+ disabled: !canSendMagicLink,+ onClick: () => {+ if (projectRef) sendMagicLink({ projectRef, user })+ },+ }}+ success={+ successAction === 'send_magic_link'+ ? {+ title: 'Magic link sent',+ description: `The link in the email is valid for ${formattedExpiry}`,+ }+ : undefined+ }+ />+ </>+ )}+ {isPhoneAuth && (+ <RowAction+ title="Send OTP"+ description="Passwordless login via phone for the user"+ button={{+ icon: <Mail />,+ text: 'Send OTP',+ isLoading: isSendingOTP,+ disabled: !canSendOtp,+ onClick: () => {+ if (projectRef) sendOTP({ projectRef, user })+ },+ }}+ success={+ successAction === 'send_otp'+ ? {+ title: 'OTP sent',+ description: `The link in the OTP SMS is valid for ${formattedExpiry}`,+ }+ : undefined+ }+ />+ )}+ </div>++ <Separator />++ <div className={cn('flex flex-col', PANEL_PADDING)}>+ <p>Danger zone</p>+ <p className="text-sm text-foreground-light">+ Be wary of the following features as they cannot be undone.+ </p>+ </div>++ <div className={cn('flex flex-col -space-y-1 !pt-0', PANEL_PADDING)}>+ <RowAction+ title="Remove MFA factors"+ description="This will log the user out of all active sessions"+ button={{+ icon: <ShieldOff />,+ text: 'Remove MFA factors',+ disabled: !canRemoveMFAFactors,+ onClick: () => setIsDeleteFactorsModalOpen(true),+ }}+ className="!bg border-destructive-400"+ />+ <RowAction+ title="Delete user"+ description="User will no longer have access to the project"+ button={{+ icon: <Trash />,+ type: 'danger',+ text: 'Delete user',+ disabled: !canRemoveUser,+ onClick: () => setIsDeleteModalOpen(true),+ }}+ className="!bg border-destructive-400"+ />+ </div>+ </div>++ <ConfirmationModal+ visible={isDeleteModalOpen}+ title="Confirm to delete"+ confirmLabel="Delete"+ onCancel={() => setIsDeleteModalOpen(false)}+ onConfirm={() => handleDelete()}+ >+ <p className="text-sm text-foreground-light">+ This is permanent! Are you sure you want to delete user {user.email}?+ </p>+ </ConfirmationModal>++ <ConfirmationModal+ visible={isDeleteFactorsModalOpen}+ title="Confirm to remove MFA factors"+ confirmLabel="Remove factors"+ confirmLabelLoading="Removing"+ onCancel={() => setIsDeleteFactorsModalOpen(false)}+ onConfirm={() => handleDeleteFactors()}+ >+ <p className="text-sm text-foreground-light">+ This is permanent! Are you sure you want to remove the user's MFA factors?+ </p>+ </ConfirmationModal>+ </>+ )+}++const RowData = ({ property, value }: { property: string; value?: string | boolean }) => {+ return (+ <div className="flex items-center gap-x-2 group">+ <p className="w-36 text-foreground-light text-sm">{property}</p>+ {typeof value === 'boolean' ? (+ <div className="h-[26px] flex items-center justify-center">+ {value ? (+ <div className="rounded-full w-4 h-4 dark:bg-white bg-black flex items-center justify-center">+ <Check size={11} className="text-contrast" strokeWidth={4} />+ </div>+ ) : (+ <X size={13} className="text-foreground-light" />+ )}+ </div>+ ) : (+ <div className="flex items-center gap-x-2 h-[26px]">+ <p className="text-sm">{!value ? '-' : value}</p>+ {!!value && (+ <CopyButton+ iconOnly+ type="text"+ icon={<Copy />}+ className="transition opacity-0 group-hover:opacity-100 px-1"+ text={value}+ />+ )}+ </div>+ )}+ </div>+ )+}++const RowAction = ({+ title,+ description,+ button,+ success,+ className,+}: {+ title: string+ description: string+ button: {+ icon: ReactNode+ type?: ComponentProps<typeof Button>['type']+ text: string+ disabled?: boolean+ isLoading?: boolean+ onClick: () => void+ }+ success?: {+ title: string+ description: string+ }+ className?: string+}) => {+ return (+ <div className={cn(CONTAINER_CLASS, className)}>+ <div>+ <p>{success ? success.title : title}</p>+ <p className="text-xs text-foreground-light">+ {success ? success.description : description}+ </p>+ </div>++ <ButtonTooltip+ type={button?.type ?? 'default'}+ icon={success ? <Check className="text-brand" /> : button.icon}+ loading={button.isLoading ?? false}+ onClick={button.onClick}+ disabled={button?.disabled ?? false}+ tooltip={{+ content: {+ side: 'bottom',+ text: `You need additional permissions to ${button.text.toLowerCase()}`,+ },+ }}+ >+ {button.text}+ </ButtonTooltip>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Auth/Users/UserPanel.tsx b/apps/studio/components/interfaces/Auth/Users/UserPanel.tsxnew file mode 100644index 00000000000..8d7e5ee0c26--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Users/UserPanel.tsx@@ -0,0 +1,74 @@+import SimpleCodeBlock from 'components/to-be-cleaned/SimpleCodeBlock'+import { User } from 'data/auth/users-query'+import { X } from 'lucide-react'+import { useState } from 'react'+import {+ Button,+ cn,+ ResizableHandle,+ ResizablePanel,+ Tabs_Shadcn_,+ TabsContent_Shadcn_,+ TabsList_Shadcn_,+ TabsTrigger_Shadcn_,+} from 'ui'+import { UserOverview } from './UserOverview'++interface UserPanelProps {+ selectedUser?: User+ onClose: () => void+}++export const PANEL_PADDING = 'px-5 py-5'++export const UserPanel = ({ selectedUser, onClose }: UserPanelProps) => {+ const [view, setView] = useState<'overview' | 'raw'>('overview')++ return (+ <>+ <ResizableHandle withHandle />+ <ResizablePanel defaultSize={30} maxSize={45} minSize={30} className="bg-studio border-t">+ <Button+ type="text"+ className="absolute top-3 right-3 px-1"+ icon={<X />}+ onClick={() => onClose()}+ />+ <Tabs_Shadcn_+ value={view}+ className="flex flex-col h-full"+ onValueChange={(value: any) => setView(value)}+ >+ <TabsList_Shadcn_ className="px-5 flex gap-x-4 min-h-[46px]">+ <TabsTrigger_Shadcn_+ value="overview"+ className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"+ >+ Overview+ </TabsTrigger_Shadcn_>+ <TabsTrigger_Shadcn_+ value="raw"+ className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"+ >+ Raw JSON+ </TabsTrigger_Shadcn_>+ </TabsList_Shadcn_>+ <TabsContent_Shadcn_+ value="overview"+ className={cn('mt-0 flex-grow min-h-0 overflow-y-auto')}+ >+ {selectedUser && <UserOverview user={selectedUser} onDeleteSuccess={onClose} />}+ </TabsContent_Shadcn_>+ <TabsContent_Shadcn_+ value="raw"+ className={cn('mt-0 flex-grow min-h-0 overflow-y-auto', PANEL_PADDING)}+ >+ <SimpleCodeBlock className="javascript">+ {JSON.stringify(selectedUser, null, 2)}+ </SimpleCodeBlock>+ </TabsContent_Shadcn_>+ </Tabs_Shadcn_>+ </ResizablePanel>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Auth/Users/Users.utils.ts b/apps/studio/components/interfaces/Auth/Users/Users.utils.tsindex 226660bdecc..ceb985bf300 100644--- a/apps/studio/components/interfaces/Auth/Users/Users.utils.ts+++ b/apps/studio/components/interfaces/Auth/Users/Users.utils.ts@@ -10,6 +10,7 @@ export const isAtBottom = ({ currentTarget }: UIEvent<HTMLDivElement>): booleanexport const formatUsersData = (users: User[]) => {return users.map((user) => {const provider: string = user.raw_app_meta_data?.provider ?? ''+ const providers: string[] = user.raw_app_meta_data?.providers ?? []return {id: user.id,@@ -17,7 +18,17 @@ export const formatUsersData = (users: User[]) => {phone: user.phone,created_at: user.created_at,last_sign_in_at: user.last_sign_in_at,- provider: user.is_anonymous ? '-' : provider,+ providers: user.is_anonymous ? '-' : providers,+ provider_icons: providers+ .map((p) => {+ return p === 'email'+ ? `${BASE_PATH}/img/icons/email-icon2.svg`+ : providerIconMap[p]+ ? `${BASE_PATH}/img/icons/${providerIconMap[p]}.svg`+ : undefined+ })+ .filter(Boolean),+ // I think it's alright to just check via the main provider since email and phone should be mutually exclusiveprovider_type: user.is_anonymous? 'Anonymous': socialProviders.includes(provider)@@ -25,13 +36,8 @@ export const formatUsersData = (users: User[]) => {: phoneProviders.includes(provider)? 'Phone': '-',- provider_icon:- provider === 'email'- ? `${BASE_PATH}/img/icons/email-icon2.svg`- : providerIconMap[provider]- ? `${BASE_PATH}/img/icons/${providerIconMap[provider]}.svg`- : undefined,- img: getAvatarUrl(user), // [Joshen] Note that the images might not load due to CSP issues+ // [Joshen] Note that the images might not load due to CSP issues+ img: getAvatarUrl(user),name: getDisplayName(user),}})@@ -73,7 +79,7 @@ const providers = {// all the potential values for each provider is under user.raw_app_meta_data.provider// Will need to go through one by one to properly verify https://supabase.com/docs/guides/auth/social-login// But I've made the UI handle to not render any icon if nothing matches in this map-const providerIconMap: { [key: string]: string } = Object.values([+export const providerIconMap: { [key: string]: string } = Object.values([...providers.social,...providers.phone,]).reduce((a, b) => {diff --git a/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx b/apps/studio/components/interfaces/Auth/Users/UsersV2.tsxindex e0dc2d0a536..2c36af2e095 100644--- a/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx+++ b/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx@@ -1,19 +1,7 @@-import { PermissionAction } from '@supabase/shared-types/out/constants'import dayjs from 'dayjs'-import {- Copy,- Mail,- RefreshCw,- Search,- ShieldOffIcon,- Trash,- User as UserIcon,- Users,- X,-} from 'lucide-react'+import { RefreshCw, Search, User as UserIcon, Users, X } from 'lucide-react'import { UIEvent, useMemo, useRef, useState } from 'react'import DataGrid, { Column, DataGridHandle, Row } from 'react-data-grid'-import { toast } from 'sonner'import { useParams } from 'common'import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'@@ -21,23 +9,13 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConteimport AlertError from 'components/ui/AlertError'import APIDocsButton from 'components/ui/APIDocsButton'import { FormHeader } from 'components/ui/Forms/FormHeader'-import { useUserDeleteMFAFactorsMutation } from 'data/auth/user-delete-mfa-factors-mutation'-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 { useUsersInfiniteQuery } from 'data/auth/users-infinite-query'-import type { User } from 'data/auth/users-query'-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'-import { copyToClipboard, timeout } from 'lib/helpers'import {Button,cn,- ContextMenu_Shadcn_,- ContextMenuContent_Shadcn_,- ContextMenuItem_Shadcn_,- ContextMenuSeparator_Shadcn_,- ContextMenuTrigger_Shadcn_,+ LoadingLine,+ ResizablePanel,+ ResizablePanelGroup,Select_Shadcn_,SelectContent_Shadcn_,SelectGroup_Shadcn_,@@ -47,11 +25,9 @@ import {} from 'ui'import { GenericSkeletonLoader } from 'ui-patterns'import { Input } from 'ui-patterns/DataInputs/Input'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import AddUserDropdown from './AddUserDropdown'+import { UserPanel } from './UserPanel'import { formatUsersData, isAtBottom } from './Users.utils'-import UsersSidePanel from './UserSidePanel'-import { formatClipboardValue } from 'components/grid/utils/common'type Filter = 'all' | 'verified' | 'unverified' | 'anonymous'const USERS_TABLE_COLUMNS = [@@ -65,9 +41,9 @@ const USERS_TABLE_COLUMNS = [width: 300,resizable: true,},- { id: 'provider', name: 'Provider', minWidth: 150, resizable: true },- { id: 'provider_type', name: 'Provider type', minWidth: 150, resizable: true },{ id: 'phone', name: 'Phone', minWidth: undefined, resizable: true },+ { id: 'providers', name: 'Providers', minWidth: 150, resizable: true },+ { id: 'provider_type', name: 'Provider type', minWidth: 150, resizable: true },{id: 'created_at',name: 'Created at',@@ -97,21 +73,6 @@ export const UsersV2 = () => {const [filterKeywords, setFilterKeywords] = useState('')const [selectedRow, setSelectedRow] = useState<number>()- const [toastId, setToastId] = useState<string | number>()- const [selectedUser, setSelectedUser] = useState<User>()- const [isUserDetailsOpen, setIsUserDetailsOpen] = useState(false)- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)- const [isDeleteFactorsModalOpen, setIsDeleteFactorsModalOpen] = useState(false)-- const canSendMagicLink = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_magic_link')- const canSendRecovery = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_recovery')- const canSendOtp = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_otp')- const canRemoveUser = useCheckPermissions(PermissionAction.TENANT_SQL_DELETE, 'auth.users')- const canRemoveMFAFactors = useCheckPermissions(- PermissionAction.TENANT_SQL_DELETE,- 'auth.mfa_factors'- )-const {data,error,@@ -133,46 +94,10 @@ export const UsersV2 = () => {})+ // eslint-disable-next-line react-hooks/exhaustive-depsconst totalUsers = useMemo(() => data?.pages[0].total, [data?.pages[0].total])const users = useMemo(() => data?.pages.flatMap((page) => page.users), [data?.pages])- const { mutate: resetPassword } = useUserResetPasswordMutation({- onSuccess: (_, vars) => {- toast.success(`Sent password recovery to ${vars.user.email}`, { id: toastId })- },- onError: (err) => {- toast.error(`Failed to send password recovery: ${err.message}`, { id: toastId })- },- })- const { mutate: sendMagicLink } = useUserSendMagicLinkMutation({- onSuccess: (_, vars) => {- toast.success(`Sent magic link to ${vars.user.email}`)- },- onError: (err) => {- toast.error(`Failed to send magic link: ${err.message}`, { id: toastId })- },- })- const { mutate: sendOTP } = useUserSendOTPMutation({- onSuccess: (_, vars) => {- toast.success(`Sent OTP to ${vars.user.phone}`)- },- onError: (err) => {- toast.error(`Failed to send OTP: ${err.message}`, { id: toastId })- },- })- const { mutate: deleteUser } = useUserDeleteMutation({- onSuccess: () => {- toast.success(`Successfully deleted ${selectedUser?.email}`)- setIsDeleteModalOpen(false)- },- })- const { mutate: deleteUserMFAFactors } = useUserDeleteMFAFactorsMutation({- onSuccess: () => {- toast.success("Successfully deleted the user's factors")- setIsDeleteFactorsModalOpen(false)- },- })-const usersTableColumns = USERS_TABLE_COLUMNS.map((col) => {const res: Column<any> = {key: col.id,@@ -181,6 +106,7 @@ export const UsersV2 = () => {sortable: false,width: col.width,minWidth: col.minWidth ?? 120,+ headerCellClass: 'z-50',renderHeaderCell: () => {if (col.id === 'img') return undefinedreturn (@@ -197,7 +123,9 @@ export const UsersV2 = () => {const formattedValue =value !== null && ['created_at', 'last_sign_in_at'].includes(col.id)? dayjs(value).format('ddd DD MMM YYYY HH:mm:ss [GMT]ZZ')- : value+ : Array.isArray(value)+ ? value.join(', ')+ : valueconst isConfirmed = user?.email_confirmed_at || user?.phone_confirmed_atif (col.id === 'img') {@@ -217,117 +145,42 @@ export const UsersV2 = () => {}return (- <ContextMenu_Shadcn_ modal={false}>- <ContextMenuTrigger_Shadcn_ asChild>- <div- className={cn(- 'w-full flex items-center text-xs gap-x-2',- col.id.includes('provider') ? 'capitalize' : ''- )}- >- {col.id === 'provider' && row.provider_icon && (- <img width={16} src={row.provider_icon} alt={`${row.provider} auth icon`} />- )}- {col.id === 'last_sign_in_at' && !isConfirmed ? (- <p className="text-foreground-lighter">Waiting for verification</p>- ) : (- <p>{formattedValue === null ? '-' : formattedValue}</p>- )}- </div>- </ContextMenuTrigger_Shadcn_>- <ContextMenuContent_Shadcn_ onCloseAutoFocus={(e) => e.stopPropagation()}>- <ContextMenuItem_Shadcn_- className="gap-x-2"- onSelect={() => {- const valueToCopy = formatClipboardValue(value)- copyToClipboard(valueToCopy)- }}- onFocusCapture={(e) => e.stopPropagation()}- >- <Copy size={14} />- Copy {col.id === 'id' ? col.name : col.name.toLowerCase()}- </ContextMenuItem_Shadcn_>- <ContextMenuItem_Shadcn_- className="gap-x-2"- onSelect={() => {- setSelectedUser(user)- setIsUserDetailsOpen(true)- }}- onFocusCapture={(e) => e.stopPropagation()}- >- <UserIcon size={14} />- View user info- </ContextMenuItem_Shadcn_>- {row.email !== null && (- <>- <ContextMenuSeparator_Shadcn_ />- <ContextMenuItem_Shadcn_- className="gap-x-2"- disabled={!canSendRecovery}- onSelect={() => {- if (user) handleResetPassword(user)- }}- onFocusCapture={(e) => e.stopPropagation()}- >- <Mail size={14} />- Send password recovery- </ContextMenuItem_Shadcn_>- <ContextMenuItem_Shadcn_- className="gap-x-2"- disabled={!canSendMagicLink}- onSelect={() => {- if (user) handleSendMagicLink(user)- }}- onFocusCapture={(e) => e.stopPropagation()}- >- <Mail size={14} />- Send magic link- </ContextMenuItem_Shadcn_>- </>- )}- {row.phone !== null && (- <>- <ContextMenuSeparator_Shadcn_ />- <ContextMenuItem_Shadcn_- className="gap-x-2"- disabled={!canSendOtp}- onSelect={() => {- if (user) handleSendOtp(user)+ <div+ className={cn(+ 'w-full flex items-center text-xs',+ col.id.includes('provider') ? 'capitalize' : ''+ )}+ >+ {/* [Joshen] Not convinced this is the ideal way to display the icons, but for now */}+ {col.id === 'providers' &&+ row.provider_icons.map((icon: string, idx: number) => {+ const provider = row.providers[idx]+ return (+ <div+ className="min-w-6 min-h-6 rounded-full border flex items-center justify-center bg-surface-75"+ style={{+ marginLeft: idx === 0 ? 0 : `-8px`,+ zIndex: row.provider_icons.length - idx,}}- onFocusCapture={(e) => e.stopPropagation()}>- <Mail size={14} />- Send OTP- </ContextMenuItem_Shadcn_>- </>- )}- <ContextMenuSeparator_Shadcn_ />- <ContextMenuItem_Shadcn_- className="gap-x-2"- disabled={!canRemoveMFAFactors}- onSelect={() => {- setSelectedUser(user)- setIsDeleteFactorsModalOpen(true)- }}- onFocusCapture={(e) => e.stopPropagation()}- >- <ShieldOffIcon size={14} />- Remove MFA factors- </ContextMenuItem_Shadcn_>- <ContextMenuItem_Shadcn_- className="gap-x-2"- disabled={!canRemoveUser}- onSelect={() => {- setSelectedUser(user)- setIsDeleteModalOpen(true)- }}- onFocusCapture={(e) => e.stopPropagation()}- >- <Trash size={14} />- Delete user- </ContextMenuItem_Shadcn_>- </ContextMenuContent_Shadcn_>- </ContextMenu_Shadcn_>+ <img+ key={`${user?.id}-${provider}`}+ width={16}+ src={icon}+ alt={`${provider} auth icon`}+ className={cn(provider === 'github' && 'dark:invert')}+ />+ </div>+ )+ })}+ {col.id === 'last_sign_in_at' && !isConfirmed ? (+ <p className="text-foreground-lighter">Waiting for verification</p>+ ) : (+ <p className={cn(col.id === 'providers' && 'ml-1')}>+ {formattedValue === null ? '-' : formattedValue}+ </p>+ )}+ </div>)},}@@ -344,188 +197,140 @@ export const UsersV2 = () => {setFilterKeywords('')}- const handleResetPassword = async (user: User) => {- if (!projectRef) return console.error('Project ref is required')- const id = toast.loading(`Sending password recovery to ${user.email}`)- setToastId(id)- resetPassword({ projectRef, user })- }-- async function handleSendMagicLink(user: User) {- if (!projectRef) return console.error('Project ref is required')- sendMagicLink({ projectRef, user })- }-- async function handleSendOtp(user: User) {- if (!projectRef) return console.error('Project ref is required')- sendOTP({ projectRef, user })- }-- async function handleDelete() {- await timeout(200)- if (!projectRef) return console.error('Project ref is required')- if (!selectedUser) return console.error('No user is selected')- deleteUser({ projectRef, user: selectedUser })- }-- async function handleDeleteFactors() {- await timeout(200)- if (!projectRef) return console.error('Project ref is required')- if (!selectedUser) return console.error('No user is selected')- deleteUserMFAFactors({ projectRef, userId: selectedUser.id as string })- }-return (- <>- <div className="h-full flex flex-col">- <FormHeader className="py-4 px-6 !mb-0" title="Users" />- <div className="bg-surface-200 py-3 px-6 flex items-center justify-between border-t">- <div className="flex items-center gap-x-2">- <Input- size="tiny"- className="w-64"- icon={<Search size={14} className="text-foreground-lighter" />}- placeholder="Search by email, phone number or UID"- value={search}- onChange={(e) => setSearch(e.target.value)}- onKeyDown={(e) => {- if (e.code === 'Enter' && search.length > 0) setFilterKeywords(search)- }}- actions={[- search && (- <Button size="tiny" type="text" icon={<X />} onClick={() => clearSearch()} />- ),- ]}- />- <Select_Shadcn_ value={filter} onValueChange={(val) => setFilter(val as Filter)}>- <SelectTrigger_Shadcn_ size="tiny" className="w-[150px]">- <SelectValue_Shadcn_ />- </SelectTrigger_Shadcn_>- <SelectContent_Shadcn_>- <SelectGroup_Shadcn_>- <SelectItem_Shadcn_ value="all">All users</SelectItem_Shadcn_>- <SelectItem_Shadcn_ value="verified">Verified users</SelectItem_Shadcn_>- <SelectItem_Shadcn_ value="unverified">Unverified users</SelectItem_Shadcn_>- <SelectItem_Shadcn_ value="anonymous">Anonymous users</SelectItem_Shadcn_>- </SelectGroup_Shadcn_>- </SelectContent_Shadcn_>- </Select_Shadcn_>- </div>- <div className="flex items-center gap-2">- {isNewAPIDocsEnabled && <APIDocsButton section={['user-management']} />}- <Button- size="tiny"- icon={<RefreshCw />}- type="default"- loading={isRefetching && !isFetchingNextPage}- onClick={() => refetch()}- >- Refresh- </Button>- <AddUserDropdown projectKpsVersion={project?.kpsVersion} />- </div>- </div>- <div className="flex flex-col w-full h-full">- <DataGrid- ref={gridRef}- className="flex-grow"- rowHeight={44}- headerRowHeight={36}- columns={usersTableColumns}- rows={formatUsersData(users ?? [])}- rowClass={(_, idx) => {- const isSelected = idx === selectedRow- return [- `${isSelected ? 'bg-surface-300 dark:bg-surface-300' : 'bg-200'} cursor-pointer`,- '[&>.rdg-cell]:border-box [&>.rdg-cell]:outline-none [&>.rdg-cell]:shadow-none',- '[&>.rdg-cell:first-child>div]:ml-4',- ].join(' ')+ <div className="h-full flex flex-col">+ <FormHeader className="py-4 px-6 !mb-0" title="Users" />+ <div className="bg-surface-200 py-3 px-6 flex items-center justify-between border-t">+ <div className="flex items-center gap-x-2">+ <Input+ size="tiny"+ className="w-64 pl-7"+ iconContainerClassName="pl-2"+ icon={<Search size={14} className="text-foreground-lighter" />}+ placeholder="Search by email, phone number or UID"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ onKeyDown={(e) => {+ if (e.code === 'Enter') setFilterKeywords(search)}}- onScroll={handleScroll}- renderers={{- renderRow(idx, props) {- return (- <Row- {...props}- key={props.row.id}- onClick={() => {- if (typeof idx === 'number' && idx >= 0) {- setSelectedRow(idx)- gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })- }- }}- />- )- },- noRowsFallback: isLoading ? (- <div className="absolute top-14 px-6 w-full">- <GenericSkeletonLoader />- </div>- ) : isError ? (- <div className="absolute top-14 px-6 flex flex-col items-center justify-center w-full">- <AlertError subject="Failed to retrieve users" error={error} />- </div>- ) : (- <div className="absolute top-20 px-6 flex flex-col items-center justify-center w-full gap-y-2">- <Users className="text-foreground-lighter" strokeWidth={1} />- <div className="text-center">- <p className="text-foreground">- {filter !== 'all' || filterKeywords.length > 0- ? 'No users found'- : 'No users in your project'}- </p>- <p className="text-foreground-light">- {filter !== 'all' || filterKeywords.length > 0- ? 'There are currently no users based on the filters applied'- : 'There are currently no users who signed up to your project'}- </p>- </div>- </div>+ actions={[+ search && (+ <Button+ size="tiny"+ type="text"+ icon={<X />}+ onClick={() => clearSearch()}+ className="px-1"+ />),- }}+ ]}/>+ <Select_Shadcn_ value={filter} onValueChange={(val) => setFilter(val as Filter)}>+ <SelectTrigger_Shadcn_ size="tiny" className="w-[150px]">+ <SelectValue_Shadcn_ />+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ <SelectItem_Shadcn_ value="all">All users</SelectItem_Shadcn_>+ <SelectItem_Shadcn_ value="verified">Verified users</SelectItem_Shadcn_>+ <SelectItem_Shadcn_ value="unverified">Unverified users</SelectItem_Shadcn_>+ <SelectItem_Shadcn_ value="anonymous">Anonymous users</SelectItem_Shadcn_>+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_></div>- <div className="flex min-h-9 h-9 overflow-hidden items-center px-6 w-full border-t text-xs text-foreground-light">- Total: {totalUsers} users+ <div className="flex items-center gap-2">+ {isNewAPIDocsEnabled && <APIDocsButton section={['user-management']} />}+ <Button+ size="tiny"+ icon={<RefreshCw />}+ type="default"+ loading={isRefetching && !isFetchingNextPage}+ onClick={() => refetch()}+ >+ Refresh+ </Button>+ <AddUserDropdown projectKpsVersion={project?.kpsVersion} /></div></div>-- <UsersSidePanel- selectedUser={selectedUser}- userSidePanelOpen={isUserDetailsOpen}- setUserSidePanelOpen={() => {- setSelectedUser(undefined)- setIsUserDetailsOpen(false)- }}- />-- <ConfirmationModal- visible={isDeleteModalOpen}- title="Confirm to delete"- confirmLabel="Delete"- onCancel={() => setIsDeleteModalOpen(false)}- onConfirm={() => {- handleDelete()- }}- >- <p className="text-sm text-foreground-light">- This is permanent! Are you sure you want to delete user {selectedUser?.email}?- </p>- </ConfirmationModal>-- <ConfirmationModal- visible={isDeleteFactorsModalOpen}- title="Confirm to delete"- confirmLabel="Delete"- onCancel={() => setIsDeleteFactorsModalOpen(false)}- onConfirm={() => {- handleDeleteFactors()- }}+ <LoadingLine loading={isLoading || isRefetching} />+ <ResizablePanelGroup+ direction="horizontal"+ className="relative flex flex-grow bg-alternative min-h-0"+ autoSaveId="query-performance-layout-v1">- <p className="text-sm text-foreground-light">- This is permanent! Are you sure you want to delete the user's MFA factors?- </p>- </ConfirmationModal>- </>+ <ResizablePanel defaultSize={1}>+ <div className="flex flex-col w-full h-full">+ <DataGrid+ ref={gridRef}+ className="flex-grow border-t-0"+ rowHeight={44}+ headerRowHeight={36}+ columns={usersTableColumns}+ rows={formatUsersData(users ?? [])}+ rowClass={(_, idx) => {+ const isSelected = idx === selectedRow+ return [+ `${isSelected ? 'bg-surface-300 dark:bg-surface-300' : 'bg-200'} cursor-pointer`,+ '[&>.rdg-cell]:border-box [&>.rdg-cell]:outline-none [&>.rdg-cell]:shadow-none',+ '[&>.rdg-cell:first-child>div]:ml-4',+ ].join(' ')+ }}+ onScroll={handleScroll}+ renderers={{+ renderRow(idx, props) {+ return (+ <Row+ {...props}+ key={props.row.id}+ onClick={() => {+ if (typeof idx === 'number' && idx >= 0) {+ setSelectedRow(idx)+ gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })+ }+ }}+ />+ )+ },+ noRowsFallback: isLoading ? (+ <div className="absolute top-14 px-6 w-full">+ <GenericSkeletonLoader />+ </div>+ ) : isError ? (+ <div className="absolute top-14 px-6 flex flex-col items-center justify-center w-full">+ <AlertError subject="Failed to retrieve users" error={error} />+ </div>+ ) : (+ <div className="absolute top-20 px-6 flex flex-col items-center justify-center w-full gap-y-2">+ <Users className="text-foreground-lighter" strokeWidth={1} />+ <div className="text-center">+ <p className="text-foreground">+ {filter !== 'all' || filterKeywords.length > 0+ ? 'No users found'+ : 'No users in your project'}+ </p>+ <p className="text-foreground-light">+ {filter !== 'all' || filterKeywords.length > 0+ ? 'There are currently no users based on the filters applied'+ : 'There are currently no users who signed up to your project'}+ </p>+ </div>+ </div>+ ),+ }}+ />+ </div>+ </ResizablePanel>+ {selectedRow !== undefined && (+ <UserPanel+ selectedUser={users?.[selectedRow]}+ onClose={() => setSelectedRow(undefined)}+ />+ )}+ </ResizablePanelGroup>+ <div className="flex min-h-9 h-9 overflow-hidden items-center px-6 w-full border-t text-xs text-foreground-light">+ Total: {totalUsers} users+ </div>+ </div>)}diff --git a/apps/studio/components/ui/CopyButton.tsx b/apps/studio/components/ui/CopyButton.tsxindex e1516c8f1dd..926f9ce100e 100644--- a/apps/studio/components/ui/CopyButton.tsx+++ b/apps/studio/components/ui/CopyButton.tsx@@ -34,8 +34,10 @@ const CopyButton = ({await copyToClipboard(text)onClick?.(e)}}- icon={showCopied ? <Check strokeWidth={2} className="text-brand" /> : <Clipboard />}{...props}+ icon={+ showCopied ? <Check strokeWidth={2} className="text-brand" /> : props.icon ?? <Clipboard />+ }>{!iconOnly && <>{children ?? (showCopied ? copiedLabel : copyLabel)}</>}</Button>