Skip to content

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

Email verification added

Digant Patel9a3523efb10c
diff --git a/components/emails/email-verification.tsx b/components/emails/email-verification.tsx
new file mode 100644
index 00000000..5bbec401
--- /dev/null
+++ b/components/emails/email-verification.tsx
@@ -0,0 +1,69 @@
+import React from "react";
+import {
+ Body,
+ Container,
+ Button,
+ Head,
+ Heading,
+ Html,
+ Preview,
+ Section,
+ Text,
+ Tailwind,
+ Hr,
+} from "@react-email/components";
+
+export default function EmailVerification({
+ verificationURL = "papermark.io",
+}: {
+ verificationURL: string;
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>Email Verification</Preview>
+ <Tailwind>
+ <Body className="bg-white my-auto mx-auto font-sans">
+ <Container className="my-10 mx-auto p-5 w-[465px]">
+ <Heading className="text-2xl font-normal text-center p-0 mt-4 mb-8 mx-0">
+ <span className="font-bold tracking-tighter">Papermark</span>
+ </Heading>
+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ Email Verification
+ </Heading>
+ <Text className="text-sm leading-6 text-black">
+ Welcome to papermark. Please click the button below to verify your
+ email.
+ </Text>
+ <Section className="my-8 text-center">
+ <Button
+ style={{ padding: "12px 20px" }}
+ className="bg-black rounded text-white text-xs font-semibold no-underline text-center"
+ href={verificationURL}
+ >
+ Verify Email
+ </Button>
+ </Section>
+ <Hr />
+ <Section className="mt-8 text-gray-400">
+ <Text className="text-xs">
+ © {new Date().getFullYear()}{" "}
+ <a
+ href="https://www.papermark.io"
+ className="no-underline text-gray-400 hover:text-gray-400 visited:text-gray-400"
+ target="_blank"
+ >
+ papermark.io
+ </a>
+ </Text>
+ <Text className="text-xs">
+ If you have any feedback or questions about this email, simply
+ reply to it. I&apos;d love to hear from you!
+ </Text>
+ </Section>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/components/view/document-view.tsx b/components/view/document-view.tsx
index bac7e083..54343f6c 100644
--- a/components/view/document-view.tsx
+++ b/components/view/document-view.tsx
@@ -7,10 +7,9 @@ import { usePlausible } from "next-plausible";
import { toast } from "sonner";
import { LinkWithDocument } from "@/lib/types";
import LoadingSpinner from "@/components/ui/loading-spinner";
-import PagesViewer from "@/components/view/PagesViewer";
-import PDFViewer from "@/components/view/PDFViewer";
-import { NotionPage } from "../NotionPage";
import { ExtendedRecordMap } from "notion-types";
+import EmailVerificationMessage from "./email-verification-form";
+import ViewData from "./view-data";
export type DEFAULT_DOCUMENT_VIEW_TYPE = {
viewId: string;
@@ -24,12 +23,14 @@ export default function DocumentView({
userId,
isProtected,
notionData,
+ authenticationCode,
}: {
link: LinkWithDocument;
+ authenticationCode: string | undefined;
userEmail: string | null | undefined;
userId: string | null | undefined;
isProtected: boolean;
- notionData?: {
+ notionData: {
rootNotionPageId: string | null;
recordMap: ExtendedRecordMap | null;
};
@@ -38,6 +39,9 @@ export default function DocumentView({
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);
@@ -63,8 +67,8 @@ export default function DocumentView({
linkId: link.id,
documentId: document.id,
userId: userId || null,
- documentVersionId: document.versions[0].id || null,
- hasPages: document.versions[0].hasPages || null,
+ documentVersionId: document.versions[0].id,
+ hasPages: document.versions[0].hasPages,
}),
});
@@ -86,7 +90,7 @@ export default function DocumentView({
event: React.FormEvent,
): Promise<void> => {
event.preventDefault();
- await handleSubmission();
+ await handleEmailVerification();
};
// If link is not submitted and does not have email / password protection, show the access form
@@ -99,6 +103,107 @@ 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
+ if (verificationRequested) {
+ return (
+ <EmailVerificationMessage
+ onSubmitHandler={handleSubmit}
+ data={data}
+ isLoading={isLoading}
+ />
+ );
+ }
+
// If link is not submitted and does not have email / password protection, show the access form
if (!submitted && isProtected) {
console.log("calling access form");
@@ -123,40 +228,10 @@ export default function DocumentView({
</div>
);
}
-
return (
<div className="bg-gray-950">
{submitted ? (
- notionData && notionData.recordMap ? (
- <NotionPage
- recordMap={notionData.recordMap}
- // rootPageId={notionData.rootNotionPageId}
- viewId={viewData.viewId}
- linkId={link.id}
- documentId={document.id}
- versionNumber={document.versions[0].versionNumber}
- />
- ) : viewData.pages ? (
- <PagesViewer
- pages={viewData.pages}
- viewId={viewData.viewId}
- linkId={link.id}
- documentId={document.id}
- assistantEnabled={document.assistantEnabled}
- versionNumber={document.versions[0].versionNumber}
- />
- ) : (
- <PDFViewer
- file={viewData.file}
- viewId={viewData.viewId}
- linkId={link.id}
- documentId={document.id}
- name={document.name}
- allowDownload={link.allowDownload}
- assistantEnabled={document.assistantEnabled}
- versionNumber={document.versions[0].versionNumber}
- />
- )
+ <ViewData link={link} viewData={viewData} notionData={notionData} />
) : (
<div className="h-screen flex items-center justify-center">
<LoadingSpinner className="h-20 w-20" />
diff --git a/components/view/email-verification-form.tsx b/components/view/email-verification-form.tsx
new file mode 100644
index 00000000..f11d528a
--- /dev/null
+++ b/components/view/email-verification-form.tsx
@@ -0,0 +1,41 @@
+import { Button } from "@/components/ui/button";
+import { DEFAULT_ACCESS_FORM_TYPE } from "@/components/view/access-form";
+
+export default function EmailVerificationMessage({
+ onSubmitHandler,
+ isLoading,
+ data,
+}: {
+ onSubmitHandler: React.FormEventHandler<HTMLFormElement>;
+ data: DEFAULT_ACCESS_FORM_TYPE;
+ isLoading: boolean;
+}) {
+ 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="flex justify-center mt-10 text-2xl font-bold leading-9 tracking-tight text-white">
+ Please verify your email
+ </h2>
+ </div>
+ <div className="sm:mx-auto sm:w-full sm:max-w-md">
+ <h6 className="block text-sm font-medium leading-6 text-white">
+ A verification link is send to your email {data.email}
+ </h6>
+ </div>
+ <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-md">
+ <form className="space-y-4" onSubmit={onSubmitHandler}>
+ <div className="flex justify-center">
+ <p className="text-sm text-gray-600">Didn't receive the email?</p>
+ </div>
+ <div className="flex justify-center">
+ <Button type="submit" className="w-1/3" loading={isLoading}>
+ Resend Link
+ </Button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/components/view/view-data.tsx b/components/view/view-data.tsx
new file mode 100644
index 00000000..95075a5a
--- /dev/null
+++ b/components/view/view-data.tsx
@@ -0,0 +1,51 @@
+import { DEFAULT_DOCUMENT_VIEW_TYPE } from "./document-view";
+import { LinkWithDocument } from "@/lib/types";
+import PagesViewer from "@/components/view/PagesViewer";
+import PDFViewer from "@/components/view/PDFViewer";
+import { NotionPage } from "@/components/NotionPage";
+import { ExtendedRecordMap } from "notion-types";
+
+export default function ViewData({
+ viewData,
+ link,
+ notionData,
+}: {
+ viewData: DEFAULT_DOCUMENT_VIEW_TYPE;
+ link: LinkWithDocument;
+ notionData: {
+ rootNotionPageId: string | null;
+ recordMap: ExtendedRecordMap | null;
+ };
+}) {
+ const { document } = link;
+ return notionData.recordMap ? (
+ <NotionPage
+ recordMap={notionData.recordMap}
+ // rootPageId={notionData.rootNotionPageId}
+ viewId={viewData.viewId}
+ linkId={link.id}
+ documentId={document.id}
+ versionNumber={document.versions[0].versionNumber}
+ />
+ ) : viewData.pages ? (
+ <PagesViewer
+ pages={viewData.pages}
+ viewId={viewData.viewId}
+ linkId={link.id}
+ documentId={document.id}
+ assistantEnabled={document.assistantEnabled}
+ versionNumber={document.versions[0].versionNumber}
+ />
+ ) : (
+ <PDFViewer
+ file={viewData.file}
+ viewId={viewData.viewId}
+ linkId={link.id}
+ documentId={document.id}
+ name={document.name}
+ allowDownload={link.allowDownload}
+ assistantEnabled={document.assistantEnabled}
+ versionNumber={document.versions[0].versionNumber}
+ />
+ );
+}
diff --git a/lib/emails/send-email-verification.ts b/lib/emails/send-email-verification.ts
new file mode 100644
index 00000000..91bbe269
--- /dev/null
+++ b/lib/emails/send-email-verification.ts
@@ -0,0 +1,12 @@
+import { sendEmail } from "@/lib/resend";
+import EmailVerification from "@/components/emails/email-verification";
+
+export const sendVerificationEmail = async (email: string, verificationURL: string) => {
+ const emailTemplate = EmailVerification({ verificationURL });
+ await sendEmail({
+ to: email,
+ subject: `Please verify your email for to view document [Papermark.io]`,
+ react: emailTemplate,
+ test: process.env.NODE_ENV === "development",
+ });
+};
\ No newline at end of file
diff --git a/pages/api/verification/email_authcode.ts b/pages/api/verification/email_authcode.ts
new file mode 100644
index 00000000..033483cb
--- /dev/null
+++ b/pages/api/verification/email_authcode.ts
@@ -0,0 +1,121 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { sendVerificationEmail } from "@/lib/emails/send-email-verification";
+import prisma from "@/lib/prisma";
+import z from "zod";
+import { checkPassword } from "@/lib/utils";
+
+const bodySchema = z.object({
+ email: z.string().email(),
+ identifier: z.string(),
+ password: z.string().nullable(),
+ emailProtected: z.boolean(),
+});
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "GET") {
+ // GET /api/verification/email_authcode
+ // Verify authcode
+ const { authenticationToken, identifier } = req.query as {
+ authenticationToken: string;
+ identifier: string;
+ };
+
+ //Check verification code in database
+ const token = await prisma.verificationToken.findFirst({
+ where: {
+ token: authenticationToken,
+ identifier: identifier,
+ },
+ });
+
+ if (!token) {
+ res.status(401).json({ message: "Unauthorized access" });
+ return;
+ }
+ //Check the token's expiry
+ if (Date.now() > token.expiresAt.getTime()) {
+ //Delete the token if expired
+ await prisma.verificationToken.delete({
+ where: {
+ token: authenticationToken,
+ },
+ });
+ return res.status(401).json({ message: "Verification code expired" });
+ }
+ res.status(200).json({ message: "Verification successful" });
+ } else if (req.method === "POST") {
+ // POST /api/verification/email_authcode
+
+ // Input validation
+ let email: string;
+ let identifier: string;
+ let password: string | null;
+ let emailProtected: boolean;
+ try {
+ ({ email, identifier, password, emailProtected } = bodySchema.parse(
+ req.body,
+ ));
+ } catch (error) {
+ res.status(403).json({ message: `Invalid inputs` });
+ return;
+ }
+
+ //Password validation
+ if (password) {
+ const link = await prisma.link.findFirst({
+ where: {
+ id: identifier,
+ },
+ });
+
+ if (!link) {
+ return res.status(404).json({ message: "Object not found" });
+ }
+
+ const isPasswordValid = await checkPassword(
+ password,
+ link.password || "",
+ );
+
+ if (!isPasswordValid) {
+ return res.status(401).json({ message: "Incorrect password" });
+ }
+ }
+
+ // Generate authcode
+ const authenticationCode = generateUniqueString(12);
+ await prisma.verificationToken.create({
+ data: {
+ token: authenticationCode,
+ identifier,
+ },
+ });
+ const URL = `${process.env.NEXT_PUBLIC_BASE_URL}/view/${identifier}?authenticationCode=${authenticationCode}`;
+
+ //Only send email if email protected
+ if (emailProtected) {
+ await sendVerificationEmail(email, URL);
+ }
+ res.status(200).json({ authenticationCode });
+ } else {
+ // We only allow GET and POST requests
+ res.setHeader("Allow", ["GET", "POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
+
+function generateUniqueString(length: number) {
+ const charset =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+ let uniqueString = "";
+
+ for (let i = 0; i < length; i++) {
+ const randomIndex = Math.floor(Math.random() * charset.length);
+ uniqueString += charset.charAt(randomIndex);
+ }
+
+ return uniqueString;
+}
diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsx
index 6b57f90f..3f54e6bc 100644
--- a/pages/view/[linkId]/index.tsx
+++ b/pages/view/[linkId]/index.tsx
@@ -59,6 +59,7 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {
recordMap,
},
},
+ revalidate: 10,
};
};
@@ -80,6 +81,7 @@ export default function ViewPage({
};
}) {
const router = useRouter();
+ const { authenticationCode } = router.query as { authenticationCode: string };
const { data: session, status } = useSession();
if (!link || status === "loading" || router.isFallback) {
@@ -120,6 +122,7 @@ export default function ViewPage({
userId={userId}
isProtected={true}
notionData={notionData}
+ authenticationCode={authenticationCode}
/>
);
}
@@ -131,6 +134,7 @@ export default function ViewPage({
userId={userId}
isProtected={false}
notionData={notionData}
+ authenticationCode={authenticationCode}
/>
);
}
diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsx
index ebc598c0..3ebb0ae4 100644
--- a/pages/view/domains/[domain]/[slug]/index.tsx
+++ b/pages/view/domains/[domain]/[slug]/index.tsx
@@ -6,8 +6,6 @@ import NotFound from "@/pages/404";
import { GetStaticPropsContext } from "next";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
-import prisma from "@/lib/prisma";
-
import { ExtendedRecordMap } from "notion-types";
import notion from "@/lib/notion";
import { parsePageId } from "notion-utils";
@@ -81,10 +79,11 @@ export default function ViewPage({
recordMap: ExtendedRecordMap | null;
};
}) {
- const router = useRouter();
const { data: session, status } = useSession();
+ const router = useRouter();
+ const { authenticationCode } = router.query as { authenticationCode: string };
- if (!link || status === "loading" || router.isFallback) {
+ if (!link || status === "loading") {
return (
<div className="h-screen flex items-center justify-center">
<LoadingSpinner className="h-20 w-20" />
@@ -122,6 +121,7 @@ export default function ViewPage({
userId={userId}
isProtected={true}
notionData={notionData}
+ authenticationCode={authenticationCode}
/>
);
}
@@ -133,6 +133,7 @@ export default function ViewPage({
userId={userId}
isProtected={false}
notionData={notionData}
+ authenticationCode={authenticationCode}
/>
);
}