The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: add beta auth hooks UI (#19312)
Stojan Dimitrovski44694ef6decc
diff --git a/apps/studio/components/interfaces/Auth/BasicAuthSettingsForm/BasicAuthSettingsForm.tsx b/apps/studio/components/interfaces/Auth/BasicAuthSettingsForm/BasicAuthSettingsForm.tsxindex a0584a46698..271871dfe77 100644--- a/apps/studio/components/interfaces/Auth/BasicAuthSettingsForm/BasicAuthSettingsForm.tsx+++ b/apps/studio/components/interfaces/Auth/BasicAuthSettingsForm/BasicAuthSettingsForm.tsx@@ -71,6 +71,8 @@ function HoursOrNeverText({ value }: { value: number }) {}}+const formId = 'auth-config-basic-settings'+const BasicAuthSettingsForm = observer(() => {const { ui } = useStore()const { ref: projectRef } = useParams()@@ -83,7 +85,6 @@ const BasicAuthSettingsForm = observer(() => {} = useAuthConfigQuery({ projectRef })const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()- const formId = 'auth-config-basic-settings'const [hidden, setHidden] = useState(true)const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')@@ -105,7 +106,6 @@ const BasicAuthSettingsForm = observer(() => {SECURITY_CAPTCHA_PROVIDER: authConfig?.SECURITY_CAPTCHA_PROVIDER || 'hcaptcha',SESSIONS_TIMEBOX: authConfig?.SESSIONS_TIMEBOX || 0,SESSIONS_INACTIVITY_TIMEOUT: authConfig?.SESSIONS_INACTIVITY_TIMEOUT || 0,-...(singlePerUserReleased? {SESSIONS_SINGLE_PER_USER: authConfig?.SESSIONS_SINGLE_PER_USER || false,diff --git a/apps/studio/components/interfaces/Auth/Hooks/BasicHooksConfig.tsx b/apps/studio/components/interfaces/Auth/Hooks/BasicHooksConfig.tsxnew file mode 100644index 00000000000..680a533a235--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Hooks/BasicHooksConfig.tsx@@ -0,0 +1,180 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useParams } from 'common'+import { observer } from 'mobx-react-lite'+import { useEffect } from 'react'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Form,+ IconAlertCircle,+ IconAlertTriangle,+ Toggle,+} from 'ui'+import { boolean, object, string } from 'yup'++import {+ FormActions,+ FormHeader,+ FormPanel,+ FormSection,+ FormSectionContent,+ FormSectionLabel,+} from 'components/ui/Forms'+import { useAuthConfigQuery } from 'data/auth/auth-config-query'+import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'+import { useCheckPermissions, useStore, useFlag } from 'hooks'++import SchemaFunctionSelector from './SchemaFunctionSelector'++const schema = object({+ HOOKS_CUSTOM_ACCESS_TOKEN_ENABLED: boolean(),+ HOOKS_CUSTOM_ACCESS_TOKEN_URI: string(),+})++const formId = 'auth-basic-hooks-form'++const BasicHooksConfig = observer(() => {+ const { ui, meta } = useStore()+ const { ref: projectRef } = useParams()+ const {+ data: authConfig,+ error: authConfigError,+ isLoading,+ isError,+ isSuccess,+ } = useAuthConfigQuery({ projectRef })+ const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()++ const customizeAccessTokenReleased = useFlag('authHooksCustomizeAccessToken')++ const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')++ // TODO: Remove as any once these properties are defined in Auth Config types+ const INITIAL_VALUES = {+ ...(customizeAccessTokenReleased+ ? {+ HOOK_CUSTOM_ACCESS_TOKEN_ENABLED: authConfig?.HOOK_CUSTOM_ACCESS_TOKEN_ENABLED || false,+ HOOK_CUSTOM_ACCESS_TOKEN_URI: authConfig?.HOOK_CUSTOM_ACCESS_TOKEN_URI || '',+ }+ : null),+ }++ const onSubmit = (values: any, { resetForm }: any) => {+ const payload = { ...values }++ if (payload.HOOK_CUSTOM_ACCESS_TOKEN_URI === '') {+ payload.HOOK_CUSTOM_ACCESS_TOKEN_URI = null+ }++ updateAuthConfig(+ { projectRef: projectRef!, config: payload },+ {+ onError: () => {+ ui.setNotification({+ category: 'error',+ message: `Failed to update settings`,+ })+ },+ onSuccess: () => {+ ui.setNotification({+ category: 'success',+ message: `Successfully updated settings`,+ })+ resetForm({ values: values, initialValues: values })+ },+ }+ )+ }++ useEffect(() => {+ if (ui.selectedProjectRef) meta.functions.load()+ }, [ui.selectedProjectRef])++ if (isError) {+ return (+ <Alert_Shadcn_ variant="destructive">+ <IconAlertCircle strokeWidth={2} />+ <AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )+ }++ return (+ <Form id={formId} initialValues={INITIAL_VALUES} onSubmit={onSubmit} validationSchema={schema}>+ {({ handleReset, resetForm, values, initialValues, setFieldValue }: any) => {+ const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)++ // Form is reset once remote data is loaded in store+ useEffect(() => {+ if (isSuccess) {+ resetForm({ values: INITIAL_VALUES, initialValues: INITIAL_VALUES })+ }+ }, [isSuccess])++ return (+ <>+ <FormHeader+ title="Auth Hooks (Beta)"+ description="Use PostgreSQL functions to customize the behavior of Supabase Auth to meet your needs."+ />+ <FormPanel+ disabled={true}+ footer={+ <div className="flex py-4 px-8">+ <FormActions+ form={formId}+ isSubmitting={isUpdatingConfig}+ hasChanges={hasChanges}+ handleReset={handleReset}+ disabled={!canUpdateConfig}+ helper={+ !canUpdateConfig+ ? 'You need additional permissions to update authentication settings'+ : undefined+ }+ />+ </div>+ }+ >+ <FormSection+ header={<FormSectionLabel>Customize Access Token (JWT) Claims</FormSectionLabel>}+ >+ <FormSectionContent loading={isLoading}>+ <SchemaFunctionSelector+ id="HOOK_CUSTOM_ACCESS_TOKEN_URI"+ descriptionText="Select the function to be called by Supabase Auth each time a new JWT is created. It should return the claims you wish to be present in the JWT."+ values={values}+ setFieldValue={setFieldValue}+ disabled={!canUpdateConfig || !customizeAccessTokenReleased}+ />+ {!customizeAccessTokenReleased && (+ <Alert_Shadcn_ variant="default">+ <AlertTitle_Shadcn_>Coming soon!</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ This hook is not available yet on your project.+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}+ {values.HOOK_CUSTOM_ACCESS_TOKEN_URI && (+ <Toggle+ id="HOOK_CUSTOM_ACCESS_TOKEN_ENABLED"+ size="medium"+ label="Enable hook"+ layout="flex"+ disabled={!canUpdateConfig || !customizeAccessTokenReleased}+ />+ )}+ </FormSectionContent>+ </FormSection>+ <div className="border-t border-muted"></div>+ </FormPanel>+ </>+ )+ }}+ </Form>+ )+})++export default BasicHooksConfigdiff --git a/apps/studio/components/interfaces/Auth/Hooks/EnterpriseHooksConfig.tsx b/apps/studio/components/interfaces/Auth/Hooks/EnterpriseHooksConfig.tsxnew file mode 100644index 00000000000..312aecb0872--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Hooks/EnterpriseHooksConfig.tsx@@ -0,0 +1,258 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useParams } from 'common'+import { observer } from 'mobx-react-lite'+import { useEffect } from 'react'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Form,+ IconAlertCircle,+ Toggle,+} from 'ui'+import { boolean, object, string } from 'yup'++import {+ FormActions,+ FormHeader,+ FormPanel,+ FormSection,+ FormSectionContent,+ FormSectionLabel,+} from 'components/ui/Forms'+import { useAuthConfigQuery } from 'data/auth/auth-config-query'+import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'+import { useCheckPermissions, useSelectedOrganization, useStore, useFlag } from 'hooks'+import UpgradeToPro from 'components/ui/UpgradeToPro'++import SchemaFunctionSelector from './SchemaFunctionSelector'++const schema = object({+ HOOKS_MFA_VERIFICATION_ATTEMPT_ENABLED: boolean(),+ HOOKS_MFA_VERIFICATION_ATTEMPT_URI: string(),+ HOOKS_PASSWORD_VERIFICATION_ATTEMPT_ENABLED: boolean(),+ HOOKS_PASSWORD_VERIFICATION_ATTEMPT_URI: string(),+})++const FORM_ID = 'enterprise-hooks-config'++const EnterpriseHooksConfig = observer(() => {+ const { ui, meta } = useStore()+ const { ref: projectRef } = useParams()+ const {+ data: authConfig,+ error: authConfigError,+ isLoading,+ isError,+ isSuccess,+ } = useAuthConfigQuery({ projectRef })+ const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()++ const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')+ const mfaVerificationAttemptReleased = useFlag('authHookMFAVerification')+ const passwordVerificationAttemptReleased = useFlag('authHookPasswordVerification')++ const organization = useSelectedOrganization()+ const { data: subscription, isSuccess: isSuccessSubscription } = useOrgSubscriptionQuery({+ orgSlug: organization!.slug,+ })++ const isTeamsEnterprisePlan =+ isSuccessSubscription && subscription?.plan?.id !== 'free' && subscription?.plan?.id !== 'pro'++ const INITIAL_VALUES = {+ ...(mfaVerificationAttemptReleased+ ? {+ HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED:+ authConfig?.HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED || false,+ HOOK_MFA_VERIFICATION_ATTEMPT_URI: authConfig?.HOOK_MFA_VERIFICATION_ATTEMPT_URI || '',+ }+ : null),+ ...(passwordVerificationAttemptReleased+ ? {+ // remove as any when the types are merged in+ HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED:+ (authConfig as any)?.HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED || false,+ HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI:+ (authConfig as any)?.HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI || '',+ }+ : null),+ }++ useEffect(() => {+ if (ui.selectedProjectRef) meta.functions.load()+ }, [ui.selectedProjectRef])++ const onSubmit = (values: any, { resetForm }: any) => {+ const payload = { ...values }+ if (payload.HOOK_MFA_VERIFICATION_ATTEMPT_URI === '') {+ payload.HOOK_MFA_VERIFICATION_ATTEMPT_URI = null+ }+ if (payload.HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI === '') {+ payload.HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI = null+ }+ updateAuthConfig(+ { projectRef: projectRef!, config: payload },+ {+ onError: () => {+ ui.setNotification({+ category: 'error',+ message: `Failed to update settings`,+ })+ },+ onSuccess: () => {+ ui.setNotification({+ category: 'success',+ message: `Successfully updated settings`,+ })+ resetForm({ values: values, initialValues: values })+ },+ }+ )+ }++ if (isError) {+ return (+ <Alert_Shadcn_ variant="destructive">+ <IconAlertCircle strokeWidth={2} />+ <AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )+ }++ return (+ <Form id={FORM_ID} initialValues={INITIAL_VALUES} onSubmit={onSubmit} validationSchema={schema}>+ {({ handleReset, resetForm, values, initialValues, setFieldValue }: any) => {+ const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)++ // Form is reset once remote data is loaded in store+ useEffect(() => {+ if (isSuccess) {+ resetForm({ values: INITIAL_VALUES, initialValues: INITIAL_VALUES })+ }+ }, [isSuccess])++ return (+ <>+ <FormHeader+ title="Enterprise Hooks"+ description="Advanced Auth hooks are available to Teams and Enterprise plan customers."+ />+ <FormPanel+ disabled={true}+ footer={+ <div className="flex py-4 px-8">+ <FormActions+ form={FORM_ID}+ isSubmitting={isUpdatingConfig}+ hasChanges={hasChanges}+ handleReset={handleReset}+ disabled={!canUpdateConfig || !isTeamsEnterprisePlan}+ helper={+ !canUpdateConfig+ ? 'You need additional permissions to update authentication settings'+ : undefined+ }+ />+ </div>+ }+ >+ {!isTeamsEnterprisePlan && (+ <UpgradeToPro+ primaryText="Upgrade plan"+ secondaryText="Configuring Enterprise Hooks requires a Teams or Enterprise plan."+ projectRef={projectRef!}+ organizationSlug={organization!.slug}+ buttonText="Upgrade"+ />+ )}+ <div className={isTeamsEnterprisePlan ? '' : 'opacity-50'}>+ <FormSection header={<FormSectionLabel>MFA Verification Attempt</FormSectionLabel>}>+ <FormSectionContent loading={isLoading}>+ <SchemaFunctionSelector+ id="HOOK_MFA_VERIFICATION_ATTEMPT_URI"+ descriptionText="Select the function to be called by Supabase Auth each time a user tries to verify an MFA factor. Return a decision on whether to reject the attempt and future ones, or to allow the user to keep trying."+ values={values}+ setFieldValue={setFieldValue}+ disabled={+ !canUpdateConfig ||+ !isTeamsEnterprisePlan ||+ !mfaVerificationAttemptReleased+ }+ />+ {!mfaVerificationAttemptReleased && (+ <Alert_Shadcn_ variant="default">+ <AlertTitle_Shadcn_>Coming soon!</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ This hook is not available yet on your project.+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}+ {values.HOOK_MFA_VERIFICATION_ATTEMPT_URI && (+ <Toggle+ id="HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED"+ size="small"+ label="Enable hook"+ layout="flex"+ disabled={+ !canUpdateConfig ||+ !isTeamsEnterprisePlan ||+ !mfaVerificationAttemptReleased+ }+ />+ )}+ </FormSectionContent>+ </FormSection>+ <div className="border-t border-muted"></div>++ <FormSection+ header={<FormSectionLabel>Password Verification Attempt</FormSectionLabel>}+ >+ <FormSectionContent loading={isLoading}>+ <SchemaFunctionSelector+ id="HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI"+ descriptionText="Select the function to be called by Supabase Auth each time a user tries to sign in with a password. Return a decision whether to allow the user to reject the attempt, or to allow the user to keep trying."+ values={values}+ setFieldValue={setFieldValue}+ disabled={+ !canUpdateConfig ||+ !isTeamsEnterprisePlan ||+ !passwordVerificationAttemptReleased+ }+ />+ {!passwordVerificationAttemptReleased && (+ <Alert_Shadcn_ variant="default">+ <AlertTitle_Shadcn_>Coming soon!</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ This hook is not available yet on your project.+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}+ {values.HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI && (+ <Toggle+ id="HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED"+ size="small"+ label="Enable hook"+ layout="flex"+ disabled={+ !canUpdateConfig ||+ !isTeamsEnterprisePlan ||+ !passwordVerificationAttemptReleased+ }+ />+ )}+ </FormSectionContent>+ </FormSection>+ </div>+ <div className="border-t border-muted"></div>+ </FormPanel>+ </>+ )+ }}+ </Form>+ )+})++export default EnterpriseHooksConfigdiff --git a/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx b/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsxnew file mode 100644index 00000000000..c8823f488df--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx@@ -0,0 +1,172 @@+import { observer } from 'mobx-react-lite'+import { useState } from 'react'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ CommandEmpty_Shadcn_,+ CommandGroup_Shadcn_,+ CommandInput_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+ Command_Shadcn_,+ IconCheck,+ IconCode,+ IconLoader,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ Popover_Shadcn_,+ ScrollArea,+} from 'ui'++import { convertArgumentTypes } from 'components/interfaces/Database/Functions/Functions.utils'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { useStore } from 'hooks'++interface FunctionSelectorProps {+ className?: string+ size?: 'tiny' | 'small'+ showError?: boolean+ schema?: string+ selectedFunctionName: string+ onSelectFunction: (name: string) => void+ disabled?: boolean+}++const FunctionSelector = ({+ className,+ size = 'tiny',+ showError = true,+ disabled = false,+ schema,+ selectedFunctionName,+ onSelectFunction,+}: FunctionSelectorProps) => {+ const { project } = useProjectContext()+ const { meta } = useStore()+ const [open, setOpen] = useState(false)++ const refetchFunctions = () => {+ meta.functions.load()+ }++ const functions = meta.functions+ .list()+ .filter((func) => schema && func.schema === schema)+ .filter((func) => func.return_type === 'json' || func.return_type === 'jsonb')+ .filter((func) => {+ const { value } = convertArgumentTypes(func.argument_types)++ if (value.length !== 1) {+ return false+ }++ return value[0].type === 'json' || value[0].type === 'jsonb'+ })++ const isFunctionsLoading = meta.functions.isLoading+ const isFunctionsError = meta.functions.hasError+ const functionsError = meta.functions.error+ const isFunctionsSuccess = !isFunctionsLoading && !isFunctionsError++ return (+ <div className={className}>+ {isFunctionsLoading && (+ <Button+ type="outline"+ className="w-full [&>span]:w-full"+ icon={<IconLoader className="animate-spin" size={12} />}+ disabled={!!disabled}+ >+ <div className="w-full flex space-x-3 py-0.5">+ <p className="text-xs text-foreground-light">Loading functions...</p>+ </div>+ </Button>+ )}++ {showError && isFunctionsError && (+ <Alert_Shadcn_ variant="warning" className="!px-3 !py-3">+ <AlertTitle_Shadcn_ className="text-xs text-amber-900">+ Failed to load functions+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="text-xs mb-2">+ Error: {functionsError?.message}+ </AlertDescription_Shadcn_>+ <Button type="default" size="tiny" onClick={() => refetchFunctions()}>+ Reload functions+ </Button>+ </Alert_Shadcn_>+ )}++ {isFunctionsSuccess && (+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>+ <PopoverTrigger_Shadcn_ asChild>+ <Button+ size={size}+ type="outline"+ className={`w-full [&>span]:w-full ${size === 'small' ? 'py-1.5' : ''}`}+ iconRight={+ <IconCode className="text-foreground-light rotate-90" strokeWidth={2} size={12} />+ }+ disabled={!!disabled}+ >+ <div className="w-full flex space-x-3 py-0.5">+ <p className="text-xs text-foreground-light">function</p>+ <p className="text-xs">+ {selectedFunctionName === '*' ? 'All functions' : selectedFunctionName}+ </p>+ </div>+ </Button>+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ className="p-0" side="bottom" align="start">+ <Command_Shadcn_>+ <CommandInput_Shadcn_ placeholder="Search functions..." />+ <CommandList_Shadcn_>+ <CommandEmpty_Shadcn_>No functions found</CommandEmpty_Shadcn_>+ <CommandGroup_Shadcn_>+ <ScrollArea className={(functions || []).length > 7 ? 'h-[210px]' : ''}>+ {!(functions || []).length && (+ <CommandItem_Shadcn_+ key="no-function-found"+ disabled={true}+ className="flex items-center justify-between space-x-2 w-full"+ >+ <span>+ No function with a single JSON/B argument+ <br />+ and JSON/B return type found in this schema.+ </span>+ </CommandItem_Shadcn_>+ )}+ {functions?.map((func) => (+ <CommandItem_Shadcn_+ key={func.id}+ className="cursor-pointer flex items-center justify-between space-x-2 w-full"+ onSelect={() => {+ onSelectFunction(func.name)+ setOpen(false)+ }}+ onClick={() => {+ onSelectFunction(func.name)+ setOpen(false)+ }}+ >+ <span>{func.name}</span>+ {selectedFunctionName === func.name && (+ <IconCheck className="text-brand" strokeWidth={2} />+ )}+ </CommandItem_Shadcn_>+ ))}+ </ScrollArea>+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ )}+ </div>+ )+}++export default observer(FunctionSelector)diff --git a/apps/studio/components/interfaces/Auth/Hooks/SchemaFunctionSelector.tsx b/apps/studio/components/interfaces/Auth/Hooks/SchemaFunctionSelector.tsxnew file mode 100644index 00000000000..a15fa0701ce--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Hooks/SchemaFunctionSelector.tsx@@ -0,0 +1,68 @@+import { useState, useEffect } from 'react'++import SchemaSelector from 'components/ui/SchemaSelector'+import FunctionSelector from './FunctionSelector'++interface SchemaFunctionSelectorProps {+ id: string+ values: any+ setFieldValue: (field: string, value: any) => void+ descriptionText?: string+ disabled?: boolean+}++const SchemaFunctionSelector = ({+ id,+ values,+ descriptionText,+ setFieldValue,+ disabled = false,+}: SchemaFunctionSelectorProps) => {+ const [_proto, _x, _db, schema, func] = (values[id] || '').split('/')+ // select the public schema by default+ const [selectedSchema, setSelectedSchema] = useState(schema || 'public')+ const [selectedFunc, setSelectedFunc] = useState(func || '')++ useEffect(() => {+ if (schema) {+ setSelectedSchema(schema)+ }+ }, [schema])++ useEffect(() => {+ if (func) {+ setSelectedFunc(func)+ }+ }, [func])++ return (+ <div className="flex flex-col gap-2">+ <SchemaSelector+ size="tiny"+ showError={false}+ selectedSchemaName={selectedSchema}+ onSelectSchema={(name) => {+ setSelectedSchema(name)+ setSelectedFunc('')+ setFieldValue(id, '')+ }}+ disabled={!!disabled || !values}+ />+ <FunctionSelector+ size="tiny"+ schema={selectedSchema}+ selectedFunctionName={selectedFunc}+ onSelectFunction={(name) => {+ setSelectedFunc(name)+ setFieldValue(id, `pg-functions://postgres/${selectedSchema}/${name}`)+ }}+ disabled={!!disabled || !values}+ />+ {descriptionText && (+ <div className="mt-2 text-foreground-lighter leading-normal text-sm">{descriptionText}</div>+ )}+ </div>+ )+}++export default SchemaFunctionSelectordiff --git a/apps/studio/components/layouts/AuthLayout/AuthLayout.tsx b/apps/studio/components/layouts/AuthLayout/AuthLayout.tsxindex 2dd7e989901..208e3b673b4 100644--- a/apps/studio/components/layouts/AuthLayout/AuthLayout.tsx+++ b/apps/studio/components/layouts/AuthLayout/AuthLayout.tsx@@ -5,7 +5,7 @@ import { PropsWithChildren, useEffect } from 'react'import { useParams } from 'common'import ProductMenu from 'components/ui/ProductMenu'import { useAuthConfigPrefetch } from 'data/auth/auth-config-query'-import { useStore, withAuth } from 'hooks'+import { useStore, withAuth, useFlag } from 'hooks'import ProjectLayout from '../'import { generateAuthMenu } from './AuthLayout.utils'@@ -17,6 +17,8 @@ const AuthLayout = ({ title, children }: PropsWithChildren<AuthLayoutProps>) =>const { ref: projectRef = 'default' } = useParams()const { ui, meta } = useStore()+ const hooksReleased = useFlag('authHooksReleased')+useAuthConfigPrefetch({ projectRef })const router = useRouter()@@ -33,7 +35,12 @@ const AuthLayout = ({ title, children }: PropsWithChildren<AuthLayoutProps>) =><ProjectLayouttitle={title || 'Authentication'}product="Authentication"- productMenu={<ProductMenu page={page} menu={generateAuthMenu(projectRef ?? 'default')} />}+ productMenu={+ <ProductMenu+ page={page}+ menu={generateAuthMenu(projectRef ?? 'default', { hooksReleased })}+ />+ }><main style={{ maxHeight: '100vh' }} className="flex-1 overflow-y-auto">{children}diff --git a/apps/studio/components/layouts/AuthLayout/AuthLayout.utils.ts b/apps/studio/components/layouts/AuthLayout/AuthLayout.utils.tsindex 4dd7dd8aae3..3ac8204ed17 100644--- a/apps/studio/components/layouts/AuthLayout/AuthLayout.utils.ts+++ b/apps/studio/components/layouts/AuthLayout/AuthLayout.utils.ts@@ -1,13 +1,15 @@-import { IS_PLATFORM } from 'lib/constants'import { ProductMenuGroup } from 'components/ui/ProductMenu/ProductMenu.types'+import { IS_PLATFORM } from 'lib/constants'-export const generateAuthMenu = (ref: string): ProductMenuGroup[] => {+export const generateAuthMenu = (+ ref: string,+ options: { hooksReleased?: boolean } = {}+): ProductMenuGroup[] => {return [{title: 'Manage',items: [{ name: 'Users', key: 'users', url: `/project/${ref}/auth/users`, items: [] }],},-{title: 'Configuration',items: [@@ -37,13 +39,23 @@ export const generateAuthMenu = (ref: string): ProductMenuGroup[] => {url: `/project/${ref}/auth/templates`,items: [],},-{name: 'URL Configuration',key: 'url-configuration',url: `/project/${ref}/auth/url-configuration`,items: [],},+ ...(options?.hooksReleased+ ? [+ {+ name: 'Hooks',+ key: 'hooks',+ url: `/project/${ref}/auth/hooks`,+ items: [],+ label: 'BETA',+ },+ ]+ : []),]: []),],diff --git a/apps/studio/components/ui/SchemaSelector.tsx b/apps/studio/components/ui/SchemaSelector.tsxindex 85e2dc697bf..459bb68493d 100644--- a/apps/studio/components/ui/SchemaSelector.tsx+++ b/apps/studio/components/ui/SchemaSelector.tsx@@ -68,6 +68,7 @@ const SchemaSelector = ({type="outline"className="w-full [&>span]:w-full"icon={<IconLoader className="animate-spin" size={12} />}+ disabled={!!disabled}><div className="w-full flex space-x-3 py-0.5"><p className="text-xs text-foreground-light">Loading schemas...</p>diff --git a/apps/studio/components/ui/UpgradeToPro.tsx b/apps/studio/components/ui/UpgradeToPro.tsxindex dc11556b095..28d894fd6f7 100644--- a/apps/studio/components/ui/UpgradeToPro.tsx+++ b/apps/studio/components/ui/UpgradeToPro.tsx@@ -14,6 +14,7 @@ interface UpgradeToProProps {organizationSlug: stringsecondaryText: stringaddon?: 'pitr' | 'customDomain' | 'computeInstance'+ buttonText?: string}const UpgradeToPro = ({@@ -23,6 +24,7 @@ const UpgradeToPro = ({organizationSlug,secondaryText,addon,+ buttonText,}: UpgradeToProProps) => {const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organizationSlug })const plan = subscription?.plan?.id@@ -63,7 +65,7 @@ const UpgradeToPro = ({: `/project/${projectRef}/settings/addons?panel=${addon}`}>- {plan === 'free' ? 'Upgrade to Pro' : 'Enable Addon'}+ {buttonText || (plan === 'free' ? 'Upgrade to Pro' : 'Enable Addon')}</Link></Button></Tooltip.Trigger>diff --git a/apps/studio/data/api.d.ts b/apps/studio/data/api.d.tsindex 5cf1cba1cf3..99b8f213e87 100644--- a/apps/studio/data/api.d.ts+++ b/apps/studio/data/api.d.ts@@ -1547,6 +1547,14 @@ export interface paths {/** Disables project's readonly mode for the next 15 minutes */post: operations['ReadOnlyController_temporarilyDisableReadonlyMode']}+ '/v1/projects/{ref}/read-replicas/setup': {+ /** Set up a read replica */+ post: operations['ReadReplicaController_setUpReadReplica']+ }+ '/v1/projects/{ref}/read-replicas/remove': {+ /** Remove a read replica */+ post: operations['ReadReplicaController_removeReadReplica']+ }'/v1/projects/{ref}/health': {/** Gets project's service health status */get: operations['ServiceHealthController_checkServiceHealth']@@ -1858,6 +1866,10 @@ export interface components {SMS_TEST_OTP_VALID_UNTIL: stringHOOK_MFA_VERIFICATION_ATTEMPT_ENABLED?: booleanHOOK_MFA_VERIFICATION_ATTEMPT_URI?: string+ HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED?: boolean+ HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI?: string+ HOOK_CUSTOM_ACCESS_TOKEN_ENABLED?: boolean+ HOOK_CUSTOM_ACCESS_TOKEN_URI?: stringEXTERNAL_APPLE_ENABLED: booleanEXTERNAL_APPLE_CLIENT_ID: stringEXTERNAL_APPLE_SECRET: string@@ -2004,6 +2016,10 @@ export interface components {SMS_TEMPLATE?: stringHOOK_MFA_VERIFICATION_ATTEMPT_ENABLED?: booleanHOOK_MFA_VERIFICATION_ATTEMPT_URI?: string+ HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED?: boolean+ HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI?: string+ HOOK_CUSTOM_ACCESS_TOKEN_ENABLED?: boolean+ HOOK_CUSTOM_ACCESS_TOKEN_URI?: stringEXTERNAL_APPLE_ENABLED?: booleanEXTERNAL_APPLE_CLIENT_ID?: stringEXTERNAL_APPLE_SECRET?: string@@ -2144,6 +2160,10 @@ export interface components {SMS_TEST_OTP_VALID_UNTIL: stringHOOK_MFA_VERIFICATION_ATTEMPT_ENABLED?: booleanHOOK_MFA_VERIFICATION_ATTEMPT_URI?: string+ HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED?: boolean+ HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI?: string+ HOOK_CUSTOM_ACCESS_TOKEN_ENABLED?: boolean+ HOOK_CUSTOM_ACCESS_TOKEN_URI?: stringEXTERNAL_APPLE_ENABLED: booleanEXTERNAL_APPLE_CLIENT_ID: stringEXTERNAL_APPLE_SECRET: string@@ -4501,6 +4521,31 @@ export interface components {override_enabled: booleanoverride_active_until: string}+ SetUpReadReplicaBody: {+ /**+ * @description Region you want your read replica to reside in+ * @example us-east-1+ * @enum {string}+ */+ read_replica_region:+ | 'us-east-1'+ | 'us-west-1'+ | 'us-west-2'+ | 'ap-southeast-1'+ | 'ap-northeast-1'+ | 'ap-northeast-2'+ | 'ap-southeast-2'+ | 'eu-west-1'+ | 'eu-west-2'+ | 'eu-west-3'+ | 'eu-central-1'+ | 'ca-central-1'+ | 'ap-south-1'+ | 'sa-east-1'+ }+ RemoveReadReplicaBody: {+ database_identifier: string+ }AuthHealthResponse: {name: stringversion: string@@ -4516,8 +4561,10 @@ export interface components {| components['schemas']['AuthHealthResponse']| components['schemas']['RealtimeHealthResponse']/** @enum {string} */- name: 'auth' | 'db' | 'realtime' | 'rest' | 'storage'+ name: 'auth' | 'db' | 'pooler' | 'realtime' | 'rest' | 'storage'healthy: boolean+ /** @enum {string} */+ status: 'COMING_UP' | 'ACTIVE_HEALTHY' | 'UNHEALTHY'error?: string}V1PgbouncerConfigResponse: {@@ -11722,12 +11769,58 @@ export interface operations {}}}+ /** Set up a read replica */+ ReadReplicaController_setUpReadReplica: {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['SetUpReadReplicaBody']+ }+ }+ responses: {+ 201: {+ content: never+ }+ /** @description Failed to set up read replica */+ 500: {+ content: never+ }+ }+ }+ /** Remove a read replica */+ ReadReplicaController_removeReadReplica: {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['RemoveReadReplicaBody']+ }+ }+ responses: {+ 201: {+ content: never+ }+ /** @description Failed to remove read replica */+ 500: {+ content: never+ }+ }+ }/** Gets project's service health status */ServiceHealthController_checkServiceHealth: {parameters: {query: {timeout_ms?: number- services: ('auth' | 'db' | 'realtime' | 'rest' | 'storage')[]+ services: ('auth' | 'db' | 'pooler' | 'realtime' | 'rest' | 'storage')[]}path: {/** @description Project ref */diff --git a/apps/studio/pages/project/[ref]/auth/hooks.tsx b/apps/studio/pages/project/[ref]/auth/hooks.tsxnew file mode 100644index 00000000000..25c27b43420--- /dev/null+++ b/apps/studio/pages/project/[ref]/auth/hooks.tsx@@ -0,0 +1,35 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useParams } from 'common'++import BasicHooksConfig from 'components/interfaces/Auth/Hooks/BasicHooksConfig'+import EnterpriseHooksConfig from 'components/interfaces/Auth/Hooks/EnterpriseHooksConfig'+import { AuthLayout } from 'components/layouts'+import { FormsContainer } from 'components/ui/Forms'+import NoPermission from 'components/ui/NoPermission'+import { useCheckPermissions, useSelectedOrganization } from 'hooks'+import { NextPageWithLayout } from 'types'++const Hooks: NextPageWithLayout = () => {+ const canReadAuthSettings = useCheckPermissions(PermissionAction.READ, 'custom_config_gotrue')+ const { ref: projectRef } = useParams()+ const organization = useSelectedOrganization()++ if (!canReadAuthSettings) {+ return <NoPermission isFullPage resourceText="access your project's auth hooks" />+ } else {+ return (+ <FormsContainer>+ <div className="flex flex-col gap-8">+ <BasicHooksConfig />+ <EnterpriseHooksConfig />+ </div>+ </FormsContainer>+ )+ }+}++Hooks.getLayout = (page) => {+ return <AuthLayout>{page}</AuthLayout>+}++export default Hooks