Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Implement email change verification process

Kiran K2dbfe61f172a
diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.ts
index 61403c4a5c..a7eff49db9 100644
--- a/apps/web/app/api/user/route.ts
+++ b/apps/web/app/api/user/route.ts
@@ -1,15 +1,20 @@
import { DubApiError } from "@/lib/api/errors";
-import { withSession } from "@/lib/auth";
+import { hashToken, withSession } from "@/lib/auth";
import { storage } from "@/lib/storage";
+import { ratelimit, redis } from "@/lib/upstash";
+import { sendEmail } from "@dub/email";
import { unsubscribe } from "@dub/email/resend/unsubscribe";
+import ConfirmEmailChange from "@dub/email/templates/confirm-email-change";
import { prisma } from "@dub/prisma";
-import { R2_URL, nanoid, trim } from "@dub/utils";
+import { APP_DOMAIN, R2_URL, nanoid, trim } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
+import { randomBytes } from "crypto";
import { NextResponse } from "next/server";
import { z } from "zod";
const updateUserSchema = z.object({
name: z.preprocess(trim, z.string().min(1).max(64)).optional(),
+ email: z.preprocess(trim, z.string().email()).optional(),
image: z.string().url().optional(),
source: z.preprocess(trim, z.string().min(1).max(32)).optional(),
defaultWorkspace: z.preprocess(trim, z.string().min(1)).optional(),
@@ -57,7 +62,7 @@ export const GET = withSession(async ({ session }) => {
// PATCH /api/user – edit a specific user
export const PATCH = withSession(async ({ req, session }) => {
- let { name, image, source, defaultWorkspace } =
+ let { name, email, image, source, defaultWorkspace } =
await updateUserSchema.parseAsync(await req.json());
if (image) {
@@ -86,46 +91,94 @@ export const PATCH = withSession(async ({ req, session }) => {
}
}
- // TODO:
- // Email change should require a verification process before updating the email in the database
-
- try {
- const response = await prisma.user.update({
+ // Verify email ownership if the email is being changed
+ if (email && email !== session.user.email) {
+ const userWithEmail = await prisma.user.findUnique({
where: {
- id: session.user.id,
- },
- data: {
- ...(name && { name }),
- ...(image && { image }),
- ...(source && { source }),
- ...(defaultWorkspace && { defaultWorkspace }),
+ email,
},
});
- waitUntil(
- (async () => {
- // Delete only if a new image is uploaded and the old image exists
- if (
- image &&
- session.user.image &&
- session.user.image.startsWith(`${R2_URL}/avatars/${session.user.id}`)
- ) {
- await storage.delete(session.user.image.replace(`${R2_URL}/`, ""));
- }
- })(),
- );
-
- return NextResponse.json(response);
- } catch (error) {
- if (error.code === "P2002") {
+ if (userWithEmail) {
throw new DubApiError({
code: "conflict",
message: "Email is already in use.",
});
}
- throw error;
+ const { success } = await ratelimit(1, "1 h").limit(
+ `email-change-request:${session.user.id}`,
+ );
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message:
+ "You've requested too many email change requests. Please try again later.",
+ });
+ }
+
+ const token = randomBytes(32).toString("hex");
+ const expiresIn = 15 * 60 * 1000;
+
+ await prisma.verificationToken.create({
+ data: {
+ identifier: session.user.id,
+ token: await hashToken(token, { secret: true }),
+ expires: new Date(Date.now() + expiresIn),
+ },
+ });
+
+ await redis.set(
+ `email-change-request:user:${session.user.id}`,
+ {
+ email: session.user.email,
+ newEmail: email,
+ },
+ {
+ px: expiresIn,
+ },
+ );
+
+ waitUntil(
+ sendEmail({
+ subject: "Confirm your email address change",
+ email,
+ react: ConfirmEmailChange({
+ email: session.user.email,
+ newEmail: email,
+ confirmUrl: `${APP_DOMAIN}/auth/confirm-email-change/${token}`,
+ }),
+ }),
+ );
}
+
+ const response = await prisma.user.update({
+ where: {
+ id: session.user.id,
+ },
+ data: {
+ ...(name && { name }),
+ ...(image && { image }),
+ ...(source && { source }),
+ ...(defaultWorkspace && { defaultWorkspace }),
+ },
+ });
+
+ waitUntil(
+ (async () => {
+ // Delete only if a new image is uploaded and the old image exists
+ if (
+ image &&
+ session.user.image &&
+ session.user.image.startsWith(`${R2_URL}/avatars/${session.user.id}`)
+ ) {
+ await storage.delete(session.user.image.replace(`${R2_URL}/`, ""));
+ }
+ })(),
+ );
+
+ return NextResponse.json(response);
});
export const PUT = PATCH;
diff --git a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/token/page-client.tsx b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/token/page-client.tsx
new file mode 100644
index 0000000000..00dd8e182f
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/token/page-client.tsx
@@ -0,0 +1,36 @@
+"use client";
+
+import { EmptyState, LoadingSpinner } from "@dub/ui";
+import { useSession } from "next-auth/react";
+import { useRouter } from "next/navigation";
+import { useEffect, useRef } from "react";
+import { toast } from "sonner";
+
+export default async function ConfirmEmailChangePageClient() {
+ const router = useRouter();
+ const { update, status } = useSession();
+ const hasUpdatedSession = useRef(false);
+
+ useEffect(() => {
+ if (status !== "authenticated" || hasUpdatedSession.current) {
+ return;
+ }
+
+ async function updateSession() {
+ hasUpdatedSession.current = true;
+ await update();
+ toast.success("Successfully updated your email!");
+ router.replace("/account/settings");
+ }
+
+ updateSession();
+ }, [status, update]);
+
+ return (
+ <EmptyState
+ icon={LoadingSpinner}
+ title="Verifying Email Change"
+ description="Verifying your email change request. This might take a few seconds..."
+ />
+ );
+}
diff --git a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/token/page.tsx b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/token/page.tsx
new file mode 100644
index 0000000000..ce9f59a703
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/token/page.tsx
@@ -0,0 +1,136 @@
+import { getSession, hashToken } from "@/lib/auth";
+import { redis } from "@/lib/upstash";
+import EmptyState from "@/ui/shared/empty-state";
+import { subscribe } from "@dub/email/resend/subscribe";
+import { unsubscribe } from "@dub/email/resend/unsubscribe";
+import { prisma } from "@dub/prisma";
+import { InputPassword, LoadingSpinner } from "@dub/ui";
+import { VerificationToken } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { redirect } from "next/navigation";
+import { Suspense } from "react";
+import ConfirmEmailChangePageClient from "./page-client";
+
+export const runtime = "nodejs";
+
+interface PageProps {
+ params: { token: string };
+ searchParams: { cancel?: string };
+}
+
+export default async function ConfirmEmailChangePage(props: PageProps) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-6 text-center">
+ <Suspense
+ fallback={
+ <EmptyState
+ icon={LoadingSpinner}
+ title="Verifying Email Change"
+ description="Verifying your email change request. This might take a few seconds..."
+ />
+ }
+ >
+ <VerifyEmailChange {...props} />
+ </Suspense>
+ </div>
+ );
+}
+
+const VerifyEmailChange = async ({
+ params: { token },
+ searchParams,
+}: PageProps) => {
+ const tokenFound = await prisma.verificationToken.findUnique({
+ where: {
+ token: await hashToken(token, { secret: true }),
+ },
+ });
+
+ if (!tokenFound || tokenFound.expires < new Date()) {
+ return (
+ <EmptyState
+ icon={InputPassword}
+ title="Invalid Token"
+ description="This token is invalid or expired. Please request a new one."
+ />
+ );
+ }
+
+ // Cancel the email change request (?cancel=true)
+ const { cancel } = searchParams;
+
+ if (cancel && cancel === "true") {
+ await deleteRequest(tokenFound);
+
+ return (
+ <EmptyState
+ icon={InputPassword}
+ title="Email Change Request Cancelled"
+ description="Your email change request has been cancelled. No changes have been made to your account. You can close this page."
+ />
+ );
+ }
+
+ // Process the email change request
+ const session = await getSession();
+
+ if (!session) {
+ redirect(`/login?next=/auth/confirm-email-change/${token}`);
+ }
+
+ const currentUserId = session.user.id;
+
+ const data = await redis.get<{
+ email: string;
+ newEmail: string;
+ }>(`email-change-request:user:${currentUserId}`);
+
+ if (!data) {
+ return (
+ <EmptyState
+ icon={InputPassword}
+ title="Invalid Token"
+ description="This token is invalid. Please request a new one."
+ />
+ );
+ }
+
+ const user = await prisma.user.update({
+ where: {
+ id: currentUserId,
+ },
+ data: {
+ email: data.newEmail,
+ },
+ select: {
+ subscribed: true,
+ },
+ });
+
+ waitUntil(
+ Promise.all([
+ deleteRequest(tokenFound),
+
+ ...(user.subscribed
+ ? [
+ unsubscribe({ email: data.email }),
+ subscribe({ email: data.newEmail }),
+ ]
+ : []),
+ ]),
+ );
+
+ return <ConfirmEmailChangePageClient />;
+};
+
+const deleteRequest = async (tokenFound: VerificationToken) => {
+ await Promise.all([
+ prisma.verificationToken.delete({
+ where: {
+ token: tokenFound.token,
+ },
+ }),
+
+ redis.del(`email-change-request:user:${tokenFound.identifier}`),
+ ]);
+};
diff --git a/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx
index f562102896..b2e2fb197a 100644
--- a/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx
@@ -46,19 +46,32 @@ export default function SettingsPageClient() {
/>
<Form
title="Your Email"
- description={`This will be the email you use to log in to ${APP_NAME} and receive notifications.`}
+ description={`This will be the email you use to log in to ${APP_NAME} and receive notifications. A confirmation is required for changes.`}
inputAttrs={{
name: "email",
type: "email",
defaultValue: session?.user?.email || undefined,
placeholder: "[email protected]",
- readOnly: true,
}}
helpText={<UpdateSubscription />}
- handleSubmit={(data) => {
- return Promise.resolve();
- }}
- disabledTooltip="You can't update your email. Please contact support if you need to change it."
+ handleSubmit={(data) =>
+ fetch("/api/user", {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ }).then(async (res) => {
+ if (res.status === 200) {
+ toast.success(
+ `A confirmation email has been sent to ${data.email}.`,
+ );
+ } else {
+ const { error } = await res.json();
+ toast.error(error.message);
+ }
+ })
+ }
/>
<UploadAvatar />
<UserId />
diff --git a/apps/web/lib/integrations/shopify/create-lead.ts b/apps/web/lib/integrations/shopify/create-lead.ts
index 20edd60a41..bb91946f07 100644
--- a/apps/web/lib/integrations/shopify/create-lead.ts
+++ b/apps/web/lib/integrations/shopify/create-lead.ts
@@ -1,5 +1,4 @@
import { includeTags } from "@/lib/api/links/include-tags";
-import { transformLink } from "@/lib/api/links/utils";
import { createId } from "@/lib/api/utils";
import { generateRandomName } from "@/lib/names";
import { getClickEvent, recordLead } from "@/lib/tinybird";
diff --git a/packages/email/src/templates/confirm-email-change.tsx b/packages/email/src/templates/confirm-email-change.tsx
new file mode 100644
index 0000000000..8696ee3d71
--- /dev/null
+++ b/packages/email/src/templates/confirm-email-change.tsx
@@ -0,0 +1,72 @@
+import { DUB_WORDMARK } from "@dub/utils";
+import {
+ Body,
+ Container,
+ Head,
+ Heading,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import { Footer } from "../components/footer";
+
+export function ConfirmEmailChange({
+ email = "[email protected]",
+ newEmail = "[email protected]",
+ confirmUrl = "https://dub.co/auth/confirm-email-change",
+}: {
+ email: string;
+ newEmail: string;
+ confirmUrl: string;
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>Confirm your email address change</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img
+ src={DUB_WORDMARK}
+ height="40"
+ alt="Dub"
+ className="mx-auto my-0"
+ />
+ </Section>
+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ Confirm your email address change
+ </Heading>
+ <Text className="mx-auto text-sm leading-6">
+ Follow this link to confirm the update to your email from{" "}
+ <strong>{email}</strong> to <strong>{newEmail}</strong>.
+ </Text>
+ <Section className="my-8 text-center">
+ <Link
+ href={confirmUrl}
+ className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
+ >
+ <strong>Confirm email change</strong>
+ </Link>
+ </Section>
+ <Text className="text-sm leading-6 text-black">
+ If you did not request this change, this email can be safely
+ ignored or{" "}
+ <Link href={`${confirmUrl}?cancel=true`}>
+ cancel this request
+ </Link>
+ .
+ </Text>
+ <Footer email={newEmail} />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
+
+export default ConfirmEmailChange;