Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: update email address change verification

Marc Seitz12e833b37b63
diff --git a/app/(auth)/auth/confirm-email-change/page-client.tsx b/app/(auth)/auth/confirm-email-change/[token]/page-client.tsx
similarity index 96%
rename from app/(auth)/auth/confirm-email-change/page-client.tsx
rename to app/(auth)/auth/confirm-email-change/[token]/page-client.tsx
index cdbeddba..181cd135 100644
--- a/app/(auth)/auth/confirm-email-change/page-client.tsx
+++ b/app/(auth)/auth/confirm-email-change/[token]/page-client.tsx
@@ -22,12 +22,12 @@ export default function ConfirmEmailChangePageClient() {
async function updateSession() {
hasUpdatedSession.current = true;
await update();
- router.replace("/account/general");
toast.success("Email update successful!");
+ router.replace("/account/general");
}
updateSession();
- }, [status, update, router]);
+ }, [status, update]);
return (
<div className="flex h-screen w-full items-center justify-center">
diff --git a/app/(auth)/auth/confirm-email-change/[token]/page.tsx b/app/(auth)/auth/confirm-email-change/[token]/page.tsx
new file mode 100644
index 00000000..de70b83f
--- /dev/null
+++ b/app/(auth)/auth/confirm-email-change/[token]/page.tsx
@@ -0,0 +1,98 @@
+import { redirect } from "next/navigation";
+
+import NotFound from "@/pages/404";
+import { VerificationToken } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+
+import EmailUpdated from "@/components/emails/email-updated";
+
+import { hashToken } from "@/lib/api/auth/token";
+import prisma from "@/lib/prisma";
+import { redis } from "@/lib/redis";
+import { sendEmail } from "@/lib/resend";
+import { CustomUser } from "@/lib/types";
+import { subscribe, unsubscribe } from "@/lib/unsend";
+
+import ConfirmEmailChangePageClient from "./page-client";
+import { getSession } from "./utils";
+
+export const runtime = "nodejs";
+
+interface PageProps {
+ params: { token: string };
+}
+
+export default async function ConfirmEmailChangePage(props: PageProps) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-6 text-center">
+ <VerifyEmailChange {...props} />
+ </div>
+ );
+}
+
+const VerifyEmailChange = async ({ params: { token } }: PageProps) => {
+ const tokenFound = await prisma.verificationToken.findUnique({
+ where: {
+ token: hashToken(token),
+ },
+ });
+
+ if (!tokenFound || tokenFound.expires < new Date()) return <NotFound />;
+
+ const session = await getSession();
+
+ if (!session) {
+ redirect(`/login?next=/auth/confirm-email-change/${token}`);
+ }
+
+ const currentUserId = (session.user as CustomUser).id;
+
+ const data = await redis.get<{ email: string; newEmail: string }>(
+ `email-change-request:user:${currentUserId}`,
+ );
+
+ if (!data) return <NotFound />;
+
+ await unsubscribe(data.email);
+
+ await prisma.user.update({
+ where: {
+ id: currentUserId,
+ },
+ data: {
+ email: data.newEmail,
+ },
+ });
+
+ waitUntil(
+ Promise.all([
+ deleteRequest(tokenFound),
+
+ subscribe(data.newEmail),
+
+ sendEmail({
+ to: data.email,
+ subject: "Your email address has been changed",
+ react: EmailUpdated({
+ oldEmail: data.email,
+ newEmail: data.newEmail,
+ }),
+ test: process.env.NODE_ENV === "development",
+ }),
+ ]),
+ );
+
+ 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/app/(auth)/auth/confirm-email-change/utils.ts b/app/(auth)/auth/confirm-email-change/[token]/utils.ts
similarity index 100%
rename from app/(auth)/auth/confirm-email-change/utils.ts
rename to app/(auth)/auth/confirm-email-change/[token]/utils.ts
diff --git a/app/(auth)/auth/confirm-email-change/page.tsx b/app/(auth)/auth/confirm-email-change/page.tsx
deleted file mode 100644
index ca05ca6d..00000000
--- a/app/(auth)/auth/confirm-email-change/page.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-import { redirect } from "next/navigation";
-
-import NotFound from "@/pages/404";
-import { waitUntil } from "@vercel/functions";
-
-import EmailUpdated from "@/components/emails/email-updated";
-
-import { hashToken } from "@/lib/api/auth/token";
-import prisma from "@/lib/prisma";
-import { sendEmail } from "@/lib/resend";
-import { CustomUser } from "@/lib/types";
-import { generateChecksum } from "@/lib/utils/generate-checksum";
-
-import ConfirmEmailChangePageClient from "./page-client";
-import { getSession } from "./utils";
-
-export const runtime = "nodejs";
-
-interface ConfirmEmailChangePageProps {
- searchParams: {
- verification_url: string;
- checksum: string;
- email: string;
- newEmail: string;
- };
-}
-
-export default async function ConfirmEmailChangePage(
- props: ConfirmEmailChangePageProps,
-) {
- return (
- <div className="flex flex-col items-center justify-center gap-6 text-center">
- <VerifyEmailChange {...props} />
- </div>
- );
-}
-
-const VerifyEmailChange = async ({
- searchParams: { checksum, verification_url, email, newEmail },
-}: ConfirmEmailChangePageProps) => {
- const urlObj = new URL(verification_url);
-
- const isValidVerificationUrl = (url: string, checksum: string): boolean => {
- try {
- if (urlObj.origin !== process.env.NEXTAUTH_URL) return false;
- const expectedChecksum = generateChecksum(url);
- return checksum === expectedChecksum;
- } catch {
- return false;
- }
- };
-
- if (!isValidVerificationUrl(verification_url, checksum)) {
- return <NotFound />;
- }
-
- const token = urlObj.searchParams.get("token");
-
- if (!token) return <NotFound />;
-
- const hasToken = await prisma.verificationToken.findUnique({
- where: {
- token: hashToken(token),
- },
- });
- if (!hasToken || hasToken.expires < new Date()) {
- return <NotFound />;
- }
- const session = await getSession();
- const user = session?.user as CustomUser;
-
- if (!session) {
- redirect(`/login?next=/account/general`);
- }
-
- await prisma.user.update({
- where: {
- id: user.id,
- },
- data: {
- email: newEmail,
- },
- });
-
- waitUntil(
- sendEmail({
- to: email as string,
- subject: "Your email address has been changed",
- react: EmailUpdated({
- oldEmail: email,
- newEmail: newEmail,
- }),
- test: process.env.NODE_ENV === "development",
- }),
- );
-
- return <ConfirmEmailChangePageClient />;
-};
diff --git a/components/account/update-mailSubscribe.tsx b/components/account/update-subscription.tsx
similarity index 96%
rename from components/account/update-mailSubscribe.tsx
rename to components/account/update-subscription.tsx
index 9fcbdfde..10756861 100644
--- a/components/account/update-mailSubscribe.tsx
+++ b/components/account/update-subscription.tsx
@@ -1,7 +1,7 @@
import { useOptimisticUpdate } from "../hooks/use-optimistic-update";
import { Switch } from "../ui/switch";
-// TODO for latter use
+// TODO: MAIL SUBSCRIPTION FOR LATER USE
export const UpdateMailSubscribe = () => {
const { data, isLoading, update } = useOptimisticUpdate<{
subscribed: boolean;
diff --git a/components/emails/email-updated.tsx b/components/emails/email-updated.tsx
index 55cf1b2b..ba839049 100644
--- a/components/emails/email-updated.tsx
+++ b/components/emails/email-updated.tsx
@@ -33,8 +33,8 @@ export function EmailUpdated({
Your email address has been changed
</Text>
<Text className="text-sm leading-6 text-black">
- The e-mail address for your Papermark account has been changed
- from <strong>{oldEmail}</strong> to <strong>{newEmail}</strong>.
+ The email address for your Papermark account has been changed from{" "}
+ <strong>{oldEmail}</strong> to <strong>{newEmail}</strong>.
</Text>
<Text className="text-sm leading-6 text-black">
If you did not make this change, please contact our support team
@@ -45,7 +45,7 @@ export function EmailUpdated({
.
</Text>
<Text className="text-sm leading-6 text-black">
- This message is being sent to your old e-mail address only.
+ This message is being sent to your old email address only.
</Text>
<Hr />
<Section className="mt-8 text-gray-400">
diff --git a/components/emails/verification-mailChange.tsx b/components/emails/verification-email-change.tsx
similarity index 99%
rename from components/emails/verification-mailChange.tsx
rename to components/emails/verification-email-change.tsx
index 18d4eea4..7ebcd7ef 100644
--- a/components/emails/verification-mailChange.tsx
+++ b/components/emails/verification-email-change.tsx
@@ -15,7 +15,7 @@ import {
interface ConfirmEmailChangeProps {
email: string;
newEmail: string;
- confirmUrl?: string;
+ confirmUrl: string;
}
export function ConfirmEmailChange({
diff --git a/lib/emails/send-mail-verification.ts b/lib/emails/send-mail-verification.ts
index cd83f042..74b0c197 100644
--- a/lib/emails/send-mail-verification.ts
+++ b/lib/emails/send-mail-verification.ts
@@ -1,33 +1,23 @@
-import ConfirmEmailChange from "@/components/emails/verification-mailChange";
+import ConfirmEmailChange from "@/components/emails/verification-email-change";
import { sendEmail } from "@/lib/resend";
-import { generateChecksum } from "../utils/generate-checksum";
-
export const sendEmailChangeVerificationRequestEmail = async (params: {
email: string;
url: string;
newEmail: string;
}) => {
const { url, email, newEmail } = params;
- const checksum = generateChecksum(url);
- const verificationUrlParams = new URLSearchParams({
- verification_url: url,
- email,
- newEmail,
- checksum,
- }).toString();
- const confirmUrl = `${process.env.NEXTAUTH_URL}/auth/confirm-email-change?${verificationUrlParams}`;
const emailTemplate = ConfirmEmailChange({
- confirmUrl,
+ confirmUrl: url,
email,
newEmail,
});
try {
await sendEmail({
- to: email as string,
+ to: email,
subject: "Confirm your email address change for Papermark!",
react: emailTemplate,
test: process.env.NODE_ENV === "development",
diff --git a/pages/account/general.tsx b/pages/account/general.tsx
index 382f7536..dafcd87a 100644
--- a/pages/account/general.tsx
+++ b/pages/account/general.tsx
@@ -20,7 +20,7 @@ const ProfilePage: NextPage = () => {
<div className="space-y-6">
<Form
title="Your Name"
- description="This will be your display name on Papermark.io."
+ description="This will be your display name on Papermark."
inputAttrs={{
name: "name",
placeholder: "Dino Hems",
@@ -36,7 +36,7 @@ const ProfilePage: NextPage = () => {
},
body: JSON.stringify(data),
}).then(async (res) => {
- if (res.status === 201) {
+ if (res.status === 200) {
update();
toast.success("Successfully updated your name!");
} else {
@@ -48,7 +48,7 @@ const ProfilePage: NextPage = () => {
/>
<Form
title="Your Email"
- description="This will be the email you use to log in to Papermark.io and receive notification. A confirmation is required for changes."
+ description="This will be the email you use to log in to Papermark and receive notification. A confirmation is required for changes."
inputAttrs={{
name: "email",
placeholder: "[email protected]",
@@ -68,21 +68,20 @@ const ProfilePage: NextPage = () => {
},
body: JSON.stringify(data),
}).then(async (res) => {
- if (res.status === 201) {
- update();
+ 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);
+ toast.error(error);
}
})
}
/>
<UploadAvatar
title="Your Avatar"
- description={`This is your avatar image on ${process.env.NEXT_PUBLIC_BASE_URL}.`}
+ description="This is your avatar image on Papermark."
helpText="Square image recommended. Accepted file types: .png, .jpg. Max file
size: 2MB."
/>
diff --git a/pages/api/account/index.tsx b/pages/api/account/index.ts
similarity index 75%
rename from pages/api/account/index.tsx
rename to pages/api/account/index.ts
index b56a8e75..9e301569 100644
--- a/pages/api/account/index.tsx
+++ b/pages/api/account/index.ts
@@ -1,6 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { waitUntil } from "@vercel/functions";
+import { randomBytes } from "crypto";
import { getServerSession } from "next-auth";
import { z } from "zod";
@@ -9,7 +10,7 @@ import { sendEmailChangeVerificationRequestEmail } from "@/lib/emails/send-mail-
import { errorhandler } from "@/lib/errorHandler";
import { newId } from "@/lib/id-helper";
import prisma from "@/lib/prisma";
-import { ratelimit } from "@/lib/redis";
+import { ratelimit, redis } from "@/lib/redis";
import { CustomUser } from "@/lib/types";
import { trim } from "@/lib/utils";
@@ -32,13 +33,13 @@ export default async function handle(
res.status(401).end("Unauthorized");
throw new Error("Unauthorized");
}
- const user = session.user as CustomUser;
+ const sessionUser = session.user as CustomUser;
const { email, image, name } = await updateUserSchema.parseAsync(
await req.body,
);
try {
- if (email && email !== session.user?.email) {
+ if (email && email !== sessionUser.email) {
const userWithEmail = await prisma.user.findUnique({
where: {
email,
@@ -48,36 +49,49 @@ export default async function handle(
throw new Error("Email is already in use.");
}
const { success } = await ratelimit(6, "6 h").limit(
- `email-change-request:${user.id}`,
+ `email-change-request:${sessionUser.id}`,
);
if (!success) {
throw new Error(
"You've requested too many email change requests. Please try again later.",
);
}
- const token = newId("email");
+ const token = randomBytes(32).toString("hex");
const expiresIn = 15 * 60 * 1000;
+
await prisma.verificationToken.create({
data: {
- identifier: user.id,
+ identifier: sessionUser.id,
token: hashToken(token),
expires: new Date(Date.now() + expiresIn),
},
});
+
+ await redis.set(
+ `email-change-request:user:${sessionUser.id}`,
+ {
+ email: sessionUser.email,
+ newEmail: email,
+ },
+ {
+ px: expiresIn,
+ },
+ );
+
waitUntil(
sendEmailChangeVerificationRequestEmail({
- email: user.email as string,
+ email: sessionUser.email as string,
newEmail: email,
- url: `${process.env.NEXTAUTH_URL}/auth/confirm-email-change?token=${token}`,
+ url: `${process.env.NEXTAUTH_URL}/auth/confirm-email-change/${token}`,
}),
);
- return res.status(201).json({ message: "success" });
+ return res.status(200).json({ message: "success" });
}
const response = await prisma.user.update({
where: {
- id: user.id,
+ id: sessionUser.id,
},
data: {
...(name && { name }),
@@ -85,7 +99,7 @@ export default async function handle(
},
});
- return res.status(201).json(response);
+ return res.status(200).json(response);
} catch (error) {
errorhandler(error, res);
}
diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].ts
index 4ebe1545..365f85b9 100644
--- a/pages/api/auth/[...nextauth].ts
+++ b/pages/api/auth/[...nextauth].ts
@@ -114,6 +114,15 @@ export const authOptions: NextAuthOptions = {
} else {
return {};
}
+
+ if (refreshedUser?.email !== user.email) {
+ // if user has changed email, delete all accounts for the user
+ if (user.id && refreshedUser.email) {
+ await prisma.account.deleteMany({
+ where: { userId: user.id },
+ });
+ }
+ }
}
return token;
},