Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: store verification token in cookies for quick refresh
Marc Seitzd748d6367061
diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxindex 12383ae5..e87597df 100644--- a/components/view/dataroom/dataroom-view.tsx+++ b/components/view/dataroom/dataroom-view.tsx@@ -4,6 +4,7 @@ import { useRouter } from "next/router";import React, { useEffect, useRef, useState } from "react";import { DataroomBrand } from "@prisma/client";+import Cookies from "js-cookie";import { usePlausible } from "next-plausible";import { ExtendedRecordMap } from "notion-types";import { toast } from "sonner";@@ -122,6 +123,9 @@ export default function DataroomView({useState<boolean>(false);const [dataroomVerified, setDataroomVerified] = useState<boolean>(false);const [documentData, setDocumentData] = useState<TDocumentData | null>(null);+ const [verificationToken, setVerificationToken] = useState<string | null>(+ token ?? null,+ );const [viewType, setViewType] = useState<"DOCUMENT_VIEW" | "DATAROOM_VIEW">("DATAROOM_VIEW",@@ -143,7 +147,7 @@ export default function DataroomView({userId: userId ?? null,documentVersionId: documentData?.documentVersionId,hasPages: documentData?.hasPages,- token: token ?? null,+ token: verificationToken ?? null,verifiedEmail: verifiedEmail ?? null,dataroomVerified: dataroomVerified,dataroomId: dataroom?.id,@@ -225,6 +229,9 @@ export default function DataroomView({undefined,{ shallow: true },);++ Cookies.remove("pm_vft", { path: currentPath });+ setVerificationToken(null);}setIsLoading(false);}diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex e936fc95..bcfe5f88 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -3,6 +3,7 @@ import { useRouter } from "next/router";import React, { useEffect, useRef, useState } from "react";import { Brand } from "@prisma/client";+import Cookies from "js-cookie";import { usePlausible } from "next-plausible";import { ExtendedRecordMap } from "notion-types";import { toast } from "sonner";@@ -100,6 +101,9 @@ export default function DocumentView({);const [verificationRequested, setVerificationRequested] =useState<boolean>(false);+ const [verificationToken, setVerificationToken] = useState<string | null>(+ token ?? null,+ );const handleSubmission = async (): Promise<void> => {setIsLoading(true);@@ -118,7 +122,7 @@ export default function DocumentView({userId: userId ?? null,documentVersionId: document.versions[0].id,hasPages: document.versions[0].hasPages,- token: token ?? null,+ token: verificationToken ?? null,verifiedEmail: verifiedEmail ?? null,useAdvancedExcelViewer,previewToken,@@ -186,6 +190,9 @@ export default function DocumentView({undefined,{ shallow: true },);++ Cookies.remove("pm_vft", { path: currentPath });+ setVerificationToken(null);}setIsLoading(false);}diff --git a/pages/api/views-dataroom.ts b/pages/api/views-dataroom.tsindex 4979ef1f..6c0375f1 100644--- a/pages/api/views-dataroom.ts+++ b/pages/api/views-dataroom.ts@@ -5,6 +5,7 @@ import { waitUntil } from "@vercel/functions";import { getServerSession } from "next-auth/next";import { parsePageId } from "notion-utils";+import { hashToken } from "@/lib/api/auth/token";import sendNotification from "@/lib/api/notification-helper";import { sendVerificationEmail } from "@/lib/emails/send-email-verification";import { getFile } from "@/lib/files/get-file";@@ -224,23 +225,28 @@ export default async function handle(// Check if email verification is required for visiting the linkif (link.emailAuthenticated && !token && !dataroomVerified) {const token = newId("email");+ const hashedToken = hashToken(token);const expiresAt = new Date();- expiresAt.setMinutes(expiresAt.getMinutes() + 20); // token expires in 20 minutes+ expiresAt.setHours(expiresAt.getHours() + 23); // token expires at 23 hours++ const ipAddress = getIpAddress(req.headers);await prisma.verificationToken.create({data: {- token,- identifier: `${linkId}:${email}`,+ token: hashedToken,+ identifier: `${linkId}:${hashToken(ipAddress)}:${email}`,expires: expiresAt,},});// set the default verification url- let verificationUrl: string = `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${linkId}/?token=${token}&email=${encodeURIComponent(email)}`;+ let verificationUrl: string =+ `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${linkId}?token=${hashedToken}&email=${encodeURIComponent(email)}` ++ (previewToken ? `&previewToken=${previewToken}` : "");if (link.domainSlug && link.slug) {// if custom domain is enabled, use the custom domain- verificationUrl = `https://${link.domainSlug}/${link.slug}/?token=${token}&email=${encodeURIComponent(email)}`;+ verificationUrl = `https://${link.domainSlug}/${link.slug}?token=${hashedToken}&email=${encodeURIComponent(email)}`;}await sendVerificationEmail(email, verificationUrl);@@ -253,10 +259,12 @@ export default async function handle(let isEmailVerified: boolean = false;if (link.emailAuthenticated && token && !dataroomVerified) {+ const hashedToken = token; // INFO: token is already hashed+ const ipAddress = getIpAddress(req.headers);const verification = await prisma.verificationToken.findUnique({where: {- token: token,- identifier: `${linkId}:${verifiedEmail}`,+ token: hashedToken,+ identifier: `${linkId}:${hashToken(ipAddress)}:${email}`,},});@@ -274,12 +282,12 @@ export default async function handle(return;}- // delete the token after verification- await prisma.verificationToken.delete({- where: {- token: token,- },- });+ // // delete the token after verification+ // await prisma.verificationToken.delete({+ // where: {+ // token: hashedToken,+ // },+ // });isEmailVerified = true;}diff --git a/pages/api/views.ts b/pages/api/views.tsindex b0c35d3b..e91d6712 100644--- a/pages/api/views.ts+++ b/pages/api/views.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { waitUntil } from "@vercel/functions";import { getServerSession } from "next-auth/next";+import { hashToken } from "@/lib/api/auth/token";import sendNotification from "@/lib/api/notification-helper";import { sendVerificationEmail } from "@/lib/emails/send-email-verification";import { getFile } from "@/lib/files/get-file";@@ -180,25 +181,28 @@ export default async function handle(// Check if email verification is required for visiting the linkif (link.emailAuthenticated && !token) {const token = newId("email");+ const hashedToken = hashToken(token);const expiresAt = new Date();- expiresAt.setMinutes(expiresAt.getMinutes() + 20); // token expires in 20 minutes+ expiresAt.setHours(expiresAt.getHours() + 23); // token expires at 23 hours++ const ipAddress = getIpAddress(req.headers);await prisma.verificationToken.create({data: {- token,- identifier: `${linkId}:${email}`,+ token: hashedToken,+ identifier: `${linkId}:${hashToken(ipAddress)}:${email}`,expires: expiresAt,},});// set the default verification urllet verificationUrl: string =- `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${linkId}/?token=${token}&email=${encodeURIComponent(email)}` ++ `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${linkId}?token=${hashedToken}&email=${encodeURIComponent(email)}` +(previewToken ? `&previewToken=${previewToken}` : "");if (link.domainSlug && link.slug && !previewToken) {// if custom domain is enabled, use the custom domain- verificationUrl = `https://${link.domainSlug}/${link.slug}/?token=${token}&email=${encodeURIComponent(email)}`;+ verificationUrl = `https://${link.domainSlug}/${link.slug}?token=${hashedToken}&email=${encodeURIComponent(email)}`;}await sendVerificationEmail(email, verificationUrl);@@ -211,10 +215,12 @@ export default async function handle(let isEmailVerified: boolean = false;if (link.emailAuthenticated && token) {+ const hashedToken = token; // INFO: token is already hashed+ const ipAddress = getIpAddress(req.headers);const verification = await prisma.verificationToken.findUnique({where: {- token: token,- identifier: `${linkId}:${verifiedEmail}`,+ token: hashedToken,+ identifier: `${linkId}:${hashToken(ipAddress)}:${email}`,},});@@ -232,12 +238,12 @@ export default async function handle(return;}- // delete the token after verification- await prisma.verificationToken.delete({- where: {- token: token,- },- });+ // // delete the token after verification+ // await prisma.verificationToken.delete({+ // where: {+ // token: hashedToken,+ // },+ // });isEmailVerified = true;}diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsxindex d2f4d195..be2f90f4 100644--- a/pages/view/[linkId]/index.tsx+++ b/pages/view/[linkId]/index.tsx@@ -1,8 +1,11 @@import { GetStaticPropsContext } from "next";import { useRouter } from "next/router";+import { useEffect, useState } from "react";+import NotFound from "@/pages/404";import { Brand, DataroomBrand } from "@prisma/client";+import Cookies from "js-cookie";import { useSession } from "next-auth/react";import { ExtendedRecordMap } from "notion-types";import { parsePageId } from "notion-utils";@@ -197,6 +200,35 @@ export default function ViewPage({}) {const router = useRouter();const { data: session, status } = useSession();+ const [storedToken, setStoredToken] = useState<string | undefined>(undefined);+ const [storedEmail, setStoredEmail] = useState<string | undefined>(undefined);++ useEffect(() => {+ // Retrieve token from cookie on component mount+ const cookieToken = Cookies.get("pm_vft");+ const storedEmail = window.localStorage.getItem("papermark.email");+ if (cookieToken) {+ setStoredToken(cookieToken);+ if (storedEmail) {+ setStoredEmail(storedEmail.toLowerCase());+ }+ }+ }, []);++ useEffect(() => {+ const { token } = router.query as { token?: string };+ // Store token in cookie when it's available from the query+ if (token) {+ // set the cookie to expire in 24 hours+ Cookies.set("pm_vft", token, {+ path: router.asPath.split("?")[0],+ expires: 1,+ sameSite: "strict",+ secure: true,+ });+ setStoredToken(token);+ }+ }, [router.query]);if (router.isFallback) {return (@@ -282,7 +314,7 @@ export default function ViewPage({/><DocumentViewlink={link}- userEmail={verifiedEmail ?? userEmail}+ userEmail={verifiedEmail ?? storedEmail ?? userEmail}userId={userId}isProtected={!!(emailProtected || linkPassword || enableAgreement)}notionData={notionData}@@ -293,7 +325,7 @@ export default function ViewPage({previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}- token={token}+ token={storedToken ?? token}verifiedEmail={verifiedEmail}/></>@@ -363,7 +395,7 @@ export default function ViewPage({/><DataroomViewlink={link}- userEmail={verifiedEmail ?? userEmail}+ userEmail={verifiedEmail ?? storedEmail ?? userEmail}userId={userId}isProtected={!!(emailProtected || linkPassword || enableAgreement)}brand={brand}@@ -371,7 +403,7 @@ export default function ViewPage({previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}- token={token}+ token={storedToken ?? token}verifiedEmail={verifiedEmail}/></>diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsxindex c9ae547b..9f20fb0d 100644--- a/pages/view/domains/[domain]/[slug]/index.tsx+++ b/pages/view/domains/[domain]/[slug]/index.tsx@@ -1,8 +1,11 @@import { GetStaticPropsContext } from "next";import { useRouter } from "next/router";+import { useEffect, useState } from "react";+import NotFound from "@/pages/404";import { Brand, DataroomBrand } from "@prisma/client";+import Cookies from "js-cookie";import { useSession } from "next-auth/react";import { ExtendedRecordMap } from "notion-types";import { parsePageId } from "notion-utils";@@ -199,6 +202,35 @@ export default function ViewPage({}) {const router = useRouter();const { data: session, status } = useSession();+ const [storedToken, setStoredToken] = useState<string | undefined>(undefined);+ const [storedEmail, setStoredEmail] = useState<string | undefined>(undefined);++ useEffect(() => {+ // Retrieve token from cookie on component mount+ const cookieToken = Cookies.get("pm_vft");+ const storedEmail = window.localStorage.getItem("papermark.email");+ if (cookieToken) {+ setStoredToken(cookieToken);+ if (storedEmail) {+ setStoredEmail(storedEmail.toLowerCase());+ }+ }+ }, []);++ useEffect(() => {+ const { token } = router.query as { token?: string };+ // Store token in cookie when it's available from the query+ if (token) {+ // set the cookie to expire in 24 hours+ Cookies.set("pm_vft", token, {+ path: router.asPath.split("?")[0],+ expires: 1,+ sameSite: "strict",+ secure: true,+ });+ setStoredToken(token);+ }+ }, [router.query]);if (router.isFallback) {return (@@ -283,7 +315,7 @@ export default function ViewPage({/><DocumentViewlink={link}- userEmail={verifiedEmail ?? userEmail}+ userEmail={verifiedEmail ?? storedEmail ?? userEmail}userId={userId}isProtected={!!(emailProtected || linkPassword || enableAgreement)}notionData={notionData}@@ -293,7 +325,7 @@ export default function ViewPage({previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}- token={token}+ token={storedToken ?? token}verifiedEmail={verifiedEmail}/></>@@ -363,7 +395,7 @@ export default function ViewPage({/><DataroomViewlink={link}- userEmail={verifiedEmail ?? userEmail}+ userEmail={verifiedEmail ?? storedEmail ?? userEmail}userId={userId}isProtected={!!(emailProtected || linkPassword || enableAgreement)}brand={brand}@@ -371,7 +403,7 @@ export default function ViewPage({previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}- token={token}+ token={storedToken ?? token}verifiedEmail={verifiedEmail}/></>