Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🐛 Fix email change silently failing when the address is already in use (#2970)
Luke Vellaa348e609704f
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex b3fbb8a30..3bcae6780 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -121,6 +121,8 @@"cancelInvite": "Cancel invite","cancelInviteConfirmation": "Are you sure you want to cancel the invite for {email}?","captchaFailed": "Verification failed. Please try again.",+ "changeEmail": "Change email",+ "changeEmailDescription": "We'll send a verification code to your new email address","changeName": "Change name","changeNameDescription": "Enter a new name for this participant.","changeNameInfo": "This will not affect any votes you have already made.",@@ -269,8 +271,10 @@"editSettings": "Edit settings","editVotes": "Edit votes","email": "Email",+ "emailChangeAddressTaken": "This email address is already in use by another account.","emailChangeRequestError": "We couldn't process this request. Please try again later.","emailChangeRequestSent": "Verify your new email address",+ "emailChangeSameAddress": "This is already your email address. Enter a different one.","emailChangeSuccess": "Email changed successfully","emailChangeVerifyDescription": "Enter the 6 digit verification code we sent to {email}.","emailChangeVerifyError": "Verification failed. Please try again.",@@ -590,6 +594,7 @@"prioritySupport": "Priority support","prioritySupportDescription": "Get faster response times and dedicated assistance","profile": "Profile",+ "profileAccount": "Account","profileDescription": "Change your profile settings","profileEmailAddress": "Email address","profileEmailAddressDescription": "Your email address is used to log in to your account",diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/change-email-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/change-email-dialog.tsxnew file mode 100644index 000000000..d73a3b0cc--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/change-email-dialog.tsx@@ -0,0 +1,341 @@+"use client";+import { zodResolver } from "@hookform/resolvers/zod";+import { Button } from "@rallly/ui/button";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+ useDialog,+} from "@rallly/ui/dialog";+import { Field, FieldError, FieldGroup, FieldLabel } from "@rallly/ui/field";+import { Form } from "@rallly/ui/form";+import { Input } from "@rallly/ui/input";+import { toast } from "@rallly/ui/sonner";+import { useRouter } from "next/navigation";+import React from "react";+import { Controller, useForm } from "react-hook-form";+import * as z from "zod";+import { InputOTP } from "@/components/input-otp";+import { checkEmailAvailabilityAction } from "@/features/user/actions";+import { Trans, useTranslation } from "@/i18n/client";+import { authClient } from "@/lib/auth-client";+import { useSafeAction } from "@/lib/safe-action/client";++const emailSchema = z.object({+ email: z.email(),+});++const otpSchema = z.object({+ otp: z.string().regex(/^\d{6}$/),+});++function RequestEmailChangeForm({+ currentEmail,+ onCodeSent,+}: {+ currentEmail: string;+ onCodeSent: (email: string) => void;+}) {+ const { t } = useTranslation();+ const emailId = React.useId();+ const checkEmailAvailability = useSafeAction(checkEmailAvailabilityAction);+ const form = useForm({+ defaultValues: { email: currentEmail },+ resolver: zodResolver(emailSchema),+ });+ const { formState } = form;++ return (+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(async (data) => {+ // Better-Auth reports success without sending when the address is+ // taken, so the conflict has to be caught before that call.+ const availability = await checkEmailAvailability.executeAsync({+ email: data.email,+ });++ if (availability?.data?.ok === false) {+ form.setError(+ "email",+ {+ message:+ availability.data.reason === "same_email"+ ? t("emailChangeSameAddress", {+ defaultValue:+ "This is already your email address. Enter a different one.",+ })+ : t("emailChangeAddressTaken", {+ defaultValue:+ "This email address is already in use by another account.",+ }),+ },+ { shouldFocus: true },+ );+ return;+ }++ if (!availability?.data?.ok) {+ form.setError("email", {+ message: t("emailChangeRequestError", {+ defaultValue:+ "We couldn't process this request. Please try again later.",+ }),+ });+ return;+ }++ const res = await authClient.emailOtp.requestEmailChange({+ newEmail: data.email,+ });++ if (res.error) {+ form.setError("email", {+ message: t("emailChangeRequestError", {+ defaultValue:+ "We couldn't process this request. Please try again later.",+ }),+ });+ return;+ }++ onCodeSent(data.email);+ })}+ >+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="changeEmail" defaults="Change email" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="changeEmailDescription"+ defaults="We'll send a verification code to your new email address"+ />+ </DialogDescription>+ </DialogHeader>++ <FieldGroup className="py-4">+ <Controller+ control={form.control}+ name="email"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel htmlFor={emailId}>+ <Trans i18nKey="email" defaults="Email" />+ </FieldLabel>+ <Input+ {...field}+ id={emailId}+ type="email"+ autoComplete="email"+ disabled={formState.isSubmitting}+ aria-invalid={fieldState.invalid}+ />+ <FieldError errors={[fieldState.error]} />+ </Field>+ )}+ />+ </FieldGroup>++ <DialogFooter>+ <DialogClose render={<Button />}>+ <Trans i18nKey="cancel" defaults="Cancel" />+ </DialogClose>+ <Button+ type="submit"+ variant="primary"+ loading={formState.isSubmitting}+ >+ <Trans i18nKey="continue" defaults="Continue" />+ </Button>+ </DialogFooter>+ </form>+ </Form>+ );+}++function VerifyEmailChangeForm({+ newEmail,+ onBack,+ onVerified,+}: {+ newEmail: string;+ onBack: () => void;+ onVerified: () => void;+}) {+ const { t } = useTranslation();+ const form = useForm({+ defaultValues: { otp: "" },+ resolver: zodResolver(otpSchema),+ });+ const { formState } = form;++ const handleSubmit = form.handleSubmit(async (data) => {+ const res = await authClient.emailOtp.changeEmail({+ newEmail,+ otp: data.otp,+ });++ if (res.error) {+ switch (res.error.code) {+ case "INVALID_OTP":+ form.setError("otp", {+ message: t("wrongVerificationCode", {+ defaultValue: "Your verification code is incorrect",+ }),+ });+ break;+ case "OTP_EXPIRED":+ form.setError("otp", {+ message: t("expiredVerificationCode", {+ defaultValue:+ "This code has expired. Request a new one to continue.",+ }),+ });+ break;+ case "TOO_MANY_ATTEMPTS":+ form.setError("otp", {+ message: t("tooManyVerificationAttempts", {+ defaultValue:+ "Too many incorrect attempts. Request a new code to continue.",+ }),+ });+ break;+ default:+ // The address can be claimed between the availability check and+ // this call, and Better-Auth only reports the conflict here.+ form.setError(+ "otp",+ res.error.message === "Email already in use"+ ? {+ message: t("emailChangeAddressTaken", {+ defaultValue:+ "This email address is already in use by another account.",+ }),+ }+ : {+ message: t("emailChangeVerifyError", {+ defaultValue: "Verification failed. Please try again.",+ }),+ },+ );+ }+ return;+ }++ onVerified();+ });++ return (+ <Form {...form}>+ <form onSubmit={handleSubmit}>+ <DialogHeader>+ <DialogTitle>+ <Trans+ i18nKey="emailChangeRequestSent"+ defaults="Verify your new email address"+ />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="emailChangeVerifyDescription"+ defaults="Enter the 6 digit verification code we sent to {email}."+ values={{ email: newEmail }}+ />+ </DialogDescription>+ </DialogHeader>++ <FieldGroup className="py-4">+ <Controller+ control={form.control}+ name="otp"+ render={({ field, fieldState }) => (+ <Field>+ <InputOTP+ {...field}+ disabled={formState.isSubmitting}+ autoFocus={true}+ onValidCode={() => {+ handleSubmit();+ }}+ />+ <FieldError errors={[fieldState.error]} />+ </Field>+ )}+ />+ </FieldGroup>++ <DialogFooter>+ <Button type="button" onClick={onBack}>+ <Trans i18nKey="back" defaults="Back" />+ </Button>+ <Button+ type="submit"+ variant="primary"+ loading={formState.isSubmitting}+ >+ <Trans i18nKey="verify" defaults="Verify" />+ </Button>+ </DialogFooter>+ </form>+ </Form>+ );+}++export function ChangeEmailDialog({+ currentEmail,+ trigger,+}: {+ currentEmail: string;+ /** Rendered as the dialog trigger; the caller styles it and wires aria labels. */+ trigger: React.ReactElement;+}) {+ const router = useRouter();+ const { t } = useTranslation();+ const dialog = useDialog();+ const [pendingEmail, setPendingEmail] = React.useState<string | null>(null);++ return (+ <Dialog+ {...dialog.dialogProps}+ onOpenChange={(open) => {+ dialog.dialogProps.onOpenChange(open);+ if (!open) {+ setPendingEmail(null);+ }+ }}+ >+ <DialogTrigger render={trigger} />+ <DialogContent>+ {pendingEmail ? (+ <VerifyEmailChangeForm+ newEmail={pendingEmail}+ onBack={() => setPendingEmail(null)}+ onVerified={() => {+ setPendingEmail(null);+ dialog.dismiss();+ toast.success(+ t("emailChangeSuccess", {+ defaultValue: "Email changed successfully",+ }),+ );+ // The change-email endpoint refreshes the session snapshot, so a+ // refresh re-renders the layouts with the new email.+ router.refresh();+ }}+ />+ ) : (+ <RequestEmailChangeForm+ currentEmail={currentEmail}+ onCodeSent={setPendingEmail}+ />+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/email-address-setting.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/email-address-setting.tsxnew file mode 100644index 000000000..f87ccb6df--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/email-address-setting.tsx@@ -0,0 +1,35 @@+import { Button } from "@rallly/ui/button";+import {+ Field,+ FieldContent,+ FieldDescription,+ FieldTitle,+} from "@rallly/ui/field";+import { MailIcon } from "lucide-react";+import { SettingIcon } from "@/components/setting-icon";+import { Trans } from "@/i18n/client";+import { ChangeEmailDialog } from "./change-email-dialog";++export function EmailAddressSetting({ email }: { email: string }) {+ return (+ <Field orientation="responsive">+ <SettingIcon>+ <MailIcon />+ </SettingIcon>+ <FieldContent>+ <FieldTitle>+ <Trans i18nKey="profileEmailAddress" defaults="Email address" />+ </FieldTitle>+ <FieldDescription>{email}</FieldDescription>+ </FieldContent>+ <ChangeEmailDialog+ currentEmail={email}+ trigger={+ <Button>+ <Trans i18nKey="changeEmail" defaults="Change email" />+ </Button>+ }+ />+ </Field>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-email-address.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-email-address.tsxdeleted file mode 100644index 7f20c7cd9..000000000--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-email-address.tsx+++ /dev/null@@ -1,264 +0,0 @@-"use client";--import { zodResolver } from "@hookform/resolvers/zod";-import { Alert, AlertDescription, AlertTitle } from "@rallly/ui/alert";-import { Button } from "@rallly/ui/button";-import {- Form,- FormControl,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@rallly/ui/form";-import { Input } from "@rallly/ui/input";-import { CheckCircleIcon, InfoIcon } from "lucide-react";-import { useRouter } from "next/navigation";-import React from "react";-import { useForm } from "react-hook-form";-import * as z from "zod";-import { InputOTP } from "@/components/input-otp";-import { Trans, useTranslation } from "@/i18n/client";-import { authClient } from "@/lib/auth-client";--const emailChangeFormData = z.object({- email: z.email(),-});--const verifyEmailChangeFormData = z.object({- otp: z.string().regex(/^\d{6}$/),-});--function VerifyEmailChangeForm({- newEmail,- onSuccess,- onCancel,-}: {- newEmail: string;- onSuccess: () => Promise<void> | void;- onCancel: () => void;-}) {- const { t } = useTranslation();- const form = useForm({- defaultValues: {- otp: "",- },- resolver: zodResolver(verifyEmailChangeFormData),- });-- const handleSubmit = form.handleSubmit(async (data) => {- const res = await authClient.emailOtp.changeEmail({- newEmail,- otp: data.otp,- });-- if (res.error) {- switch (res.error.code) {- case "INVALID_OTP":- form.setError("otp", {- message: t("wrongVerificationCode", {- defaultValue: "Your verification code is incorrect",- }),- });- break;- case "OTP_EXPIRED":- form.setError("otp", {- message: t("expiredVerificationCode", {- defaultValue:- "This code has expired. Request a new one to continue.",- }),- });- break;- case "TOO_MANY_ATTEMPTS":- form.setError("otp", {- message: t("tooManyVerificationAttempts", {- defaultValue:- "Too many incorrect attempts. Request a new code to continue.",- }),- });- break;- default:- form.setError("otp", {- message: t("emailChangeVerifyError", {- defaultValue: "Verification failed. Please try again.",- }),- });- }- return;- }-- await onSuccess();- });-- return (- <Form {...form}>- <form onSubmit={handleSubmit}>- <div className="flex flex-col gap-y-4">- <Alert>- <InfoIcon />- <AlertTitle>- <Trans- i18nKey="emailChangeRequestSent"- defaults="Verify your new email address"- />- </AlertTitle>- <AlertDescription>- <p>- <Trans- i18nKey="emailChangeVerifyDescription"- defaults="Enter the 6 digit verification code we sent to {email}."- values={{ email: newEmail }}- />- </p>- </AlertDescription>- </Alert>- <FormField- control={form.control}- name="otp"- render={({ field }) => (- <FormItem>- <FormControl>- <InputOTP- disabled={form.formState.isSubmitting}- autoFocus={true}- onValidCode={() => {- handleSubmit();- }}- {...field}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <div className="mt-4 flex gap-x-2">- <Button- loading={form.formState.isSubmitting}- type="submit"- variant="primary"- >- <Trans i18nKey="verify" defaults="Verify" />- </Button>- <Button type="button" onClick={onCancel}>- <Trans i18nKey="cancel" />- </Button>- </div>- </div>- </form>- </Form>- );-}--export const ProfileEmailAddress = ({ email }: { email: string }) => {- const router = useRouter();- const { t } = useTranslation();-- const [pendingEmail, setPendingEmail] = React.useState<string | null>(null);- const [didChangeEmail, setDidChangeEmail] = React.useState(false);-- const form = useForm({- defaultValues: {- email,- },- resolver: zodResolver(emailChangeFormData),- });-- const { handleSubmit, formState, reset } = form;-- if (pendingEmail) {- return (- <VerifyEmailChangeForm- newEmail={pendingEmail}- onCancel={() => {- setPendingEmail(null);- reset({ email });- }}- onSuccess={() => {- reset({ email: pendingEmail });- setPendingEmail(null);- setDidChangeEmail(true);- // The change-email endpoint refreshes the session snapshot, so a- // refresh re-renders the layouts with the new email.- router.refresh();- }}- />- );- }-- return (- <div className="grid gap-y-4">- <Form {...form}>- <form- onSubmit={handleSubmit(async (data) => {- if (data.email === email) {- return;- }-- setDidChangeEmail(false);-- const res = await authClient.emailOtp.requestEmailChange({- newEmail: data.email,- });-- if (res.error) {- form.setError("email", {- message: t("emailChangeRequestError", {- defaultValue:- "We couldn't process this request. Please try again later.",- }),- });- return;- }-- setPendingEmail(data.email);- })}- >- <div className="flex flex-col gap-y-4">- <FormField- control={form.control}- name="email"- render={({ field }) => (- <FormItem>- <FormLabel>- <Trans i18nKey="email" />- </FormLabel>- <FormControl>- <Input- type="email"- autoComplete="email"- disabled={form.formState.isSubmitting}- {...field}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- {didChangeEmail ? (- <Alert variant="success">- <CheckCircleIcon />- <AlertDescription>- <p>- <Trans- i18nKey="emailChangeSuccess"- defaults="Email changed successfully"- />- </p>- </AlertDescription>- </Alert>- ) : null}- <div className="mt-4 flex">- <Button- loading={formState.isSubmitting}- type="submit"- disabled={!formState.isDirty}- >- <Trans i18nKey="save" />- </Button>- </div>- </div>- </form>- </Form>- </div>- );-};diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/page.tsxindex 0b7e32ea7..f8c1a1a19 100644--- a/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx@@ -31,7 +31,7 @@ import {DeleteAccountSetting,PendingDeletionSetting,} from "./components/delete-account-setting";-import { ProfileEmailAddress } from "./components/profile-email-address";+import { EmailAddressSetting } from "./components/email-address-setting";import { ProfileSettings } from "./components/profile-settings";export default async function Page() {@@ -72,7 +72,7 @@ export default async function Page() {<PageSection variant="card"><PageSectionHeader><PageSectionTitle>- <Trans i18nKey="profileEmailAddress" defaults="Email address" />+ <Trans i18nKey="profileAccount" defaults="Account" /></PageSectionTitle><PageSectionDescription><Trans@@ -82,7 +82,9 @@ export default async function Page() {</PageSectionDescription></PageSectionHeader><PageSectionContent>- <ProfileEmailAddress email={user.email} />+ <FieldGroup variant="divided">+ <EmailAddressSetting email={user.email} />+ </FieldGroup></PageSectionContent></PageSection>diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.tsindex 92ebc23c2..38a0f9e04 100644--- a/apps/web/src/features/user/actions.ts+++ b/apps/web/src/features/user/actions.ts@@ -5,6 +5,7 @@ import { supportedLngs } from "@rallly/languages";import { headers } from "next/headers";import * as z from "zod";import { avatarAssetProfile } from "@/features/user/constants";+import { isEmailTaken } from "@/features/user/data";import { banUser, unbanUser, updateUserRole } from "@/features/user/mutations";import authLib from "@/lib/auth";import { timeFormatSchema, weekStartSchema } from "@/lib/datetime/schema";@@ -70,6 +71,34 @@ export const updateLocalizationAction = authActionClient});});+// Better-Auth's request-email-change endpoint returns success without sending+// anything when the address already belongs to an account, to avoid confirming+// that it is registered. That leaves the caller unable to tell "code sent" from+// "silently skipped", so check first and report the conflict as a value. The+// address can still be claimed between this check and verification, which the+// verify step handles via its own "email already in use" error.+export const checkEmailAvailabilityAction = authActionClient+ .metadata({ actionName: "check_email_availability" })+ .use(createRateLimitMiddleware(10, "1 h"))+ .inputSchema(+ z.object({+ email: z.email(),+ }),+ )+ .action(async ({ ctx, parsedInput }) => {+ const email = parsedInput.email.toLowerCase();++ if (email === ctx.user.email.toLowerCase()) {+ return { ok: false as const, reason: "same_email" as const };+ }++ if (await isEmailTaken(email)) {+ return { ok: false as const, reason: "email_taken" as const };+ }++ return { ok: true as const };+ });+export const getAvatarUploadUrlAction = authActionClient.metadata({ actionName: "get_avatar_upload_url" }).use(createRateLimitMiddleware(10, "1 h"))diff --git a/apps/web/src/features/user/data.test.ts b/apps/web/src/features/user/data.test.tsnew file mode 100644index 000000000..3301d0e3a--- /dev/null+++ b/apps/web/src/features/user/data.test.ts@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { isEmailTaken } from "./data";++const { mockFindUnique } = vi.hoisted(() => ({+ mockFindUnique: vi.fn(),+}));++vi.mock("@rallly/database", () => ({+ prisma: {+ user: {+ findUnique: mockFindUnique,+ },+ },+}));++describe("isEmailTaken", () => {+ beforeEach(() => {+ mockFindUnique.mockReset();+ });++ it("returns true when another account already uses the address", async () => {+ mockFindUnique.mockResolvedValue({ id: "user-1" });++ await expect(isEmailTaken("[email protected]")).resolves.toBe(true);+ });++ it("returns false when no account uses the address", async () => {+ mockFindUnique.mockResolvedValue(null);++ await expect(isEmailTaken("[email protected]")).resolves.toBe(false);+ });++ it("matches addresses case-insensitively", async () => {+ mockFindUnique.mockResolvedValue({ id: "user-1" });++ await isEmailTaken("[email protected]");++ expect(mockFindUnique).toHaveBeenCalledWith({+ where: { email: "[email protected]" },+ select: { id: true },+ });+ });+});diff --git a/apps/web/src/features/user/data.ts b/apps/web/src/features/user/data.tsindex 6ae4656ea..3839eda1a 100644--- a/apps/web/src/features/user/data.ts+++ b/apps/web/src/features/user/data.ts@@ -73,6 +73,14 @@ export async function getUserDeletionDetails(userId: string) {};}+export const isEmailTaken = async (email: string) => {+ const user = await prisma.user.findUnique({+ where: { email: email.toLowerCase() },+ select: { id: true },+ });+ return !!user;+};+export const getUserHasPassword = async (userId: string) => {const account = await prisma.account.findFirst({where: {