Skip to content

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

Add a modal for adding new factor.

Ivan Vasilov777c5b407a6e
diff --git a/studio/components/interfaces/Account/AddNewFactorModal.tsx b/studio/components/interfaces/Account/AddNewFactorModal.tsx
new file mode 100644
index 00000000000..822b59b3b11
--- /dev/null
+++ b/studio/components/interfaces/Account/AddNewFactorModal.tsx
@@ -0,0 +1,201 @@
+import ConfirmationModal from 'components/ui/ConfirmationModal'
+import InformationBox from 'components/ui/InformationBox'
+import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
+import { useMfaChallengeAndVerifyMutation } from 'data/profile/mfa-challenge-and-verify-mutation'
+import { useMfaEnrollMutation } from 'data/profile/mfa-enroll-mutation'
+import { useMfaUnenrollMutation } from 'data/profile/mfa-unenroll-mutation'
+import { useStore } from 'hooks'
+import Image from 'next/image'
+import { Dispatch, SetStateAction, useEffect, useState } from 'react'
+import { Input, Modal } from 'ui'
+
+const AddNewFactorModal = ({ onClose }: { onClose: () => void }) => {
+ const [verificationComplete, setVerificationComplete] = useState(false)
+ // Generate a name with a number between 0 and 1000
+ const [name, setName] = useState(`App ${Math.floor(Math.random() * 1000)}`)
+
+ const {
+ mutate: enroll,
+ data,
+ reset: resetEnrollment,
+ isLoading: isEnrolling,
+ } = useMfaEnrollMutation()
+ const { mutate: unenroll } = useMfaUnenrollMutation()
+
+ useEffect(() => {
+ return () => {
+ // when the modal is closed, if there's a factor id which hasn't been verified, unenroll it
+ if (data?.id && !verificationComplete) {
+ // delete the internal state of enroll mutation so that the next time enroll is called,
+ // it makes an API call
+ resetEnrollment()
+ unenroll({ factorId: data.id })
+ }
+ }
+ }, [])
+
+ return !data ? (
+ <FirstStep name={name} setName={setName} enroll={enroll} onClose={onClose} />
+ ) : (
+ <SecondStep
+ factorName={name}
+ factor={data}
+ isLoading={isEnrolling}
+ onSuccess={() => {
+ setVerificationComplete(true)
+ onClose()
+ }}
+ onClose={onClose}
+ />
+ )
+}
+
+const FirstStep = ({
+ name,
+ setName,
+ enroll,
+ onClose,
+}: {
+ name: string
+ setName: Dispatch<SetStateAction<string>>
+ enroll: (params: { factorType: 'totp'; friendlyName?: string }) => void
+ onClose: () => void
+}) => {
+ return (
+ <ConfirmationModal
+ size="medium"
+ visible
+ header="Add a new authenticator app as a factor"
+ buttonLabel="Generate QR"
+ buttonLoadingLabel="Generating QR"
+ buttonDisabled={name.length === 0}
+ onSelectCancel={onClose}
+ onSelectConfirm={() => {
+ enroll({
+ factorType: 'totp',
+ friendlyName: name,
+ })
+ }}
+ >
+ <Modal.Content>
+ <>
+ <div className="pt-6 pb-5">
+ <Input
+ label="Provide a name to identify this app"
+ descriptionText="A string will be randomly generated if a name is not provided"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </div>
+ </>
+ </Modal.Content>
+ </ConfirmationModal>
+ )
+}
+
+const SecondStep = ({
+ factorName,
+ factor,
+ isLoading,
+ onSuccess,
+ onClose,
+}: {
+ factorName: string
+ factor: {
+ id: string
+ type: 'totp'
+ totp: {
+ qr_code: string
+ secret: string
+ uri: string
+ }
+ }
+ isLoading: boolean
+ onSuccess: () => void
+ onClose: () => void
+}) => {
+ const [code, setCode] = useState('')
+
+ const { ui } = useStore()
+
+ const {
+ mutate: challengeAndVerify,
+ isLoading: isVerifying,
+ isSuccess: verificationComplete,
+ } = useMfaChallengeAndVerifyMutation({
+ onError: (error) => {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to add a second factor authentication: ${error?.message}`,
+ })
+ },
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully added a second factor authentication`,
+ })
+ onSuccess()
+ },
+ })
+
+ return (
+ <ConfirmationModal
+ size="medium"
+ visible
+ header={`Verify new factor ${factorName}`}
+ buttonLabel="Confirm"
+ buttonLoadingLabel="Confirming"
+ loading={isVerifying}
+ onSelectCancel={onClose}
+ onSelectConfirm={() => challengeAndVerify({ factorId: factor.id, code })}
+ >
+ <Modal.Content>
+ <>
+ <div className="py-4 px-4 text-sm">
+ <span>
+ Use an authenticator app to scan the following QR code, and provide the code from the
+ app to complete the enrolment.
+ </span>
+ </div>
+ {isLoading ? (
+ <div className="pb-4 px-4">
+ <GenericSkeletonLoader />
+ </div>
+ ) : (
+ <>
+ <div className="flex justify-center py-3">
+ <div className="h-48 w-48 bg-white rounded">
+ <Image width={190} height={190} src={factor.totp.qr_code} alt={factor.totp.uri} />
+ </div>
+ </div>
+ <div>
+ <InformationBox
+ title="Unable to scan?"
+ description={
+ <Input
+ copy
+ disabled
+ id="ref"
+ size="small"
+ label="You can also enter this secret key into your authenticator app"
+ value={factor.totp.secret}
+ />
+ }
+ />
+ </div>
+ <div className="pt-2 pb-4">
+ <Input
+ label="Authentication code"
+ value={code}
+ onChange={(e) => setCode(e.target.value)}
+ />
+ </div>
+ </>
+ )}
+ </>
+ </Modal.Content>
+ </ConfirmationModal>
+ )
+}
+
+export default AddNewFactorModal
diff --git a/studio/components/interfaces/Account/index.ts b/studio/components/interfaces/Account/index.ts
index 4ce89542872..38c906b34f7 100644
--- a/studio/components/interfaces/Account/index.ts
+++ b/studio/components/interfaces/Account/index.ts
@@ -1,5 +1,6 @@
import AccessTokenList from './AccessTokenList'
-import NewTokenBanner from './NewTokenBanner'
+import AddNewFactorModal from './AddNewFactorModal'
import NewAccessTokenButton from './NewAccessTokenButton'
+import NewTokenBanner from './NewTokenBanner'
-export { AccessTokenList, NewTokenBanner, NewAccessTokenButton }
+export { AccessTokenList, NewTokenBanner, NewAccessTokenButton, AddNewFactorModal }
diff --git a/studio/components/ui/ConfirmationModal.tsx b/studio/components/ui/ConfirmationModal.tsx
index 842572933c0..940fdafd810 100644
--- a/studio/components/ui/ConfirmationModal.tsx
+++ b/studio/components/ui/ConfirmationModal.tsx
@@ -10,6 +10,7 @@ export interface ConfirmationModalProps {
size?: 'small' | 'tiny' | 'medium' | 'large'
buttonLabel: string
buttonLoadingLabel?: string
+ buttonDisabled?: boolean
onSelectCancel: () => void
onSelectConfirm: () => void
}
@@ -23,6 +24,7 @@ const ConfirmationModal = ({
size = 'small',
buttonLabel = '',
buttonLoadingLabel = '',
+ buttonDisabled = false,
onSelectCancel = () => {},
onSelectConfirm = () => {},
children,
@@ -62,7 +64,7 @@ const ConfirmationModal = ({
<Button
type={danger ? 'danger' : 'primary'}
loading={loading}
- disabled={loading}
+ disabled={loading || buttonDisabled}
onClick={onConfirm}
>
{loading ? buttonLoadingLabel : buttonLabel}
diff --git a/studio/data/profile/keys.ts b/studio/data/profile/keys.ts
index 49ba29ad7b7..a43a33f7a73 100644
--- a/studio/data/profile/keys.ts
+++ b/studio/data/profile/keys.ts
@@ -1,3 +1,4 @@
export const profileKeys = {
profile: () => ['profile'] as const,
+ mfaFactors: () => ['mfa', 'factors'] as const,
}
diff --git a/studio/data/profile/mfa-challenge-and-verify-mutation.ts b/studio/data/profile/mfa-challenge-and-verify-mutation.ts
new file mode 100644
index 00000000000..59d3c7ad6c1
--- /dev/null
+++ b/studio/data/profile/mfa-challenge-and-verify-mutation.ts
@@ -0,0 +1,32 @@
+import { AuthMFAVerifyResponse, MFAChallengeAndVerifyParams } from '@supabase/supabase-js'
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { auth } from 'lib/gotrue'
+import { profileKeys } from './keys'
+
+export const mfaChallengeAndVerify = async (params: MFAChallengeAndVerifyParams) => {
+ const { error, data } = await auth.mfa.challengeAndVerify(params)
+
+ if (error) throw error
+ return data
+}
+
+type CustomMFAVerifyResponse = NonNullable<AuthMFAVerifyResponse['data']>
+type CustomMFAVerifyError = NonNullable<AuthMFAVerifyResponse['error']>
+
+export const useMfaChallengeAndVerifyMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<CustomMFAVerifyResponse, CustomMFAVerifyError, MFAChallengeAndVerifyParams>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation((vars) => mfaChallengeAndVerify(vars), {
+ async onSuccess(data, variables, context) {
+ await queryClient.invalidateQueries(profileKeys.mfaFactors())
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
diff --git a/studio/data/profile/mfa-enroll-mutation.ts b/studio/data/profile/mfa-enroll-mutation.ts
new file mode 100644
index 00000000000..e51a294a5e8
--- /dev/null
+++ b/studio/data/profile/mfa-enroll-mutation.ts
@@ -0,0 +1,22 @@
+import { AuthMFAEnrollResponse, MFAEnrollParams } from '@supabase/supabase-js'
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import { auth } from 'lib/gotrue'
+
+const mfaEnroll = async (params: MFAEnrollParams) => {
+ const { error, data } = await auth.mfa.enroll(params)
+
+ if (error) throw error
+ return data
+}
+
+type CustomMFAEnrollResponse = NonNullable<AuthMFAEnrollResponse['data']>
+type CustomMFAEnrollError = NonNullable<AuthMFAEnrollResponse['error']>
+
+export const useMfaEnrollMutation = ({
+ ...options
+}: Omit<
+ UseMutationOptions<CustomMFAEnrollResponse, CustomMFAEnrollError, MFAEnrollParams>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation((vars) => mfaEnroll(vars), { ...options })
+}
diff --git a/studio/data/profile/mfa-list-factors-query.ts b/studio/data/profile/mfa-list-factors-query.ts
new file mode 100644
index 00000000000..29171d3b099
--- /dev/null
+++ b/studio/data/profile/mfa-list-factors-query.ts
@@ -0,0 +1,31 @@
+import { AuthMFAListFactorsResponse } 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 getMfaListFactors() {
+ const { error, data } = await auth.mfa.listFactors()
+
+ if (error) throw error
+ return data
+}
+
+type CustomMFAListFactorsData = NonNullable<AuthMFAListFactorsResponse['data']>
+type CustomMFAListFactorsError = NonNullable<AuthMFAListFactorsResponse['error']>
+
+export const useMfaListFactorsQuery = <TData = CustomMFAListFactorsData>({
+ enabled = true,
+ ...options
+}: UseQueryOptions<CustomMFAListFactorsData, CustomMFAListFactorsError, TData> = {}) => {
+ return useQuery<CustomMFAListFactorsData, CustomMFAListFactorsError, TData>(
+ profileKeys.mfaFactors(),
+ () => getMfaListFactors(),
+ {
+ staleTime: 1000 * 60 * 30, // default good for 30 mins
+ ...options,
+ }
+ )
+}
diff --git a/studio/data/profile/mfa-unenroll-mutation.ts b/studio/data/profile/mfa-unenroll-mutation.ts
new file mode 100644
index 00000000000..0d8bf7ff41e
--- /dev/null
+++ b/studio/data/profile/mfa-unenroll-mutation.ts
@@ -0,0 +1,33 @@
+import { AuthMFAUnenrollResponse, MFAUnenrollParams } from '@supabase/supabase-js'
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { auth } from 'lib/gotrue'
+import { profileKeys } from './keys'
+
+const mfaUnenroll = async (params: MFAUnenrollParams) => {
+ const { error, data } = await auth.mfa.unenroll(params)
+
+ auth.mfa.listFactors
+ if (error) throw error
+ return data
+}
+
+type CustomMFAUnenrollResponse = NonNullable<AuthMFAUnenrollResponse['data']>
+type CustomMFAUnenrollError = NonNullable<AuthMFAUnenrollResponse['error']>
+
+export const useMfaUnenrollMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<CustomMFAUnenrollResponse, CustomMFAUnenrollError, MFAUnenrollParams>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation((vars) => mfaUnenroll(vars), {
+ async onSuccess(data, variables, context) {
+ await queryClient.invalidateQueries(profileKeys.mfaFactors())
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}