Skip to content

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

feat: improve auth email verification

Marc Seitz2460e7eb1520
diff --git a/components/links/link-sheet/email-authentication-section.tsx b/components/links/link-sheet/email-authentication-section.tsx
new file mode 100644
index 00000000..080e93e6
--- /dev/null
+++ b/components/links/link-sheet/email-authentication-section.tsx
@@ -0,0 +1,50 @@
+import { Dispatch, SetStateAction, useState, useEffect } from "react";
+import { Switch } from "@/components/ui/switch";
+import { cn } from "@/lib/utils";
+import { DEFAULT_LINK_TYPE } from ".";
+
+export default function EmailAuthenticationSection({
+ data,
+ setData,
+}: {
+ data: DEFAULT_LINK_TYPE;
+ setData: Dispatch<SetStateAction<DEFAULT_LINK_TYPE>>;
+}) {
+ const { emailProtected, emailAuthenticated } = data;
+ const [enabled, setEnabled] = useState<boolean>(true);
+
+ useEffect(() => {
+ setEnabled(emailAuthenticated);
+ }, [emailAuthenticated]);
+
+ const handleEnableAuthentication = () => {
+ const updatedEmailAuthentication = !enabled;
+ setData({
+ ...data,
+ emailProtected: updatedEmailAuthentication ? true : emailProtected,
+ emailAuthenticated: updatedEmailAuthentication,
+ });
+ setEnabled(updatedEmailAuthentication);
+ };
+
+ return (
+ <div className="pb-5">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center justify-between space-x-2">
+ <h2
+ className={cn(
+ "text-sm font-medium leading-6",
+ enabled ? "text-foreground" : "text-muted-foreground",
+ )}
+ >
+ Require email authentication to view
+ </h2>
+ </div>
+ <Switch
+ checked={enabled}
+ onCheckedChange={handleEnableAuthentication}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/components/links/link-sheet/email-protection-section.tsx b/components/links/link-sheet/email-protection-section.tsx
index 2ea159ea..d02bfd12 100644
--- a/components/links/link-sheet/email-protection-section.tsx
+++ b/components/links/link-sheet/email-protection-section.tsx
@@ -10,7 +10,7 @@ export default function EmailProtectionSection({
data: DEFAULT_LINK_TYPE;
setData: Dispatch<SetStateAction<DEFAULT_LINK_TYPE>>;
}) {
- const { emailProtected } = data;
+ const { emailProtected, emailAuthenticated } = data;
const [enabled, setEnabled] = useState<boolean>(true);
useEffect(() => {
@@ -19,7 +19,11 @@ export default function EmailProtectionSection({
const handleEnableProtection = () => {
const updatedEmailProtection = !enabled;
- setData({ ...data, emailProtected: updatedEmailProtection });
+ setData({
+ ...data,
+ emailProtected: updatedEmailProtection,
+ emailAuthenticated: !updatedEmailProtection && false,
+ });
setEnabled(updatedEmailProtection);
};
diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsx
index e63b2889..19e8eb42 100644
--- a/components/links/link-sheet/index.tsx
+++ b/components/links/link-sheet/index.tsx
@@ -25,6 +25,7 @@ import DomainSection from "./domain-section";
import AllowDownloadSection from "./allow-download-section";
import { useTeam } from "@/context/team-context";
import AllowNotificationSection from "./allow-notification";
+import EmailAuthenticationSection from "./email-authentication-section";
export const DEFAULT_LINK_PROPS = {
id: null,
@@ -34,6 +35,7 @@ export const DEFAULT_LINK_PROPS = {
expiresAt: null,
password: null,
emailProtected: true,
+ emailAuthenticated: false,
allowDownload: false,
enableNotification: true,
};
@@ -46,6 +48,7 @@ export type DEFAULT_LINK_TYPE = {
expiresAt: Date | null;
password: string | null;
emailProtected: boolean;
+ emailAuthenticated: boolean;
allowDownload: boolean;
enableNotification: boolean;
};
@@ -188,6 +191,7 @@ export default function LinkSheet({
<div>
<EmailProtectionSection {...{ data, setData }} />
+ <EmailAuthenticationSection {...{ data, setData }} />
<AllowDownloadSection {...{ data, setData }} />
<PasswordSection {...{ data, setData }} />
<ExpirationSection {...{ data, setData }} />
diff --git a/components/view/document-view.tsx b/components/view/document-view.tsx
index 54343f6c..997da414 100644
--- a/components/view/document-view.tsx
+++ b/components/view/document-view.tsx
@@ -10,6 +10,8 @@ import LoadingSpinner from "@/components/ui/loading-spinner";
import { ExtendedRecordMap } from "notion-types";
import EmailVerificationMessage from "./email-verification-form";
import ViewData from "./view-data";
+import { is } from "date-fns/locale";
+import handle from "@/pages/api/record_reaction";
export type DEFAULT_DOCUMENT_VIEW_TYPE = {
viewId: string;
@@ -22,26 +24,27 @@ export default function DocumentView({
userEmail,
userId,
isProtected,
+ hasEmailVerification,
notionData,
- authenticationCode,
+ token,
+ verifiedEmail,
}: {
link: LinkWithDocument;
- authenticationCode: string | undefined;
userEmail: string | null | undefined;
userId: string | null | undefined;
isProtected: boolean;
- notionData: {
+ hasEmailVerification: boolean;
+ notionData?: {
rootNotionPageId: string | null;
recordMap: ExtendedRecordMap | null;
};
+ token: string | undefined;
+ verifiedEmail: string | undefined;
}) {
const { document, emailProtected, password: linkPassword } = link;
const plausible = usePlausible();
- const [isEmailVerified, setIsEmailVerified] = useState<boolean>(false);
- const [verificationRequested, setVerificationRequested] =
- useState<boolean>(false);
const didMount = useRef<boolean>(false);
const [submitted, setSubmitted] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(false);
@@ -53,6 +56,8 @@ export default function DocumentView({
const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>(
DEFAULT_ACCESS_FORM_DATA,
);
+ const [verificationRequested, setVerificationRequested] =
+ useState<boolean>(false);
const handleSubmission = async (): Promise<void> => {
setIsLoading(true);
@@ -69,16 +74,24 @@ export default function DocumentView({
userId: userId || null,
documentVersionId: document.versions[0].id,
hasPages: document.versions[0].hasPages,
+ token: token || null,
}),
});
if (response.ok) {
- const { viewId, file, pages } =
- (await response.json()) as DEFAULT_DOCUMENT_VIEW_TYPE;
- plausible("documentViewed"); // track the event
- setViewData({ viewId, file, pages });
- setSubmitted(true);
- setIsLoading(false);
+ const data = await response.json();
+
+ if (data.type === "email-verification") {
+ setVerificationRequested(true);
+ setIsLoading(false);
+ } else {
+ const { viewId, file, pages } = data as DEFAULT_DOCUMENT_VIEW_TYPE;
+ plausible("documentViewed"); // track the event
+ setViewData({ viewId, file, pages });
+ setSubmitted(true);
+ setVerificationRequested(false);
+ setIsLoading(false);
+ }
} else {
const { message } = await response.json();
toast.error(message);
@@ -90,9 +103,16 @@ export default function DocumentView({
event: React.FormEvent,
): Promise<void> => {
event.preventDefault();
- await handleEmailVerification();
+ await handleSubmission();
};
+ // If token is present, run handle submit which will verify token and get document
+ useEffect(() => {
+ if (token) {
+ handleSubmission();
+ }
+ }, [token]);
+
// If link is not submitted and does not have email / password protection, show the access form
useEffect(() => {
if (!didMount.current) {
@@ -103,97 +123,7 @@ export default function DocumentView({
}
}, [submitted, isProtected]);
- //Generates verification link from backend
- const handleEmailVerification = async () => {
- setIsLoading(true);
- const URL = `/api/verification/email_authcode`;
- const response = await fetch(URL, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- identifier: link.id,
- email: data.email,
- emailProtected: link.emailProtected,
- password: link.password,
- }),
- });
- if (response.ok) {
- //If only password protected, show the document if password is verified
- if (!link.emailProtected && link.password) {
- await handleSubmission();
- } else {
- setVerificationRequested(true);
- }
- setIsLoading(false);
- return true;
- } else {
- setIsLoading(false);
- return false;
- }
- };
-
- //Verifies authentication code
- const handleAuthCodeVerification = async () => {
- setIsLoading(true);
- const URL = `/api/verification/email_authcode?authenticationCode=${authenticationCode}&identifier=${link.id}`;
- const response = await fetch(URL, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
- });
- if (response.ok) {
- setIsEmailVerified(true);
- setVerificationRequested(false);
- await handleSubmission();
- return true;
- } else {
- setIsLoading(false);
- return false;
- }
- };
-
- //If URL contains authenticationCode
- if (authenticationCode) {
- useEffect(() => {
- (async () => {
- setIsLoading(true);
- await handleAuthCodeVerification();
- })();
- }, []);
-
- //Component to render if Loading
- if (isLoading) {
- return (
- <div className="h-screen flex items-center justify-center">
- <LoadingSpinner className="mr-1 h-20 w-20" />
- </div>
- );
- }
-
- //Component to render when verification code is invalid
- if (!isEmailVerified) {
- return (
- <div className="flex h-screen flex-1 flex-col px-6 py-12 lg:px-8 bg-black">
- <div className="sm:mx-auto sm:w-full sm:max-w-md">
- <h2 className="mt-10 text-2xl font-bold leading-9 tracking-tight text-white">
- Unauthorized access
- </h2>
- </div>
- </div>
- );
- }
-
- return (
- <div className="bg-gray-950">
- <ViewData link={link} viewData={viewData} notionData={notionData} />
- </div>
- );
- }
-
- //Components to render when email is submitted but verification is pending
+ // Components to render when email is submitted but verification is pending
if (verificationRequested) {
return (
<EmailVerificationMessage
@@ -205,7 +135,7 @@ export default function DocumentView({
}
// If link is not submitted and does not have email / password protection, show the access form
- if (!submitted && isProtected) {
+ if (!submitted && isProtected && !token) {
console.log("calling access form");
return (
<AccessForm
diff --git a/components/view/view-data.tsx b/components/view/view-data.tsx
index 95075a5a..15b4976a 100644
--- a/components/view/view-data.tsx
+++ b/components/view/view-data.tsx
@@ -12,13 +12,13 @@ export default function ViewData({
}: {
viewData: DEFAULT_DOCUMENT_VIEW_TYPE;
link: LinkWithDocument;
- notionData: {
+ notionData?: {
rootNotionPageId: string | null;
recordMap: ExtendedRecordMap | null;
};
}) {
const { document } = link;
- return notionData.recordMap ? (
+ return notionData?.recordMap ? (
<NotionPage
recordMap={notionData.recordMap}
// rootPageId={notionData.rootNotionPageId}
diff --git a/lib/id-helper.ts b/lib/id-helper.ts
index a880883e..86824038 100644
--- a/lib/id-helper.ts
+++ b/lib/id-helper.ts
@@ -35,4 +35,5 @@ export class IdGenerator<TPrefixes extends string> {
export const newId = new IdGenerator({
view: "view",
inv: "inv",
+ email: "email",
}).id;
diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.ts
index 3af5bdc4..e7628cc0 100644
--- a/pages/api/links/[id]/index.ts
+++ b/pages/api/links/[id]/index.ts
@@ -23,6 +23,7 @@ export default async function handle(
id: true,
expiresAt: true,
emailProtected: true,
+ emailAuthenticated: true,
allowDownload: true,
password: true,
isArchived: true,
@@ -130,6 +131,7 @@ export default async function handle(
password: hashedPassword,
name: linkData.name || null,
emailProtected: linkData.emailProtected,
+ emailAuthenticated: linkData.emailAuthenticated,
allowDownload: linkData.allowDownload,
expiresAt: exat,
domainId: domainObj?.id || null,
diff --git a/pages/api/links/[id]/verify-email.ts b/pages/api/links/[id]/verify-email.ts
new file mode 100644
index 00000000..f81a4fba
--- /dev/null
+++ b/pages/api/links/[id]/verify-email.ts
@@ -0,0 +1,51 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { sendVerificationEmail } from "@/lib/emails/send-email-verification";
+import prisma from "@/lib/prisma";
+import z from "zod";
+
+const bodySchema = z.object({
+ email: z.string().email(),
+ password: z.string().nullable(),
+});
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "POST") {
+ // POST /api/links/[linkId]/verify-email
+ const { token, email } = req.body as { token: string; email: string };
+
+ // Check verification code in database
+ const verification = await prisma.verificationToken.findUnique({
+ where: {
+ token: token,
+ identifier: email,
+ },
+ });
+
+ if (!verification) {
+ res.status(401).json({ message: "Unauthorized access" });
+ return;
+ }
+
+ // Check the token's expiration date
+ if (Date.now() > verification.expires.getTime()) {
+ res.status(401).json({ message: "Token expired" });
+ return;
+ }
+
+ // // remove token from database
+ // await prisma.verificationToken.delete({
+ // where: {
+ // token: token,
+ // },
+ // });
+
+ res.status(200).json({ message: "Verification successful" });
+ } else {
+ // We only allow GET and POST requests
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index c03d35a7..59c5d010 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -93,6 +93,7 @@ export default async function handler(
password: hashedPassword,
name: linkData.name || null,
emailProtected: linkData.emailProtected,
+ emailAuthenticated: linkData.emailAuthenticated,
expiresAt: exat,
allowDownload: linkData.allowDownload,
domainId: domainObj?.id || null,
diff --git a/pages/api/verification/email_authcode.ts b/pages/api/verification/email_authcode.ts
index 033483cb..ce40e617 100644
--- a/pages/api/verification/email_authcode.ts
+++ b/pages/api/verification/email_authcode.ts
@@ -6,9 +6,8 @@ import { checkPassword } from "@/lib/utils";
const bodySchema = z.object({
email: z.string().email(),
- identifier: z.string(),
+ linkId: z.string(),
password: z.string().nullable(),
- emailProtected: z.boolean(),
});
export default async function handle(
@@ -24,10 +23,9 @@ export default async function handle(
};
//Check verification code in database
- const token = await prisma.verificationToken.findFirst({
+ const token = await prisma.verificationToken.findUnique({
where: {
token: authenticationToken,
- identifier: identifier,
},
});
@@ -36,7 +34,7 @@ export default async function handle(
return;
}
//Check the token's expiry
- if (Date.now() > token.expiresAt.getTime()) {
+ if (Date.now() > token.expires.getTime()) {
//Delete the token if expired
await prisma.verificationToken.delete({
where: {
@@ -51,13 +49,11 @@ export default async function handle(
// Input validation
let email: string;
- let identifier: string;
+ let linkId: string;
let password: string | null;
let emailProtected: boolean;
try {
- ({ email, identifier, password, emailProtected } = bodySchema.parse(
- req.body,
- ));
+ ({ email, linkId, password } = bodySchema.parse(req.body));
} catch (error) {
res.status(403).json({ message: `Invalid inputs` });
return;
@@ -65,14 +61,14 @@ export default async function handle(
//Password validation
if (password) {
- const link = await prisma.link.findFirst({
+ const link = await prisma.link.findUnique({
where: {
- id: identifier,
+ id: linkId,
},
});
if (!link) {
- return res.status(404).json({ message: "Object not found" });
+ return res.status(404).json({ message: "Link not found" });
}
const isPasswordValid = await checkPassword(
@@ -91,6 +87,7 @@ export default async function handle(
data: {
token: authenticationCode,
identifier,
+ expires: new Date(Date.now() + 1000 * 60 * 60 * 24),
},
});
const URL = `${process.env.NEXT_PUBLIC_BASE_URL}/view/${identifier}?authenticationCode=${authenticationCode}`;
diff --git a/pages/api/views.ts b/pages/api/views.ts
index cd9dfd27..93a00e85 100644
--- a/pages/api/views.ts
+++ b/pages/api/views.ts
@@ -3,6 +3,8 @@ import prisma from "@/lib/prisma";
import { checkPassword, log } from "@/lib/utils";
import { trackAnalytics } from "@/lib/analytics";
import { client } from "@/trigger";
+import { newId } from "@/lib/id-helper";
+import { sendVerificationEmail } from "@/lib/emails/send-email-verification";
export default async function handle(
req: NextApiRequest,
@@ -14,8 +16,22 @@ export default async function handle(
return;
}
// POST /api/views
- const { linkId, documentId, userId, documentVersionId, hasPages, ...data } =
- req.body;
+ const {
+ linkId,
+ documentId,
+ userId,
+ documentVersionId,
+ hasPages,
+ token,
+ ...data
+ } = req.body as {
+ linkId: string;
+ documentId: string;
+ userId: string | null;
+ documentVersionId: string;
+ hasPages: boolean;
+ token: string | null;
+ };
const { email, password } = data as { email: string; password: string };
@@ -27,6 +43,7 @@ export default async function handle(
select: {
emailProtected: true,
enableNotification: true,
+ emailAuthenticated: true,
password: true,
},
});
@@ -60,6 +77,49 @@ export default async function handle(
}
}
+ // Check if email verification is required for visiting the link
+ if (link.emailAuthenticated && !token) {
+ const token = newId("email");
+ const expiresAt = new Date();
+ expiresAt.setHours(expiresAt.getHours() + 24); // token expires in 24 hour
+
+ await prisma.verificationToken.create({
+ data: {
+ token,
+ identifier: email,
+ expires: expiresAt,
+ },
+ });
+
+ const verificationUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/view/${linkId}/?token=${token}`;
+ await sendVerificationEmail(email, verificationUrl);
+ res.status(200).json({
+ type: "email-verification",
+ message: "Verification email sent.",
+ });
+ return;
+ }
+
+ let isEmailVerified: boolean = false;
+ if (link.emailAuthenticated && token) {
+ const verification = await prisma.verificationToken.findUnique({
+ where: { token: token },
+ });
+
+ if (!verification) {
+ res.status(401).json({ message: "Unauthorized access" });
+ return;
+ }
+
+ // Check the token's expiration date
+ if (Date.now() > verification.expires.getTime()) {
+ res.status(401).json({ message: "Token expired" });
+ return;
+ }
+
+ isEmailVerified = true;
+ }
+
try {
console.time("create-view");
const newView = await prisma.view.create({
@@ -67,6 +127,7 @@ export default async function handle(
linkId: linkId,
viewerEmail: email,
documentId: documentId,
+ verified: isEmailVerified,
},
select: { id: true },
});
diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsx
index 3f54e6bc..79c0a84a 100644
--- a/pages/view/[linkId]/index.tsx
+++ b/pages/view/[linkId]/index.tsx
@@ -9,6 +9,8 @@ import { CustomUser, LinkWithDocument } from "@/lib/types";
import { parsePageId } from "notion-utils";
import { GetStaticPropsContext } from "next";
import { useRouter } from "next/router";
+import { useEffect, useState } from "react";
+import { set } from "date-fns";
export const getStaticProps = async (context: GetStaticPropsContext) => {
const { linkId } = context.params as { linkId: string };
@@ -81,7 +83,10 @@ export default function ViewPage({
};
}) {
const router = useRouter();
- const { authenticationCode } = router.query as { authenticationCode: string };
+ const { token, email: verifiedEmail } = router.query as {
+ token: string;
+ email: string;
+ };
const { data: session, status } = useSession();
if (!link || status === "loading" || router.isFallback) {
@@ -95,6 +100,7 @@ export default function ViewPage({
const {
expiresAt,
emailProtected,
+ emailAuthenticated,
password: linkPassword,
isArchived,
} = link;
@@ -114,15 +120,17 @@ export default function ViewPage({
);
}
- if (emailProtected || linkPassword) {
+ if (emailProtected || emailAuthenticated || linkPassword) {
return (
<DocumentView
link={link}
userEmail={userEmail}
userId={userId}
isProtected={true}
+ hasEmailVerification={emailAuthenticated}
notionData={notionData}
- authenticationCode={authenticationCode}
+ token={token}
+ verifiedEmail={verifiedEmail}
/>
);
}
@@ -133,8 +141,10 @@ export default function ViewPage({
userEmail={userEmail}
userId={userId}
isProtected={false}
+ hasEmailVerification={false}
notionData={notionData}
- authenticationCode={authenticationCode}
+ token={token}
+ verifiedEmail={verifiedEmail}
/>
);
}
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index d349dc8c..3f35598b 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -165,6 +165,7 @@ model Link {
password String? // Optional password for link protection
allowedEmails String[] // Array of emails allowed to view the document
emailProtected Boolean @default(true) // Optional email protection
+ emailAuthenticated Boolean @default(false) // Optional email authentication flag
allowDownload Boolean? @default(false) // Optional give user a option to allow to download the document
isArchived Boolean @default(false) // Indicates if the link is archived
views View[]
@@ -203,6 +204,7 @@ model View {
document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
documentId String
viewerEmail String? // Email of the viewer if known
+ verified Boolean @default(false) // Whether the viewer email has been verified
viewedAt DateTime @default(now())
reactions Reaction[]