Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
team scoped api/domain/[domain]
Aashish-Upadhyay-101c9f0968e1ff3
diff --git a/lib/team/helper.ts b/lib/team/helper.tsindex 96acdaaf..07aceeaf 100644--- a/lib/team/helper.ts+++ b/lib/team/helper.ts@@ -1,5 +1,6 @@import prisma from "@/lib/prisma";import { TeamError } from "../errorHandler";+import { Document, DocumentVersion, Domain, View } from "@prisma/client";interface ITeamUserAndDocument {teamId: string;@@ -12,6 +13,7 @@ interface ITeamUserAndDocument {interface ITeamWithDomain {teamId: string;userId: string;+ domain?: string;options?: {};}@@ -50,7 +52,9 @@ export async function getTeamWithUsersAndDocument({}// check if the document exists in the team- let document: any;+ let document:+ | (Document & { views?: View[]; versions?: DocumentVersion[] })+ | undefined;if (docId) {document = team?.documents.find((doc) => doc.id === docId);if (!document) {@@ -60,7 +64,7 @@ export async function getTeamWithUsersAndDocument({// Check that the user is owner of the document, otherwise return 401if (checkOwner) {- const isUserOwnerOfDocument = document.ownerId === userId;+ const isUserOwnerOfDocument = document?.ownerId === userId;if (!isUserOwnerOfDocument) {throw new TeamError("Unauthorized access to the document");}@@ -72,6 +76,7 @@ export async function getTeamWithUsersAndDocument({export async function getTeamWithDomain({teamId,userId,+ domain: domainSlug,options,}: ITeamWithDomain) {const team = await prisma.team.findUnique({@@ -101,5 +106,14 @@ export async function getTeamWithDomain({throw new TeamError("You are not a member of the team");}- return { team };+ // check if the domain exists in the team+ let domain: Domain | undefined;+ if (domainSlug) {+ domain = team.domains.find((_domain) => _domain.slug === domainSlug);+ if (!domain) {+ throw new TeamError("Domain doesn't exists in the team");+ }+ }++ return { team, domain };}diff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.tsindex c085ef5e..a6e40d35 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts@@ -60,11 +60,11 @@ export default async function handle(// get the numPages from documentconst numPages =- document?.versions[0]?.numPages || document?.numPages || 0;+ document?.versions?.[0]?.numPages || document?.numPages || 0;- const views = document.views;+ const views = document?.views || [];- const durationsPromises = views.map((view: { id: string }) => {+ const durationsPromises = views?.map((view: { id: string }) => {return getViewPageDuration({documentId: docId,viewId: view.id,@@ -84,7 +84,7 @@ export default async function handle(});// Construct the response combining views and their respective durations- const viewsWithDuration = views.map((view: any, index: number) => {+ const viewsWithDuration = views?.map((view: any, index: number) => {// calculate the completion rateconst completionRate = numPages? (durations[index].data.length / numPages) * 100diff --git a/pages/api/teams/[teamId]/domains/[domain]/index.ts b/pages/api/teams/[teamId]/domains/[domain]/index.tsindex ead45758..72353091 100644--- a/pages/api/teams/[teamId]/domains/[domain]/index.ts+++ b/pages/api/teams/[teamId]/domains/[domain]/index.ts@@ -5,21 +5,24 @@ import { authOptions } from "@/pages/api//auth/[...nextauth]";import { log } from "@/lib/utils";import { getApexDomain, removeDomainFromVercel } from "@/lib/domains";import { CustomUser } from "@/lib/types";+import { getTeamWithDomain } from "@/lib/team/helper";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,res: NextApiResponse) {if (req.method === "DELETE") {- // DELETE /api/domains/:domain+ // DELETE /api/teams/:teamId/domains/:domainconst session = await getServerSession(req, res, authOptions);if (!session) {return res.status(401).end("Unauthorized");}// Assuming the domain slug is sent in the request body.- const { domain } = req.query as { domain: string };+ const { teamId, domain } = req.query as { teamId: string; domain: string };+ const userId = (session.user as CustomUser).id;// console.log("Deleting domain:", domain);@@ -28,6 +31,12 @@ export default async function handle(}try {+ const { domain: domainToBeDeleted } = await getTeamWithDomain({+ teamId,+ userId,+ domain,+ });+// calculate the domainCountconst apexDomain = getApexDomain(`https://${domain}`);const domainCount = await prisma.domain.count({@@ -45,36 +54,19 @@ export default async function handle(},});- const domainToBeDeleted = await prisma.domain.findFirst({- where: {- slug: domain,- userId: (session.user as CustomUser).id,- },- select: {- id: true,- },- });-- if (!domainToBeDeleted) {- return res.status(404).json("Domain not found");- }-await Promise.allSettled([removeDomainFromVercel(domain, domainCount),prisma.domain.delete({where: {- id: domainToBeDeleted.id,+ id: domainToBeDeleted?.id,},}),]);- res.status(204).end(); // 204 No Content response for successful deletes+ return res.status(204).end(); // 204 No Content response for successful deletes} catch (error) {log(`Failed to delete domain: ${domain}. Error: \n\n ${error}`);- res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message- });+ errorHanlder(error, res);}} else {// We only allow POST requestsdiff --git a/pages/api/teams/[teamId]/domains/[domain]/verify.ts b/pages/api/teams/[teamId]/domains/[domain]/verify.tsindex 5f9dca95..dfec1648 100644--- a/pages/api/teams/[teamId]/domains/[domain]/verify.ts+++ b/pages/api/teams/[teamId]/domains/[domain]/verify.ts@@ -1,4 +1,4 @@-import { NextApiRequest, NextApiResponse } from 'next';+import { NextApiRequest, NextApiResponse } from "next";import {getConfigResponse,getDomainResponse,@@ -6,12 +6,15 @@ import {} from "@/lib/domains";import { DomainVerificationStatusProps } from "@/lib/types";import prisma from "@/lib/prisma";-import { analytics, identifyUser, trackAnalytics } from '@/lib/analytics';+import { analytics, identifyUser, trackAnalytics } from "@/lib/analytics";-export default async function handle(req: NextApiRequest, res: NextApiResponse) {- // GET /api/domains/[domain]/verify - get domain verification status+export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ // GET /api/teams/:teamId/domains/[domain]/verify - get domain verification statusif (req.method === "GET") {- const { domain } = req.query as { domain: string; };+ const { domain } = req.query as { domain: string };let status: DomainVerificationStatusProps = "Valid Configuration";const [domainJson, configJson] = await Promise.all([@@ -55,7 +58,7 @@ export default async function handle(req: NextApiRequest, res: NextApiResponse)},select: {verified: true,- }+ },});const updatedDomain = await prisma.domain.update({@@ -69,7 +72,7 @@ export default async function handle(req: NextApiRequest, res: NextApiResponse)select: {userId: true,verified: true,- }+ },});if (!currentDomain!.verified && updatedDomain.verified) {