Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
team scoped /api/links
Aashish-Upadhyay-10175264cb8871b
diff --git a/lib/errorHandler.ts b/lib/errorHandler.tsindex 8cc1825b..48788004 100644--- a/lib/errorHandler.ts+++ b/lib/errorHandler.ts@@ -7,8 +7,15 @@ export class TeamError extends Error {}}+export class DocumentError extends Error {+ statusCode = 400;+ constructor(public message: string) {+ super(message);+ }+}+export function errorHanlder(err: unknown, res: NextApiResponse) {- if (err instanceof TeamError) {+ if (err instanceof TeamError || err instanceof DocumentError) {return res.status(err.statusCode).end(err.message);} else {return res.status(500).json({diff --git a/lib/team/helper.ts b/lib/team/helper.tsindex 07aceeaf..ad848bc9 100644--- a/lib/team/helper.ts+++ b/lib/team/helper.ts@@ -1,12 +1,12 @@import prisma from "@/lib/prisma";-import { TeamError } from "../errorHandler";+import { DocumentError, TeamError } from "../errorHandler";import { Document, DocumentVersion, Domain, View } from "@prisma/client";interface ITeamUserAndDocument {teamId: string;userId: string;docId?: string;- checkOwner?: boolean; // will be deprecated in the future+ checkOwner?: boolean;options?: {};}@@ -17,6 +17,12 @@ interface ITeamWithDomain {options?: {};}+interface IDocumentWithLink {+ docId: string;+ userId: string;+ options?: {};+}+export async function getTeamWithUsersAndDocument({teamId,userId,@@ -117,3 +123,31 @@ export async function getTeamWithDomain({return { team, domain };}++export async function getDocumentWithTeamAndUser({+ docId,+ userId,+ options,+}: IDocumentWithLink) {+ const document = (await prisma.document.findUnique({+ where: {+ id: docId,+ },+ include: {+ ...options,+ },+ })) as Document & { team: { users: { userId: string }[] } };++ if (!document) {+ throw new DocumentError("Document doesn't exists");+ }++ const teamHasUser = document.team?.users.some(+ (user) => user.userId === userId+ );+ if (!teamHasUser) {+ throw new TeamError("You are not a member of the team");+ }++ return { document };+}diff --git a/pages/api/links/[id]/archive.ts b/pages/api/links/[id]/archive.tsindex cf5a9dd5..398e87ff 100644--- a/pages/api/links/[id]/archive.ts+++ b/pages/api/links/[id]/archive.ts@@ -1,14 +1,13 @@import { NextApiRequest, NextApiResponse } from "next";import prisma from "@/lib/prisma";import { getServerSession } from "next-auth/next";-import { hashPassword } from "@/lib/utils";import { authOptions } from "../../auth/[...nextauth]";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,res: NextApiResponse) {-if (req.method === "PUT") {// PUT /api/links/:id/archiveconst session = await getServerSession(req, res, authOptions);@@ -20,29 +19,33 @@ export default async function handle(const { isArchived } = req.body;- // Update the link in the database- const updatedLink = await prisma.link.update({- where: { id: id },- data: {- isArchived: isArchived- },- include: {- views: {- orderBy: {- viewedAt: "desc",- },+ try {+ // Update the link in the database+ const updatedLink = await prisma.link.update({+ where: { id: id },+ data: {+ isArchived: isArchived,},- _count: {- select: { views: true },+ include: {+ views: {+ orderBy: {+ viewedAt: "desc",+ },+ },+ _count: {+ select: { views: true },+ },},- },- });+ });- if (!updatedLink) {- return res.status(404).json({ error: "Link not found" });- }+ if (!updatedLink) {+ return res.status(404).json({ error: "Link not found" });+ }- return res.status(200).json(updatedLink);+ return res.status(200).json(updatedLink);+ } catch (error) {+ errorHanlder(error, res);+ }}// We only allow PUT requestsdiff --git a/pages/api/links/[id]/visits.ts b/pages/api/links/[id]/visits.tsindex 05e598af..09cdf8e1 100644--- a/pages/api/links/[id]/visits.ts+++ b/pages/api/links/[id]/visits.ts@@ -4,6 +4,9 @@ import prisma from "@/lib/prisma";import { authOptions } from "../../auth/[...nextauth]";import { log } from "@/lib/utils";import { getViewPageDuration } from "@/lib/tinybird";+import { getDocumentWithTeamAndUser } from "@/lib/team/helper";+import { CustomUser } from "@/lib/types";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,@@ -28,6 +31,7 @@ export default async function handle(select: {document: {select: {+ id: true,numPages: true,versions: {where: { isPrimary: true },@@ -39,7 +43,30 @@ export default async function handle(},},});- const numPages = result?.document?.versions[0]?.numPages || result?.document?.numPages || 0;++ const docId = result?.document.id!;+ const userId = (session.user as CustomUser).id;+ // check if the the team that own the document has the current user+ await getDocumentWithTeamAndUser({+ docId,+ userId,+ options: {+ team: {+ select: {+ users: {+ select: {+ userId: true,+ },+ },+ },+ },+ },+ });++ const numPages =+ result?.document?.versions[0]?.numPages ||+ result?.document?.numPages ||+ 0;const views = await prisma.view.findMany({where: {@@ -70,28 +97,27 @@ export default async function handle(// Construct the response combining views and their respective durationsconst viewsWithDuration = views.map((view, index) => {- // calculate the completion rate- const completionRate = numPages ? (durations[index].data.length / numPages) * 100 : 0;-+ // calculate the completion rate+ const completionRate = numPages+ ? (durations[index].data.length / numPages) * 100+ : 0;+return {...view,duration: durations[index],totalDuration: summedDurations[index],completionRate: completionRate.toFixed(),- }+ };});// TODO: Check that the user is owner of the links, otherwise return 401// console.log("viewsWithDuration:", viewsWithDuration)- res.status(200).json(viewsWithDuration);+ return res.status(200).json(viewsWithDuration);} catch (error) {log(`Failed to get views for link ${id}. Error: \n\n ${error}`);- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else {// We only allow GET requestsdiff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 76b6a0bf..f559f624 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -5,6 +5,11 @@ import { authOptions } from "../auth/[...nextauth]";import { hashPassword } from "@/lib/utils";import { identifyUser, trackAnalytics } from "@/lib/analytics";import { CustomUser } from "@/lib/types";+import { errorHanlder } from "@/lib/errorHandler";+import {+ getDocumentWithTeamAndUser,+ getTeamWithUsersAndDocument,+} from "@/lib/team/helper";export default async function handler(req: NextApiRequest,@@ -18,83 +23,106 @@ export default async function handler(const { documentId, password, expiresAt, ...linkDomainData } = req.body;- const hashedPassword =- password && password.length > 0 ? await hashPassword(password) : null;- const exat = expiresAt ? new Date(expiresAt) : null;+ const userId = (session.user as CustomUser).id;++ try {+ // check if the the team that own the document has the current user+ await getDocumentWithTeamAndUser({+ docId: documentId,+ userId,+ options: {+ team: {+ select: {+ users: {+ select: {+ userId: true,+ },+ },+ },+ },+ },+ });- let { domain, slug, ...linkData } = linkDomainData;+ const hashedPassword =+ password && password.length > 0 ? await hashPassword(password) : null;+ const exat = expiresAt ? new Date(expiresAt) : null;- // set domain and slug to null if the domain is papermark.io- if (domain && domain === "papermark.io") {- domain = null;- slug = null;- }+ let { domain, slug, ...linkData } = linkDomainData;- let domainObj;+ // set domain and slug to null if the domain is papermark.io+ if (domain && domain === "papermark.io") {+ domain = null;+ slug = null;+ }- if (domain && slug) {- domainObj = await prisma.domain.findUnique({- where: {- slug: domain,- },- });+ let domainObj;- if (!domainObj) {- return res.status(400).json({ error: "Domain not found." });- }+ if (domain && slug) {+ domainObj = await prisma.domain.findUnique({+ where: {+ slug: domain,+ },+ });++ if (!domainObj) {+ return res.status(400).json({ error: "Domain not found." });+ }- // console.log(domainObj);+ // console.log(domainObj);- const existingLink = await prisma.link.findUnique({- where: {- domainSlug_slug: {- slug: slug,- domainSlug: domain,+ const existingLink = await prisma.link.findUnique({+ where: {+ domainSlug_slug: {+ slug: slug,+ domainSlug: domain,+ },},+ });++ if (existingLink) {+ return res.status(400).json({+ error: "The link already exists.",+ });+ }+ }++ // Fetch the link and its related document from the database+ const link = await prisma.link.create({+ data: {+ documentId: documentId,+ password: hashedPassword,+ name: linkData.name || null,+ emailProtected: linkData.emailProtected,+ expiresAt: exat,+ allowDownload: linkData.allowDownload,+ domainId: domainObj?.id || null,+ domainSlug: domain || null,+ slug: slug || null,},});- if (existingLink) {- return res.status(400).json({- error: "The link already exists.",- });- }- }+ const linkWithView = {+ ...link,+ _count: { views: 0 },+ views: [],+ };- // Fetch the link and its related document from the database- const link = await prisma.link.create({- data: {- documentId: documentId,- password: hashedPassword,- name: linkData.name || null,- emailProtected: linkData.emailProtected,- expiresAt: exat,- allowDownload: linkData.allowDownload,- domainId: domainObj?.id || null,- domainSlug: domain || null,- slug: slug || null,- },- });-- const linkWithView = {- ...link,- _count: { views: 0 },- views: [],- };-- if (!linkWithView) {- return res.status(404).json({ error: "Link not found" });- }+ if (!linkWithView) {+ return res.status(404).json({ error: "Link not found" });+ }- await identifyUser((session.user as CustomUser).id);- await trackAnalytics({- event: "Link Added",- linkId: linkWithView.id,- documentId: linkWithView.documentId,- customDomain: linkWithView.domainSlug,- });+ await identifyUser((session.user as CustomUser).id);+ await trackAnalytics({+ event: "Link Added",+ linkId: linkWithView.id,+ documentId: linkWithView.documentId,+ customDomain: linkWithView.domainSlug,+ });- return res.status(200).json(linkWithView);+ return res.status(200).json(linkWithView);+ } catch (error) {+ errorHanlder(error, res);+ }}return res.status(405).json({ error: "Method not allowed" });diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex b3f2772a..3beb2214 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -103,7 +103,7 @@ model Document {numPages Int? // This should be a reference to the number of pages in the documentowner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)teamId String?- Team Team? @relation(fields: [teamId], references: [id])+ team Team? @relation(fields: [teamId], references: [id])ownerId String // This field holds the foreign key.createdAt DateTime @default(now())updatedAt DateTime @updatedAt