Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Migrate email change flow to Better Auth's OTP endpoints (#2433)
Luke Vella3b26d8f9896e
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex c98cdcd6d..e2fe9db97 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -226,12 +226,11 @@"editSettings": "Edit settings","editVotes": "Edit votes","email": "Email",- "emailAlreadyInUse": "This email address is already associated with another account. Please use a different email address.",- "emailChangeInvalidToken": "The verification link is invalid or has expired. Please try again.",- "emailChangeInvalidUserId": "Please login with the same email address as the one you used to request the change.",+ "emailChangeRequestError": "We couldn't process this request. Please try again later.","emailChangeRequestSent": "Verify your new email address",- "emailChangeRequestSentDescription": "To complete the change, please check your email for a verification link.","emailChangeSuccess": "Email changed successfully",+ "emailChangeVerifyDescription": "Enter the 6 digit verification code we sent to {email}.",+ "emailChangeVerifyError": "Verification failed. Please try again.","emailDoesNotMatch": "The email address does not match.","emailMismatch": "Email does not match the account email","emailNotAllowed": "This email is not allowed.",@@ -558,7 +557,6 @@"saved": "Saved","saveInstruction": "Select your availability and click <b>{action}</b>","saving": "Saving...",- "schedulateDate": "Scheduled Date","schedulePoll": "Schedule","schedulePollDescription": "Select a final date for your event.","scrollLeft": "Scroll Left",@@ -678,6 +676,7 @@"validEmail": "Please enter a valid email","verificationCodeHelp": "Didn't get the email? Check your spam/junk.","verificationCodePlaceholder": "Enter your 6-digit code",+ "verify": "Verify","verifyEmail": "Verify your email","viewPoll": "View poll","viewResults": "View results",diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/profile-email-address.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/profile-email-address.tsxindex e77885490..ac4196c8d 100644--- a/apps/web/src/app/[locale]/(space)/settings/profile/profile-email-address.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/profile/profile-email-address.tsx@@ -12,61 +12,208 @@ import {FormMessage,} from "@rallly/ui/form";import { Input } from "@rallly/ui/input";-import { CheckCircleIcon, InfoIcon, XIcon } from "lucide-react";-import { useSearchParams } from "next/navigation";+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";import { trpc } from "@/trpc/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+ placeholder={t("verificationCodePlaceholder")}+ 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 = () => {const [user] = trpc.user.getAuthed.useSuspenseQuery();- const requestEmailChange = trpc.user.requestEmailChange.useMutation();+ const utils = trpc.useUtils();+ 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: user.email,},resolver: zodResolver(emailChangeFormData),});- const { t } = useTranslation();-- const searchParams = useSearchParams();- const error = searchParams.get("error");- const didEmailChange = searchParams.get("emailChanged") === "true";-- const [didRequestEmailChange, setDidRequestEmailChange] =- React.useState(false);const { handleSubmit, formState, reset } = form;+ if (pendingEmail) {+ return (+ <VerifyEmailChangeForm+ newEmail={pendingEmail}+ onCancel={() => {+ setPendingEmail(null);+ reset({ email: user.email });+ }}+ onSuccess={async () => {+ reset({ email: pendingEmail });+ setPendingEmail(null);+ setDidChangeEmail(true);+ await utils.user.getAuthed.invalidate();+ router.refresh();+ }}+ />+ );+ }+return (<div className="grid gap-y-4"><Form {...form}><formonSubmit={handleSubmit(async (data) => {- if (data.email !== user.email) {- const res = await requestEmailChange.mutateAsync({- email: data.email,+ if (data.email === user.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.",+ }),});- if (res.success === false) {- if (res.reason === "emailAlreadyInUse") {- form.setError("email", {- message: t("emailAlreadyInUse", {- defaultValue:- "This email address is already associated with another account. Please use a different email address.",- }),- });- }- } else {- setDidRequestEmailChange(true);- reset(data);- }+ return;}++ setPendingEmail(data.email);})}><div className="flex flex-col gap-y-4">@@ -85,26 +232,7 @@ export const ProfileEmailAddress = () => {</FormItem>)}/>- {didRequestEmailChange ? (- <Alert>- <InfoIcon />- <AlertTitle>- <Trans- i18nKey="emailChangeRequestSent"- defaults="Verify your new email address"- />- </AlertTitle>- <AlertDescription>- <p>- <Trans- i18nKey="emailChangeRequestSentDescription"- defaults="To complete the change, please check your email for a verification link."- />- </p>- </AlertDescription>- </Alert>- ) : null}- {didEmailChange ? (+ {didChangeEmail ? (<Alert variant="success"><CheckCircleIcon /><AlertDescription>@@ -117,32 +245,6 @@ export const ProfileEmailAddress = () => {</AlertDescription></Alert>) : null}- {error === "invalidToken" ? (- <Alert variant="warning">- <XIcon />- <AlertDescription>- <p>- <Trans- i18nKey="emailChangeInvalidToken"- defaults="The verification link is invalid or has expired. Please try again."- />- </p>- </AlertDescription>- </Alert>- ) : null}- {error === "invalidUserId" ? (- <Alert variant="warning">- <XIcon />- <AlertDescription>- <p>- <Trans- i18nKey="emailChangeInvalidUserId"- defaults="Please login with the same email address as the one you used to request the change."- />- </p>- </AlertDescription>- </Alert>- ) : null}<div className="mt-4 flex"><Buttonloading={formState.isSubmitting}diff --git a/apps/web/src/app/api/user/verify-email-change/route.ts b/apps/web/src/app/api/user/verify-email-change/route.tsdeleted file mode 100644index caba38b94..000000000--- a/apps/web/src/app/api/user/verify-email-change/route.ts+++ /dev/null@@ -1,82 +0,0 @@-import { stripe } from "@rallly/billing";-import { prisma } from "@rallly/database";-import { absoluteUrl } from "@rallly/utils/absolute-url";-import * as Sentry from "@sentry/nextjs";-import type { NextRequest } from "next/server";-import { NextResponse } from "next/server";-import { posthog } from "@/features/analytics/posthog";-import { getSession } from "@/lib/auth";-import { withPostHog } from "@/utils/posthog";-import { decryptToken } from "@/utils/session";--type EmailChangePayload = {- userId: string;- toEmail: string;-};--const handler = async (request: NextRequest) => {- const token = request.nextUrl.searchParams.get("token");-- if (!token) {- return NextResponse.json({ error: "No token provided" }, { status: 400 });- }-- const session = await getSession();-- if (!session?.user || session.user.isGuest) {- const loginUrl = new URL(absoluteUrl("/login"));- loginUrl.searchParams.set(- "redirectTo",- `${request.nextUrl.pathname}${request.nextUrl.search}`,- );- return NextResponse.redirect(loginUrl);- }-- const payload = await decryptToken<EmailChangePayload>(token);-- if (!payload) {- return NextResponse.redirect(- absoluteUrl("/settings/profile?error=invalidToken"),- );- }-- if (payload.userId !== session.user.id) {- return NextResponse.redirect(- absoluteUrl("/settings/profile?error=invalidUserId"),- );- }-- const user = await prisma.user.update({- where: { id: payload.userId },- data: { email: payload.toEmail },- select: {- customerId: true,- },- });-- try {- if (user.customerId) {- await stripe.customers.update(user.customerId, {- email: payload.toEmail,- });- }- } catch (error) {- Sentry.captureException(error);- }-- posthog()?.capture({- event: "account_email_change_complete",- distinctId: session.user.id,- properties: {- $set: {- email: payload.toEmail,- },- },- });-- return NextResponse.redirect(- absoluteUrl("/settings/profile?emailChanged=true"),- );-};--export const GET = withPostHog(handler);diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.tsindex 9e69102b2..7e05fe0fb 100644--- a/apps/web/src/lib/auth.ts+++ b/apps/web/src/lib/auth.ts@@ -1,4 +1,6 @@+import { stripe } from "@rallly/billing";import { prisma } from "@rallly/database";+import { sendChangeEmailEmail } from "@rallly/emails/templates/change-email";import { sendRegisterEmail } from "@rallly/emails/templates/register";import { sendResetPasswordEmail } from "@rallly/emails/templates/reset-password";import { createLogger } from "@rallly/logger";@@ -6,7 +8,7 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";import type { BetterAuthPlugin } from "better-auth";import { APIError, betterAuth } from "better-auth";import { prismaAdapter } from "better-auth/adapters/prisma";-import { createAuthMiddleware } from "better-auth/api";+import { createAuthMiddleware, getSessionFromCtx } from "better-auth/api";import { nextCookies } from "better-auth/next-js";import {admin,@@ -151,6 +153,9 @@ export const authLib = betterAuth({disableSignUp: true,expiresIn: 15 * 60,overrideDefaultEmailVerification: true,+ changeEmail: {+ enabled: true,+ },async sendVerificationOTP({ email, otp, type }) {const locale = await getLocale(); // TODO: Get locale from emailconst branding = await getInstanceBranding();@@ -168,6 +173,16 @@ export const authLib = betterAuth({}),);break;+ case "change-email":+ after(() =>+ sendChangeEmailEmail({+ to: email,+ locale,+ branding,+ props: { code: otp },+ }),+ );+ break;}},}),@@ -235,6 +250,10 @@ export const authLib = betterAuth({window: 60 * 60, // 1 hourmax: 100,},+ "/email-otp/request-email-change": {+ window: 60 * 60, // 1 hour+ max: 5,+ },},},account: {@@ -256,15 +275,19 @@ export const authLib = betterAuth({ctx.path.startsWith("/sign-up") ||ctx.path.startsWith("/email-otp")) {- if (ctx.body?.email) {- if (isEmailBlocked(ctx.body.email as string)) {+ // The email change endpoints submit the address as `newEmail`+ const email = (ctx.body?.email ?? ctx.body?.newEmail) as+ | string+ | undefined;+ if (email) {+ if (isEmailBlocked(email)) {throw new APIError("BAD_REQUEST", {code: "EMAIL_BLOCKED",message:"This email address is not allowed. Please use a different email or contact support.",});}- if (isTemporaryEmail(ctx.body.email as string)) {+ if (isTemporaryEmail(email)) {throw new APIError("BAD_REQUEST", {code: "TEMPORARY_EMAIL_NOT_ALLOWED",message:@@ -274,6 +297,79 @@ export const authLib = betterAuth({}}}),+ after: createAuthMiddleware(async (ctx) => {+ if (+ ctx.path !== "/email-otp/request-email-change" &&+ ctx.path !== "/email-otp/change-email"+ ) {+ return;+ }++ const returned = ctx.context.returned as+ | { success?: boolean }+ | undefined;++ if (returned?.success !== true) {+ return;+ }++ const path = ctx.path;+ const newEmail = (ctx.body?.newEmail as string).toLowerCase();++ // Run side effects after the response so they can't fail or delay an+ // email change that Better-Auth has already accepted.+ after(async () => {+ try {+ const session = await getSessionFromCtx(ctx);++ if (!session) {+ return;+ }++ if (path === "/email-otp/request-email-change") {+ posthog()?.capture({+ event: "account_email_change_request",+ distinctId: session.user.id,+ properties: {+ fromEmail: session.user.email,+ toEmail: newEmail,+ },+ });+ return;+ }++ const user = await prisma.user.findUnique({+ where: { id: session.user.id },+ select: { customerId: true },+ });++ if (user?.customerId) {+ try {+ await stripe.customers.update(user.customerId, {+ email: newEmail,+ });+ } catch (error) {+ logger.error(+ { error },+ "Failed to update Stripe customer email after email change",+ );+ }+ }++ posthog()?.capture({+ event: "account_email_change_complete",+ distinctId: session.user.id,+ properties: {+ $set: {+ email: newEmail,+ },+ },+ });+ } catch (error) {+ logger.error({ error }, "Failed to run email change side effects");+ }+ });+ }),},databaseHooks: {user: {diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.tsindex 94defb034..dc0225c99 100644--- a/apps/web/src/trpc/routers/user.ts+++ b/apps/web/src/trpc/routers/user.ts@@ -1,18 +1,14 @@import { subject } from "@casl/ability";import { prisma } from "@rallly/database";import { sendRawEmail } from "@rallly/emails";-import { sendChangeEmailRequest } from "@rallly/emails/templates/change-email-request";-import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import * as z from "zod";-import { getInstanceBranding } from "@/emails/branding";import { posthog } from "@/features/analytics/posthog";import { feedbackSchema } from "@/features/feedback/schema";import { defaultNotificationPreferences } from "@/features/notifications/constants";import { getNotificationPreferences } from "@/features/notifications/queries";import { activityEventTypes } from "@/features/notifications/schema";import { defineAbilityFor } from "@/features/user/ability";-import { createToken } from "@/utils/session";import { timezoneSchema } from "@/utils/timezone-schema";import {createRateLimitMiddleware,@@ -58,69 +54,6 @@ export const user = router({return { success: true };}),- requestEmailChange: privateProcedure- .input(z.object({ email: z.email() }))- .use(createRateLimitMiddleware("request_email_change", 5, "1 h"))- .mutation(async ({ input, ctx }) => {- const currentUser = await prisma.user.findUnique({- where: { id: ctx.user.id },- select: { email: true, id: true, locale: true },- });-- if (!currentUser) {- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "User not found",- });- }-- // check if the email is already in use- const existingUser = await prisma.user.count({- where: { email: input.email },- });-- if (existingUser) {- return {- success: false as const,- reason: "emailAlreadyInUse" as const,- };- }-- // create a verification token- const token = await createToken(- {- userId: currentUser.id,- toEmail: input.email,- },- {- ttl: 60 * 10,- },- );-- sendChangeEmailRequest({- to: input.email,- locale: currentUser.locale ?? undefined,- branding: await getInstanceBranding(),- props: {- verificationUrl: absoluteUrl(- `/api/user/verify-email-change?token=${token}`,- ),- fromEmail: currentUser.email,- toEmail: input.email,- },- });-- posthog()?.capture({- event: "account_email_change_request",- distinctId: ctx.user.id,- properties: {- toEmail: input.email,- fromEmail: currentUser.email,- },- });-- return { success: true as const };- }),deleteMe: privateProcedure.mutation(async ({ ctx }) => {const userId = ctx.user.id;diff --git a/packages/emails/locales/en/emails.json b/packages/emails/locales/en/emails.jsonindex 866f25719..a1f0c54a3 100644--- a/packages/emails/locales/en/emails.json+++ b/packages/emails/locales/en/emails.json@@ -8,13 +8,12 @@"abandoned_checkout_signoff": "Best regards,","abandoned_checkout_subject": "Get {discount}% off your first year of Rallly Pro","abandoned_checkout_support": "If you have any questions about Rallly Pro or need help with anything at all, just reply to this email. I'm here to help!",- "changeEmailRequest_button": "Verify Email Address",- "changeEmailRequest_heading": "Verify Your New Email Address",- "changeEmailRequest_preview": "Please verify your email address",- "changeEmailRequest_subject": "Verify your new email address",- "changeEmailRequest_text1": "We've received a request to change the email address for your account from <b>{fromEmail}</b> to <b>{toEmail}</b>.",- "changeEmailRequest_text2": "To complete this change, please click the button below:",- "changeEmailRequest_text3": "This link will expire in 10 minutes. If you did not request this change, please ignore this email.",+ "changeEmail_codeValid": "This code is valid for 15 minutes",+ "changeEmail_content2": "You're receiving this email because a request was made to change the email address of an account on <domain />. If this wasn't you contact <a>{supportEmail}</a>.",+ "changeEmail_heading": "Verify your new email address",+ "changeEmail_preview": "Your 6-digit code is: {code}",+ "changeEmail_subject": "Verify your new email address",+ "changeEmail_text": "Please use the following 6-digit verification code to confirm your new email address","common_disableNotifications": "You can <a>manage your notification settings</a> to stop receiving these emails.","common_poweredBy": "Powered by <a>{domain}</a>","common_viewOn": "View on {domain}",diff --git a/packages/emails/src/previews/change-email-request.tsx b/packages/emails/src/previews/change-email-request.tsxdeleted file mode 100644index 6444c846a..000000000--- a/packages/emails/src/previews/change-email-request.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { previewEmailContext } from "../components/email-context";-import { ChangeEmailRequest } from "../templates/change-email-request";--export default function ChangeEmailRequestPreview() {- return (- <ChangeEmailRequest- fromEmail="[email protected]"- toEmail="[email protected]"- verificationUrl="https://rallly.co/verify-email-change?token=1234567890"- ctx={previewEmailContext}- />- );-}diff --git a/packages/emails/src/previews/change-email.tsx b/packages/emails/src/previews/change-email.tsxnew file mode 100644index 000000000..b47c68d7d--- /dev/null+++ b/packages/emails/src/previews/change-email.tsx@@ -0,0 +1,6 @@+import { previewEmailContext } from "../components/email-context";+import { ChangeEmailEmail } from "../templates/change-email";++export default function ChangeEmailEmailPreview() {+ return <ChangeEmailEmail code="123456" ctx={previewEmailContext} />;+}diff --git a/packages/emails/src/templates/change-email-request.tsx b/packages/emails/src/templates/change-email-request.tsxdeleted file mode 100644index 4048a56cb..000000000--- a/packages/emails/src/templates/change-email-request.tsx+++ /dev/null@@ -1,78 +0,0 @@-import { Section } from "@react-email/components";-import { Trans } from "react-i18next/TransWithoutContext";--import { EmailLayout } from "../components/email-layout";-import { Button, Heading, Text } from "../components/styled-components";-import { createEmailTemplate } from "../create-email-template";-import type { EmailContext } from "../types";--interface ChangeEmailRequestProps {- ctx: EmailContext;- verificationUrl: string;- fromEmail: string;- toEmail: string;-}--export const ChangeEmailRequest = ({- ctx,- verificationUrl,- fromEmail,- toEmail,-}: ChangeEmailRequestProps) => {- return (- <EmailLayout- ctx={ctx}- preview={ctx.t("changeEmailRequest_preview", {- ns: "emails",- defaultValue: "Please verify your email address",- })}- >- <Heading>- {ctx.t("changeEmailRequest_heading", {- defaultValue: "Verify Your New Email Address",- ns: "emails",- })}- </Heading>- <Text>- <Trans- {...ctx.i18nProps}- i18nKey="changeEmailRequest_text1"- defaults="We've received a request to change the email address for your account from <b>{fromEmail}</b> to <b>{toEmail}</b>."- values={{ fromEmail, toEmail }}- components={{ b: <b /> }}- />- </Text>- <Text>- {ctx.t("changeEmailRequest_text2", {- defaultValue:- "To complete this change, please click the button below:",- ns: "emails",- })}- </Text>- <Section>- <Button href={verificationUrl} color={ctx.primaryColor}>- {ctx.t("changeEmailRequest_button", {- ns: "emails",- defaultValue: "Verify Email Address",- })}- </Button>- </Section>- <Text light>- {ctx.t("changeEmailRequest_text3", {- ns: "emails",- defaultValue:- "This link will expire in 10 minutes. If you did not request this change, please contact support.",- })}- </Text>- </EmailLayout>- );-};--export const sendChangeEmailRequest = createEmailTemplate({- component: ChangeEmailRequest,- subject: (_props, ctx) =>- ctx.t("changeEmailRequest_subject", {- defaultValue: "Verify your new email address",- ns: "emails",- }),-});diff --git a/packages/emails/src/templates/change-email.tsx b/packages/emails/src/templates/change-email.tsxnew file mode 100644index 000000000..eddc22586--- /dev/null+++ b/packages/emails/src/templates/change-email.tsx@@ -0,0 +1,93 @@+import { Section } from "@react-email/components";+import { Trans } from "react-i18next/TransWithoutContext";++import { EmailLayout } from "../components/email-layout";+import {+ Card,+ Domain,+ Heading,+ Link,+ Text,+ trackingWide,+} from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";+import type { EmailContext } from "../types";++interface ChangeEmailEmailProps {+ code: string;+ ctx: EmailContext;+}++export const ChangeEmailEmail = ({ code, ctx }: ChangeEmailEmailProps) => {+ return (+ <EmailLayout+ ctx={ctx}+ preview={ctx.t("changeEmail_preview", {+ ns: "emails",+ defaultValue: "Your 6-digit code is: {code}",+ code,+ })}+ >+ <Heading>+ {ctx.t("changeEmail_heading", {+ defaultValue: "Verify your new email address",+ ns: "emails",+ })}+ </Heading>+ <Text>+ {ctx.t("changeEmail_text", {+ defaultValue:+ "Please use the following 6-digit verification code to confirm your new email address",+ ns: "emails",+ })}+ </Text>+ <Card style={{ textAlign: "center" }}>+ <Text+ style={{+ ...trackingWide,+ textAlign: "center",+ fontSize: "32px",+ fontWeight: "bold",+ }}+ id="code"+ >+ {code}+ </Text>+ <Text style={{ textAlign: "center" }} light={true}>+ {ctx.t("changeEmail_codeValid", {+ defaultValue: "This code is valid for 15 minutes",+ ns: "emails",+ })}+ </Text>+ </Card>+ <Section>+ <Text light={true}>+ <Trans+ {...ctx.i18nProps}+ i18nKey="changeEmail_content2"+ defaults="You're receiving this email because a request was made to change the email address of an account on <domain />. If this wasn't you contact <a>{supportEmail}</a>."+ values={{ supportEmail: ctx.supportEmail }}+ components={{+ domain: <Domain ctx={ctx} />,+ a: (+ <Link+ color={ctx.primaryColor}+ href={`mailto:${ctx.supportEmail}`}+ />+ ),+ }}+ />+ </Text>+ </Section>+ </EmailLayout>+ );+};++export const sendChangeEmailEmail = createEmailTemplate({+ component: ChangeEmailEmail,+ subject: (_props, ctx) =>+ ctx.t("changeEmail_subject", {+ defaultValue: "Verify your new email address",+ ns: "emails",+ }),+});