Skip to content

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

feat: use code instead of reset password link (#37171)

Stojan Dimitrovski944aba84ae96
diff --git a/apps/studio/components/interfaces/SignIn/ForgotPasswordForm.tsx b/apps/studio/components/interfaces/SignIn/ForgotPasswordForm.tsx
deleted file mode 100644
index 176f4112373..00000000000
--- a/apps/studio/components/interfaces/SignIn/ForgotPasswordForm.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import HCaptcha from '@hcaptcha/react-hcaptcha'
-import { useRouter } from 'next/router'
-import { useRef, useState } from 'react'
-import { toast } from 'sonner'
-import { object, string } from 'yup'
-
-import { useResetPasswordMutation } from 'data/misc/reset-password-mutation'
-import { BASE_PATH } from 'lib/constants'
-import { Button, Form, Input } from 'ui'
-
-const forgotPasswordSchema = object({
- email: string().email('Must be a valid email').required('Email is required'),
-})
-
-const ForgotPasswordForm = () => {
- const router = useRouter()
- const captchaRef = useRef<HCaptcha>(null)
- const [captchaToken, setCaptchaToken] = useState<string | null>(null)
-
- const { mutate: resetPassword, isLoading } = useResetPasswordMutation({
- onSuccess: async () => {
- toast.success(
- `If you registered using your email and password, you will receive a password reset email. The password reset link expires in 10 minutes.`
- )
- await router.push('/sign-in')
- },
- onError: (error) => {
- setCaptchaToken(null)
- captchaRef.current?.resetCaptcha()
- toast.error(`Failed to send reset email: ${error.message}`)
- },
- })
-
- const onForgotPassword = async ({ email }: { email: string }) => {
- let token = captchaToken
- if (!token) {
- const captchaResponse = await captchaRef.current?.execute({ async: true })
- token = captchaResponse?.response ?? null
- }
-
- resetPassword({
- email,
- hcaptchaToken: token,
- redirectTo: `${
- process.env.NEXT_PUBLIC_VERCEL_ENV === 'preview'
- ? location.origin
- : process.env.NEXT_PUBLIC_SITE_URL
- }${BASE_PATH}/reset-password`,
- })
- }
-
- return (
- <Form
- validateOnBlur
- id="forgot-password-form"
- initialValues={{ email: '' }}
- validationSchema={forgotPasswordSchema}
- onSubmit={onForgotPassword}
- >
- {() => {
- return (
- <div className="flex flex-col pt-4 space-y-4">
- <Input
- id="email"
- name="email"
- type="email"
- label="Email"
- placeholder="[email protected]"
- disabled={isLoading}
- autoComplete="email"
- />
-
- <div className="self-center">
- <HCaptcha
- ref={captchaRef}
- sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}
- size="invisible"
- onVerify={(token) => {
- setCaptchaToken(token)
- }}
- onExpire={() => {
- setCaptchaToken(null)
- }}
- />
- </div>
-
- <div className="border-t border-overlay-border" />
-
- <Button
- block
- form="forgot-password-form"
- htmlType="submit"
- size="medium"
- disabled={isLoading}
- loading={isLoading}
- >
- Send Reset Email
- </Button>
- </div>
- )
- }}
- </Form>
- )
-}
-
-export default ForgotPasswordForm
diff --git a/apps/studio/components/interfaces/SignIn/ForgotPasswordWizard.tsx b/apps/studio/components/interfaces/SignIn/ForgotPasswordWizard.tsx
new file mode 100644
index 00000000000..4aa80ad51d1
--- /dev/null
+++ b/apps/studio/components/interfaces/SignIn/ForgotPasswordWizard.tsx
@@ -0,0 +1,197 @@
+import HCaptcha from '@hcaptcha/react-hcaptcha'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useRouter } from 'next/router'
+import { useRef, useState } from 'react'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import { toast } from 'sonner'
+import * as z from 'zod'
+
+import { useResetPasswordMutation } from 'data/misc/reset-password-mutation'
+import { BASE_PATH } from 'lib/constants'
+import { auth } from 'lib/gotrue'
+import { Button, Form_Shadcn_, FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_ } from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+
+const forgotPasswordSchema = z.object({
+ email: z.string().email('Must be a valid email').min(1, 'Email is required'),
+})
+
+const codeSchema = z.object({
+ code: z.string().regex(/^\d{6}$/, 'Code must be 6 digits'),
+})
+
+type ForgotPasswordFormData = z.infer<typeof forgotPasswordSchema>
+type CodeFormData = z.infer<typeof codeSchema>
+
+export const ForgotPasswordWizard = () => {
+ const [email, setEmail] = useState('')
+
+ if (email) {
+ return <ConfirmResetCodeForm email={email} />
+ }
+
+ return <ForgotPasswordForm onSuccess={(email) => setEmail(email)} />
+}
+
+const ConfirmResetCodeForm = ({ email }: { email: string }) => {
+ const router = useRouter()
+ const [isLoading, setIsLoading] = useState(false)
+
+ const codeForm = useForm<CodeFormData>({
+ resolver: zodResolver(codeSchema),
+ defaultValues: { code: '' },
+ })
+
+ const onCodeEntered: SubmitHandler<CodeFormData> = async (data) => {
+ setIsLoading(true)
+ const {
+ data: { user },
+ error,
+ } = await auth.verifyOtp({ email, token: data.code, type: 'recovery' })
+
+ // This fixes a race condition where the user is redirected to the reset password page without the session being set
+ // which causes the user to be redirected to /sign-in page even though he's signed in
+ await new Promise((resolve) => setTimeout(resolve, 1000))
+
+ if (error) {
+ setIsLoading(false)
+ toast.error(`Failed to verify code: ${error.message}`)
+ } else {
+ if (user?.factors?.length) {
+ await router.push({
+ pathname: '/forgot-password-mfa',
+ query: { returnTo: '/reset-password' },
+ })
+ } else {
+ await router.push('reset-password')
+ }
+ }
+ }
+
+ return (
+ <Form_Shadcn_ {...codeForm}>
+ <form
+ id="code-input-form"
+ className="flex flex-col pt-4 space-y-4"
+ onSubmit={codeForm.handleSubmit(onCodeEntered)}
+ >
+ <FormField_Shadcn_
+ control={codeForm.control}
+ name="code"
+ render={({ field }) => (
+ <FormItemLayout label="Code">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ placeholder="123456"
+ autoComplete="off"
+ disabled={isLoading}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+
+ <div className="border-t border-overlay-border" />
+
+ <Button block form="code-input-form" htmlType="submit" size="medium" loading={isLoading}>
+ Confirm reset code
+ </Button>
+ </form>
+ </Form_Shadcn_>
+ )
+}
+
+const ForgotPasswordForm = ({ onSuccess }: { onSuccess: (email: string) => void }) => {
+ const captchaRef = useRef<HCaptcha>(null)
+ const [captchaToken, setCaptchaToken] = useState<string | null>(null)
+
+ const forgotPasswordForm = useForm<ForgotPasswordFormData>({
+ resolver: zodResolver(forgotPasswordSchema),
+ defaultValues: { email: '' },
+ })
+
+ const { mutate: resetPassword, isLoading } = useResetPasswordMutation({
+ onSuccess: () => {
+ onSuccess(forgotPasswordForm.getValues('email'))
+ },
+ onError: (error) => {
+ setCaptchaToken(null)
+ captchaRef.current?.resetCaptcha()
+ toast.error(`Failed to send reset email: ${error.message}`)
+ },
+ })
+
+ const onForgotPassword: SubmitHandler<ForgotPasswordFormData> = async (data) => {
+ let token = captchaToken
+ if (!token) {
+ const captchaResponse = await captchaRef.current?.execute({ async: true })
+ token = captchaResponse?.response ?? null
+ }
+
+ resetPassword({
+ email: data.email,
+ hcaptchaToken: token,
+ redirectTo: `${
+ process.env.NEXT_PUBLIC_VERCEL_ENV === 'preview'
+ ? location.origin
+ : process.env.NEXT_PUBLIC_SITE_URL
+ }${BASE_PATH}/reset-password`,
+ })
+ }
+
+ return (
+ <Form_Shadcn_ {...forgotPasswordForm}>
+ <form
+ id="forgot-password-form"
+ className="flex flex-col pt-4 space-y-4"
+ onSubmit={forgotPasswordForm.handleSubmit(onForgotPassword)}
+ >
+ <FormField_Shadcn_
+ control={forgotPasswordForm.control}
+ name="email"
+ render={({ field }) => (
+ <FormItemLayout label="Email">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ type="email"
+ placeholder="[email protected]"
+ disabled={isLoading}
+ autoComplete="email"
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+
+ <div className="self-center">
+ <HCaptcha
+ ref={captchaRef}
+ sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}
+ size="invisible"
+ onVerify={(token) => {
+ setCaptchaToken(token)
+ }}
+ onExpire={() => {
+ setCaptchaToken(null)
+ }}
+ />
+ </div>
+
+ <div className="border-t border-overlay-border" />
+
+ <Button
+ block
+ form="forgot-password-form"
+ htmlType="submit"
+ size="medium"
+ disabled={isLoading}
+ loading={isLoading}
+ >
+ Send reset code
+ </Button>
+ </form>
+ </Form_Shadcn_>
+ )
+}
diff --git a/apps/studio/components/interfaces/SignIn/ResetPasswordForm.tsx b/apps/studio/components/interfaces/SignIn/ResetPasswordForm.tsx
index d048a96b0fe..868b5d96162 100644
--- a/apps/studio/components/interfaces/SignIn/ResetPasswordForm.tsx
+++ b/apps/studio/components/interfaces/SignIn/ResetPasswordForm.tsx
@@ -1,22 +1,66 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import * as Sentry from '@sentry/nextjs'
+import { Eye, EyeOff } from 'lucide-react'
import { useRouter } from 'next/router'
+import { useState } from 'react'
+import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
+import { z } from 'zod'
import { auth } from 'lib/gotrue'
-import { passwordSchema } from 'lib/schemas'
-import { Button, Form, Input } from 'ui'
+import {
+ Button,
+ Form_Shadcn_,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormMessage_Shadcn_,
+ Input,
+} from 'ui'
+
+import PasswordConditionsHelper from './PasswordConditionsHelper'
const WHITELIST_ERRORS = [
'New password should be different from the old password',
'Password is known to be weak and easy to guess, please choose a different one',
]
+// Convert the existing yup passwordSchema to Zod
+const passwordSchema = z.object({
+ password: z
+ .string()
+ .min(1, 'Password is required')
+ .max(72, 'Password cannot exceed 72 characters')
+ .refine((password) => {
+ // Basic password validation - you can enhance this based on your requirements
+ const hasUppercase = /[A-Z]/.test(password)
+ const hasLowercase = /[a-z]/.test(password)
+ const hasNumber = /[0-9]/.test(password)
+ const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};`':"\\|,.<>\/?]/.test(password)
+ const isLongEnough = password.length >= 8
+
+ return hasUppercase && hasLowercase && hasNumber && hasSpecialChar && isLongEnough
+ }, 'Password must contain at least 8 characters, including uppercase, lowercase, number, and special character'),
+})
+
+type FormData = z.infer<typeof passwordSchema>
+
const ResetPasswordForm = () => {
const router = useRouter()
+ const [showConditions, setShowConditions] = useState(false)
+ const [passwordHidden, setPasswordHidden] = useState(true)
- const onResetPassword = async ({ password }: { password: string }) => {
+ const form = useForm<FormData>({
+ resolver: zodResolver(passwordSchema),
+ defaultValues: {
+ password: '',
+ },
+ mode: 'onChange',
+ })
+
+ const onResetPassword = async (data: FormData) => {
const toastId = toast.loading('Saving password...')
- const { error } = await auth.updateUser({ password })
+ const { error } = await auth.updateUser({ password: data.password })
if (!error) {
toast.success('Password saved successfully!', { id: toastId })
@@ -33,42 +77,59 @@ const ResetPasswordForm = () => {
}
return (
- <Form
- validateOnBlur
- id="reset-password-form"
- initialValues={{ password: '' }}
- validationSchema={passwordSchema}
- onSubmit={onResetPassword}
- >
- {({ isSubmitting }: { isSubmitting: boolean }) => {
- return (
- <div className="space-y-4 pt-4">
- <Input
- id="password"
- name="password"
- type="password"
- label="Password"
- placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;"
- disabled={isSubmitting}
- autoComplete="new-password"
- />
-
- <div className="border-overlay-border border-t" />
-
- <Button
- block
- form="reset-password-form"
- htmlType="submit"
- size="medium"
- disabled={isSubmitting}
- loading={isSubmitting}
- >
- Save New Password
- </Button>
- </div>
- )
- }}
- </Form>
+ <Form_Shadcn_ {...form}>
+ <form onSubmit={form.handleSubmit(onResetPassword)} className="space-y-4 pt-4">
+ <FormField_Shadcn_
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem_Shadcn_>
+ <FormControl_Shadcn_>
+ <Input
+ id="password"
+ type={passwordHidden ? 'password' : 'text'}
+ label="Password"
+ placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;"
+ disabled={form.formState.isSubmitting}
+ onFocus={() => setShowConditions(true)}
+ autoComplete="new-password"
+ actions={
+ <Button
+ icon={passwordHidden ? <Eye /> : <EyeOff />}
+ type="default"
+ className="!mr-1"
+ onClick={() => setPasswordHidden((prev) => !prev)}
+ />
+ }
+ {...field}
+ />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <div
+ className={`${
+ showConditions ? 'max-h-[500px]' : 'max-h-[0px]'
+ } transition-all duration-400 overflow-y-hidden`}
+ >
+ <PasswordConditionsHelper password={form.watch('password')} />
+ </div>
+
+ <div className="border-overlay-border border-t" />
+
+ <Button
+ block
+ htmlType="submit"
+ size="medium"
+ disabled={form.formState.isSubmitting}
+ loading={form.formState.isSubmitting}
+ >
+ Save new password
+ </Button>
+ </form>
+ </Form_Shadcn_>
)
}
diff --git a/apps/studio/pages/forgot-password-mfa.tsx b/apps/studio/pages/forgot-password-mfa.tsx
new file mode 100644
index 00000000000..7061c9c84a8
--- /dev/null
+++ b/apps/studio/pages/forgot-password-mfa.tsx
@@ -0,0 +1,94 @@
+import * as Sentry from '@sentry/nextjs'
+import { useQueryClient } from '@tanstack/react-query'
+import { useRouter } from 'next/router'
+import { useEffect, useState } from 'react'
+import { toast } from 'sonner'
+
+import { useParams } from 'common'
+import SignInMfaForm from 'components/interfaces/SignIn/SignInMfaForm'
+import ForgotPasswordLayout from 'components/layouts/SignInLayout/ForgotPasswordLayout'
+import { Loading } from 'components/ui/Loading'
+import useLatest from 'hooks/misc/useLatest'
+import { auth, buildPathWithParams, getAccessToken, getReturnToPath } from 'lib/gotrue'
+import type { NextPageWithLayout } from 'types'
+
+const ForgotPasswordMfa: NextPageWithLayout = () => {
+ const router = useRouter()
+
+ const queryClient = useQueryClient()
+ const {
+ // current methods for mfa are github and sso
+ method: signInMethod = 'unknown',
+ } = useParams()
+ const signInMethodRef = useLatest(signInMethod)
+
+ const [loading, setLoading] = useState(true)
+
+ // This useEffect redirects the user to MFA if they're already halfway signed in
+ useEffect(() => {
+ auth
+ .initialize()
+ .then(async ({ error }) => {
+ if (error) {
+ // if there was a problem signing in via the url, don't redirect
+ setLoading(false)
+ return
+ }
+
+ const token = await getAccessToken()
+
+ if (token) {
+ const { data, error } = await auth.mfa.getAuthenticatorAssuranceLevel()
+ if (error) {
+ // if there was a problem signing in via the url, don't redirect
+ toast.error(
+ `Failed to retrieve assurance level: ${error.message}. Please try signing in again`
+ )
+ setLoading(false)
+ return router.push({ pathname: '/sign-in', query: router.query })
+ }
+
+ if (data.currentLevel === data.nextLevel) {
+ await queryClient.resetQueries()
+ router.push(getReturnToPath())
+ return
+ } else {
+ // Show the MFA form
+ setLoading(false)
+ return
+ }
+ } else {
+ // if the user doesn't have a token, he needs to go back to the sign-in page
+ const redirectTo = buildPathWithParams('/sign-in')
+ router.replace(redirectTo)
+ return
+ }
+ })
+ .catch((error) => {
+ Sentry.captureException(error)
+ console.error('Auth initialization error:', error)
+ toast.error('Failed to initialize authentication. Please try again.')
+ setLoading(false)
+ router.push({ pathname: '/sign-in', query: router.query })
+ })
+ }, [])
+
+ if (loading) {
+ return (
+ <div className="flex flex-col flex-1 bg-alternative h-screen items-center justify-center">
+ <Loading />
+ </div>
+ )
+ }
+
+ return (
+ <ForgotPasswordLayout
+ heading="Complete two-factor authentication"
+ subheading="Enter the authentication code from your two-factor authentication app before changing your password"
+ >
+ <SignInMfaForm />
+ </ForgotPasswordLayout>
+ )
+}
+
+export default ForgotPasswordMfa
diff --git a/apps/studio/pages/forgot-password.tsx b/apps/studio/pages/forgot-password.tsx
index 9768b22a13c..03f7a5a75fa 100644
--- a/apps/studio/pages/forgot-password.tsx
+++ b/apps/studio/pages/forgot-password.tsx
@@ -1,4 +1,4 @@
-import ForgotPasswordForm from 'components/interfaces/SignIn/ForgotPasswordForm'
+import { ForgotPasswordWizard } from 'components/interfaces/SignIn/ForgotPasswordWizard'
import ForgotPasswordLayout from 'components/layouts/SignInLayout/ForgotPasswordLayout'
import Link from 'next/link'
import type { NextPageWithLayout } from 'types'
@@ -7,7 +7,7 @@ const ForgotPasswordPage: NextPageWithLayout = () => {
return (
<>
<div className="flex flex-col gap-4">
- <ForgotPasswordForm />
+ <ForgotPasswordWizard />
</div>
<div className="my-8 self-center text-sm">
@@ -22,8 +22,8 @@ const ForgotPasswordPage: NextPageWithLayout = () => {
ForgotPasswordPage.getLayout = (page) => (
<ForgotPasswordLayout
- heading="Reset Your Password"
- subheading="Type in your email and we'll send you a link to reset your password"
+ heading="Forgot your password?"
+ subheading="Type in your email and we'll send you a code to reset the password"
>
{page}
</ForgotPasswordLayout>
diff --git a/apps/studio/pages/reset-password.tsx b/apps/studio/pages/reset-password.tsx
index 96368073eff..67585813e65 100644
--- a/apps/studio/pages/reset-password.tsx
+++ b/apps/studio/pages/reset-password.tsx
@@ -11,21 +11,14 @@ const ResetPasswordPage: NextPageWithLayout = () => {
<div className="flex flex-col gap-4">
<ResetPasswordForm />
</div>
-
- <div className="my-8 self-center text-sm">
- <span className="text-foreground-light">Already have an account?</span>{' '}
- <Link href="/sign-in" className="underline hover:text-foreground-light">
- Sign In
- </Link>
- </div>
</>
)
}
ResetPasswordPage.getLayout = (page) => (
<ForgotPasswordLayout
- heading="Reset Your Password"
- subheading="Type in a new secure password and press save to update your password"
+ heading="Change your password"
+ subheading="Welcome back! Choose a new strong password and save it to proceed"
>
{page}
</ForgotPasswordLayout>