Skip to content

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

Add a page for signing in via MFA.

Ivan Vasilov7b5183016ea9
diff --git a/studio/components/interfaces/SignIn/SignInMfaForm.tsx b/studio/components/interfaces/SignIn/SignInMfaForm.tsx
new file mode 100644
index 00000000000..7647c14b266
--- /dev/null
+++ b/studio/components/interfaces/SignIn/SignInMfaForm.tsx
@@ -0,0 +1,124 @@
+import { AuthError } from '@supabase/gotrue-js'
+import { Factor } from '@supabase/supabase-js'
+import { useQueryClient } from '@tanstack/react-query'
+import { mfaChallengeAndVerify } from 'data/profile/mfa-challenge-and-verify-mutation'
+import { useMfaListFactorsQuery } from 'data/profile/mfa-list-factors-query'
+import { useStore } from 'hooks'
+import { usePushNext } from 'hooks/misc/useAutoAuthRedirect'
+import { useEffect, useState } from 'react'
+import { Button, Form, IconLock, Input } from 'ui'
+import { object, string } from 'yup'
+
+const signInSchema = object({
+ code: string().required('MFA Code is required'),
+})
+
+const SignInMfaForm = () => {
+ const { ui } = useStore()
+ const pushNext = usePushNext()
+ const queryClient = useQueryClient()
+ const { data: factors, isSuccess: factorsSuccess } = useMfaListFactorsQuery()
+ const [selectedFactor, setSelectedFactor] = useState<Factor | null>(null)
+
+ // if the user wanders into this page and he has no MFA setup, send the user to the next screen
+ if (factorsSuccess && factors.totp.length === 0) {
+ queryClient.resetQueries().then(() => pushNext())
+ }
+
+ useEffect(() => {
+ if (factorsSuccess) {
+ setSelectedFactor(factors.totp[0])
+ }
+ }, [factors?.totp, factorsSuccess])
+
+ const onSignIn = async ({ code }: { code: string }) => {
+ const toastId = ui.setNotification({
+ category: 'loading',
+ message: `Signing in...`,
+ })
+ if (selectedFactor) {
+ try {
+ const result = await mfaChallengeAndVerify({ factorId: selectedFactor.id, code })
+
+ ui.setNotification({
+ id: toastId,
+ category: 'success',
+ message: `Signed in successfully!`,
+ })
+
+ await queryClient.resetQueries()
+
+ await pushNext()
+ } catch (error: unknown) {
+ ui.setNotification({
+ id: toastId,
+ category: 'error',
+ message: (error as AuthError).message,
+ })
+ }
+ }
+ }
+
+ return (
+ <Form
+ validateOnBlur
+ id="sign-in-mfa-form"
+ initialValues={{ code: '' }}
+ validationSchema={signInSchema}
+ onSubmit={onSignIn}
+ >
+ {({ isSubmitting }: { isSubmitting: boolean }) => {
+ return (
+ <div className="flex flex-col gap-4">
+ <Input
+ id="code"
+ name="code"
+ type="text"
+ icon={<IconLock />}
+ placeholder="XXXXXX"
+ disabled={isSubmitting}
+ autoComplete="off"
+ spellCheck="false"
+ autoCapitalize="none"
+ autoCorrect="off"
+ label={
+ selectedFactor && factors?.totp.length === 2
+ ? `Code generated by ${selectedFactor.friendly_name}`
+ : null
+ }
+ />
+
+ <Button
+ block
+ form="sign-in-mfa-form"
+ htmlType="submit"
+ size="large"
+ disabled={isSubmitting}
+ loading={isSubmitting}
+ >
+ Verify
+ </Button>
+ {factors?.totp.length === 2 && (
+ <div className="text-sm flex flex-col items-center w-full gap-1">
+ <div>
+ <span className="text-scale-900">Having problems?</span>{' '}
+ <a
+ className="text-white hover:border-b border-white"
+ href="#"
+ onClick={() =>
+ setSelectedFactor(factors.totp.find((f) => f.id !== selectedFactor?.id)!)
+ }
+ >{`Authenticate using ${
+ factors.totp.find((f) => f.id !== selectedFactor?.id)?.friendly_name
+ }?`}</a>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+ }}
+ </Form>
+ )
+}
+
+export default SignInMfaForm
diff --git a/studio/data/profile/keys.ts b/studio/data/profile/keys.ts
index a43a33f7a73..2ed0d876185 100644
--- a/studio/data/profile/keys.ts
+++ b/studio/data/profile/keys.ts
@@ -1,4 +1,5 @@
export const profileKeys = {
profile: () => ['profile'] as const,
mfaFactors: () => ['mfa', 'factors'] as const,
+ aaLevel: () => ['mfa', 'aaLevel'] as const,
}
diff --git a/studio/data/profile/mfa-authenticator-assurance-level-query.ts b/studio/data/profile/mfa-authenticator-assurance-level-query.ts
new file mode 100644
index 00000000000..f5b2ae77113
--- /dev/null
+++ b/studio/data/profile/mfa-authenticator-assurance-level-query.ts
@@ -0,0 +1,41 @@
+import { AuthMFAGetAuthenticatorAssuranceLevelResponse } from '@supabase/supabase-js'
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { auth } from 'lib/gotrue'
+import { profileKeys } from './keys'
+import { Profile } from './types'
+
+export type ProfileResponse = Profile
+
+export async function getMfaAuthenticatorAssuranceLevel() {
+ const { error, data } = await auth.mfa.getAuthenticatorAssuranceLevel()
+
+ if (error) throw error
+ return data
+}
+
+type CustomAuthMFAGetAuthenticatorAssuranceLevelData = NonNullable<
+ AuthMFAGetAuthenticatorAssuranceLevelResponse['data']
+>
+type CustomAuthMFAGetAuthenticatorAssuranceLevelError = NonNullable<
+ AuthMFAGetAuthenticatorAssuranceLevelResponse['error']
+>
+
+export const useAuthenticatorAssuranceLevelQuery = <
+ TData = CustomAuthMFAGetAuthenticatorAssuranceLevelData
+>({
+ enabled = true,
+ ...options
+}: UseQueryOptions<
+ CustomAuthMFAGetAuthenticatorAssuranceLevelData,
+ CustomAuthMFAGetAuthenticatorAssuranceLevelError,
+ TData
+> = {}) => {
+ return useQuery<
+ CustomAuthMFAGetAuthenticatorAssuranceLevelData,
+ CustomAuthMFAGetAuthenticatorAssuranceLevelError,
+ TData
+ >(profileKeys.aaLevel(), () => getMfaAuthenticatorAssuranceLevel(), {
+ staleTime: 1000 * 60 * 30, // default good for 30 mins
+ ...options,
+ })
+}
diff --git a/studio/data/profile/mfa-challenge-and-verify-mutation.ts b/studio/data/profile/mfa-challenge-and-verify-mutation.ts
index 59d3c7ad6c1..21d8c721f8a 100644
--- a/studio/data/profile/mfa-challenge-and-verify-mutation.ts
+++ b/studio/data/profile/mfa-challenge-and-verify-mutation.ts
@@ -24,7 +24,12 @@ export const useMfaChallengeAndVerifyMutation = ({
return useMutation((vars) => mfaChallengeAndVerify(vars), {
async onSuccess(data, variables, context) {
- await queryClient.invalidateQueries(profileKeys.mfaFactors())
+ // when a MFA is added, the aaLevel is bumped up
+ await Promise.all([
+ queryClient.invalidateQueries(profileKeys.mfaFactors()),
+ queryClient.invalidateQueries(profileKeys.aaLevel()),
+ ])
+
await onSuccess?.(data, variables, context)
},
...options,
diff --git a/studio/data/profile/mfa-unenroll-mutation.ts b/studio/data/profile/mfa-unenroll-mutation.ts
index 0d8bf7ff41e..903efb9f98b 100644
--- a/studio/data/profile/mfa-unenroll-mutation.ts
+++ b/studio/data/profile/mfa-unenroll-mutation.ts
@@ -25,7 +25,12 @@ export const useMfaUnenrollMutation = ({
return useMutation((vars) => mfaUnenroll(vars), {
async onSuccess(data, variables, context) {
- await queryClient.invalidateQueries(profileKeys.mfaFactors())
+ // when a factor is unenrolled, the aaLevel is bumped down if it's the last factor
+ await Promise.all([
+ queryClient.invalidateQueries(profileKeys.mfaFactors()),
+ queryClient.invalidateQueries(profileKeys.aaLevel()),
+ ])
+
await onSuccess?.(data, variables, context)
},
...options,
diff --git a/studio/pages/sign-in-mfa.tsx b/studio/pages/sign-in-mfa.tsx
new file mode 100644
index 00000000000..aaafe13a6a7
--- /dev/null
+++ b/studio/pages/sign-in-mfa.tsx
@@ -0,0 +1,25 @@
+import SignInMfaForm from 'components/interfaces/SignIn/SignInMfaForm'
+import { SignInLayout } from 'components/layouts'
+import { NextPageWithLayout } from 'types'
+
+const SignInMfaPage: NextPageWithLayout = () => {
+ return (
+ <>
+ <div className="flex flex-col gap-5">
+ <SignInMfaForm />
+ </div>
+ </>
+ )
+}
+
+SignInMfaPage.getLayout = (page) => (
+ <SignInLayout
+ heading="Two-factor authentication"
+ subheading="Enter the authentication code from your two-factor authentication (TOTP) app"
+ logoLinkToMarketingSite={true}
+ >
+ {page}
+ </SignInLayout>
+)
+
+export default SignInMfaPage