Skip to content

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

feat: add link settings to document view page

Marc Seitz91bf575541d1
diff --git a/components/view/access-form/email-section.tsx b/components/view/access-form/email-section.tsx
new file mode 100644
index 00000000..cb174406
--- /dev/null
+++ b/components/view/access-form/email-section.tsx
@@ -0,0 +1,39 @@
+import { DEFAULT_ACCESS_FORM_TYPE } from "@/pages/view/[linkId]";
+import { Dispatch, SetStateAction } from "react";
+
+
+export default function EmailSection({
+ data,
+ setData,
+}: {
+ data: DEFAULT_ACCESS_FORM_TYPE;
+ setData: Dispatch<SetStateAction<DEFAULT_ACCESS_FORM_TYPE>>;
+}) {
+ const { email } = data;
+
+ return (
+ <div className="pb-5">
+ <div className="relative rounded-md shadow-sm space-y-2">
+ <label
+ htmlFor="email"
+ className="block text-sm font-medium leading-6 text-white"
+ >
+ Email address
+ </label>
+ <input
+ name="email"
+ id="email"
+ type="email"
+ autoComplete="email"
+ className="flex w-full rounded-md border-0 py-1.5 text-white bg-black shadow-sm ring-1 ring-inset ring-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-300 sm:text-sm sm:leading-6"
+ value={email || ""}
+ placeholder="Enter email"
+ onChange={(e) => {
+ setData({ ...data, email: e.target.value });
+ }}
+ aria-invalid="true"
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/components/view/access-form/index.tsx b/components/view/access-form/index.tsx
new file mode 100644
index 00000000..ce7e2c92
--- /dev/null
+++ b/components/view/access-form/index.tsx
@@ -0,0 +1,46 @@
+import { Dispatch, SetStateAction } from "react";
+import PasswordSection from "./password-section";
+import EmailSection from "./email-section";
+import { DEFAULT_ACCESS_FORM_TYPE } from "@/pages/view/[linkId]";
+import { Button } from "@/components/ui/button";
+
+
+export default function AccessForm({
+ onSubmitHandler,
+ data,
+ setData,
+ requireEmail,
+ requirePassword
+}: {
+ onSubmitHandler: React.FormEventHandler<HTMLFormElement>;
+ data: DEFAULT_ACCESS_FORM_TYPE;
+ setData: Dispatch<SetStateAction<DEFAULT_ACCESS_FORM_TYPE>>;
+ requireEmail: boolean;
+ requirePassword: 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="mt-10 text-2xl font-bold leading-9 tracking-tight text-white">
+ Name requests your action to continue
+ </h2>
+ </div>
+
+ <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-md">
+ <form className="space-y-4" onSubmit={onSubmitHandler}>
+ {requireEmail ? <EmailSection {...{ data, setData }} /> : null}
+ {requirePassword ? <PasswordSection {...{ data, setData }} /> : null}
+
+ <div className="flex justify-center">
+ <Button type="submit" className="w-1/3">
+ Continue
+ </Button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/components/view/access-form/password-section.tsx b/components/view/access-form/password-section.tsx
new file mode 100644
index 00000000..deb966fc
--- /dev/null
+++ b/components/view/access-form/password-section.tsx
@@ -0,0 +1,52 @@
+import { Dispatch, SetStateAction, useState } from "react";
+import Eye from "@/components/shared/icons/eye";
+import EyeOff from "@/components/shared/icons/eye-off";
+import { DEFAULT_ACCESS_FORM_TYPE } from "@/pages/view/[linkId]";
+export default function PasswordSection({
+ data,
+ setData,
+}: {
+ data: DEFAULT_ACCESS_FORM_TYPE;
+ setData: Dispatch<SetStateAction<DEFAULT_ACCESS_FORM_TYPE>>;
+}) {
+ const { password } = data;
+ const [showPassword, setShowPassword] = useState<boolean>(false);
+
+ return (
+ <div className="pb-5">
+ <div className="rounded-md shadow-sm space-y-2">
+ <label
+ htmlFor="password"
+ className="block text-sm font-medium leading-6 text-white"
+ >
+ Passcode
+ </label>
+ <div className="relative">
+ <input
+ name="password"
+ id="password"
+ type={showPassword ? "text" : "password"}
+ className="flex w-full rounded-md border-0 py-1.5 text-white bg-black shadow-sm ring-1 ring-inset ring-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-300 sm:text-sm sm:leading-6"
+ value={password || ""}
+ placeholder="Enter passcode"
+ onChange={(e) => {
+ setData({ ...data, password: e.target.value });
+ }}
+ aria-invalid="true"
+ />
+ <button
+ type="button"
+ onClick={() => setShowPassword(!showPassword)}
+ className="absolute inset-y-0 right-0 flex items-center pr-3"
+ >
+ {showPassword ? (
+ <Eye className="h-4 w-4 text-gray-400" aria-hidden="true" />
+ ) : (
+ <EyeOff className="h-4 w-4 text-gray-400" aria-hidden="true" />
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.ts
index 0dda4e59..8827bf7d 100644
--- a/pages/api/links/[id]/index.ts
+++ b/pages/api/links/[id]/index.ts
@@ -19,6 +19,9 @@ export default async function handle(
},
select: {
id: true,
+ expiresAt: true,
+ emailProtected: true,
+ password: true,
document: { select: { id: true, name: true, file: true } },
},
});
diff --git a/pages/api/views.ts b/pages/api/views.ts
index 8758ef74..29d9c6ef 100644
--- a/pages/api/views.ts
+++ b/pages/api/views.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import prisma from "@/lib/prisma";
-import { log } from "@/lib/utils";
+import { checkPassword, log } from "@/lib/utils";
export default async function handle(
req: NextApiRequest,
@@ -11,8 +11,50 @@ export default async function handle(
res.status(405).json({ message: "Method Not Allowed" });
return;
}
+ // POST /api/views
+ const { linkId, documentId, ...data } = req.body;
- const { linkId, email, documentId } = req.body;
+ const { email, password } = data as { email: string; password: string };
+
+ // Fetch the link to verify the settings
+ const link = await prisma.link.findUnique({
+ where: {
+ id: linkId,
+ },
+ select: {
+ emailProtected: true,
+ password: true,
+ },
+ });
+
+ if (!link) {
+ res.status(404).json({ message: "Link not found." });
+ return;
+ }
+
+ // Check if email is required for visiting the link
+ if (link.emailProtected) {
+ if (!email || email.trim() === "") {
+ res.status(400).json({ message: "Email is required." });
+ return;
+ }
+
+ // You can implement more thorough email validation if required
+ }
+
+ // Check if password is required for visiting the link
+ if (link.password) {
+ if (!password || password.trim() === "") {
+ res.status(400).json({ message: "Password is required." });
+ return;
+ }
+
+ const isPasswordValid = await checkPassword(password, link.password);
+ if (!isPasswordValid) {
+ res.status(403).json({ message: "Invalid password." });
+ return;
+ }
+ }
try {
const newView = await prisma.view.create({
@@ -25,7 +67,7 @@ export default async function handle(
res.status(200).json({ message: "View recorded", viewId: newView.id });
} catch (error) {
- log(`Failed to record view for ${linkId}. Error: \n\n ${error}`)
+ log(`Failed to record view for ${linkId}. Error: \n\n ${error}`);
res.status(500).json({ message: (error as Error).message });
}
}
diff --git a/pages/view/[linkId].tsx b/pages/view/[linkId].tsx
index 6678d2fd..869ad950 100644
--- a/pages/view/[linkId].tsx
+++ b/pages/view/[linkId].tsx
@@ -1,16 +1,31 @@
-import React, { useState } from "react";
+import React, { useEffect, useRef, useState } from "react";
import EmailForm from "@/components/EmailForm";
-import { classNames, getExtension } from "@/lib/utils";
+import { getExtension } from "@/lib/utils";
import { useLink } from "@/lib/swr/use-link";
import ErrorPage from "next/error";
import PDFViewer from "@/components/PDFViewer";
-import { set } from "date-fns";
+import AccessForm from "@/components/view/access-form";
+import { toast } from "sonner";
+
+export const DEFAULT_ACCESS_FORM_DATA = {
+ email: null,
+ password: null,
+};
+
+export type DEFAULT_ACCESS_FORM_TYPE = {
+ email: string | null;
+ password: string | null;
+};
export default function DocumentView() {
const { link, error } = useLink();
- const [email, setEmail] = useState("");
- const [submitted, setSubmitted] = useState(false);
+ const [submitted, setSubmitted] = useState<boolean>(false);
const [viewId, setViewId] = useState<string>("");
+ const hasInitiatedSubmit = useRef(false);
+
+ const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>(
+ DEFAULT_ACCESS_FORM_DATA
+ );
if (error && error.status === 404) {
return <ErrorPage statusCode={404} />;
@@ -19,17 +34,26 @@ export default function DocumentView() {
if (!link) {
return <div>Loading...</div>;
}
- const { document } = link;
- const handleSubmit = async (event: React.FormEvent) => {
- event.preventDefault();
+ const { document, expiresAt, emailProtected, password: linkPassword } = link;
+ // Check if link is expired
+ const isExpired = expiresAt && new Date(expiresAt) < new Date();
+ if (isExpired) {
+ return <div>Link is expired</div>;
+ }
+
+ const handleSubmission = async () => {
const response = await fetch("/api/views", {
method: "POST",
- body: JSON.stringify({ linkId: link.id, email, documentId: document.id }),
headers: {
"Content-Type": "application/json",
},
+ body: JSON.stringify({
+ ...data,
+ linkId: link.id,
+ documentId: document.id,
+ }),
});
if (response.ok) {
@@ -37,12 +61,37 @@ export default function DocumentView() {
setViewId(viewId);
setSubmitted(true);
} else {
- // Handle error
+ const { message } = await response.json();
+ toast.error(message);
}
+ }
+
+ const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (event: React.FormEvent) => {
+ event.preventDefault()
+ await handleSubmission();
};
- if (!submitted) {
- return <EmailForm onSubmitHandler={handleSubmit} setEmail={setEmail} />;
+ if ((!submitted && emailProtected) || (!submitted && linkPassword)) {
+ // return <EmailForm onSubmitHandler={handleSubmit} data={data} setData={setData} />;
+ return (
+ <AccessForm
+ onSubmitHandler={handleSubmit}
+ data={data}
+ setData={setData}
+ requireEmail={emailProtected}
+ requirePassword={!!linkPassword}
+ />
+ );
+ }
+
+ if (
+ !emailProtected &&
+ !linkPassword &&
+ !submitted &&
+ !hasInitiatedSubmit.current
+ ) {
+ hasInitiatedSubmit.current = true;
+ handleSubmission();
}
// get the file extension
@@ -80,7 +129,12 @@ export default function DocumentView() {
}
return (
<div className="bg-gray-950">
- <PDFViewer file={document.file} viewId={viewId} linkId={link.id} documentId={document.id} />
+ <PDFViewer
+ file={document.file}
+ viewId={viewId}
+ linkId={link.id}
+ documentId={document.id}
+ />
</div>
);
}