Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

use getLink and getDomain in routes

Kiran K7c02896902a8
diff --git a/apps/web/app/api/analytics/events/export/route.ts b/apps/web/app/api/analytics/events/export/route.ts
index 2cb16ecbca..63d481bf81 100644
--- a/apps/web/app/api/analytics/events/export/route.ts
+++ b/apps/web/app/api/analytics/events/export/route.ts
@@ -1,5 +1,6 @@
import { getEvents } from "@/lib/analytics/get-events";
import { convertToCSV, validDateRangeForPlan } from "@/lib/analytics/utils";
+import { getLink } from "@/lib/api/links/get-link";
import { withWorkspace } from "@/lib/auth";
import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
import { clickEventEnrichedSchema } from "@/lib/zod/schemas/clicks";
@@ -36,7 +37,7 @@ const columnAccessors = {
// GET /api/analytics/events/export – get export data for analytics
export const GET = withWorkspace(
- async ({ searchParams, workspace, link }) => {
+ async ({ searchParams, workspace }) => {
const parsedParams = eventsQuerySchema
.and(
z.object({
@@ -47,7 +48,25 @@ export const GET = withWorkspace(
}),
)
.parse(searchParams);
- const { event, domain, key, interval, start, end, columns } = parsedParams;
+ const {
+ event,
+ domain,
+ key,
+ interval,
+ start,
+ end,
+ columns,
+ linkId,
+ externalId,
+ } = parsedParams;
+
+ const link = await getLink({
+ workspace: workspace,
+ linkId,
+ externalId,
+ domain,
+ key,
+ });
validDateRangeForPlan({
plan: workspace.plan,
@@ -57,11 +76,9 @@ export const GET = withWorkspace(
throwError: true,
});
- const linkId = link ? link.id : null;
-
const response = await getEvents({
...parsedParams,
- ...(linkId && { linkId }),
+ ...(link && { linkId: link.id }),
workspaceId: workspace.id,
limit: 100000,
});
diff --git a/apps/web/app/api/analytics/events/route.ts b/apps/web/app/api/analytics/events/route.ts
index 902e37f47b..4ac31996d2 100644
--- a/apps/web/app/api/analytics/events/route.ts
+++ b/apps/web/app/api/analytics/events/route.ts
@@ -1,14 +1,24 @@
import { getEvents } from "@/lib/analytics/get-events";
import { validDateRangeForPlan } from "@/lib/analytics/utils";
+import { getLink } from "@/lib/api/links/get-link";
import { withWorkspace } from "@/lib/auth";
import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
import { NextResponse } from "next/server";
export const GET = withWorkspace(
- async ({ searchParams, workspace, link }) => {
+ async ({ searchParams, workspace }) => {
const parsedParams = eventsQuerySchema.parse(searchParams);
- let { event, interval, start, end } = parsedParams;
+ let { event, interval, start, end, linkId, externalId, domain, key } =
+ parsedParams;
+
+ const link = await getLink({
+ workspace: workspace,
+ linkId,
+ externalId,
+ domain,
+ key,
+ });
validDateRangeForPlan({
plan: workspace.plan,
@@ -18,12 +28,10 @@ export const GET = withWorkspace(
throwError: true,
});
- const linkId = link ? link.id : null;
-
const response = await getEvents({
...parsedParams,
event,
- ...(linkId && { linkId }),
+ ...(link && { linkId: link.id }),
workspaceId: workspace.id,
});
diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.ts
index 7679fe79b6..390ce294df 100644
--- a/apps/web/app/api/analytics/export/route.ts
+++ b/apps/web/app/api/analytics/export/route.ts
@@ -1,15 +1,25 @@
import { VALID_ANALYTICS_ENDPOINTS } from "@/lib/analytics/constants";
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { convertToCSV, validDateRangeForPlan } from "@/lib/analytics/utils";
+import { getLink } from "@/lib/api/links/get-link";
import { withWorkspace } from "@/lib/auth";
import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
import JSZip from "jszip";
// GET /api/analytics/export – get export data for analytics
export const GET = withWorkspace(
- async ({ searchParams, workspace, link }) => {
+ async ({ searchParams, workspace }) => {
const parsedParams = analyticsQuerySchema.parse(searchParams);
- const { interval, start, end } = parsedParams;
+ const { interval, start, end, linkId, externalId, domain, key } =
+ parsedParams;
+
+ const link = await getLink({
+ workspace: workspace,
+ linkId,
+ externalId,
+ domain,
+ key,
+ });
validDateRangeForPlan({
plan: workspace.plan,
@@ -19,8 +29,6 @@ export const GET = withWorkspace(
throwError: true,
});
- const linkId = link ? link.id : null;
-
const zip = new JSZip();
await Promise.all(
@@ -36,7 +44,7 @@ export const GET = withWorkspace(
const response = await getAnalytics({
...parsedParams,
workspaceId: workspace.id,
- ...(linkId && { linkId }),
+ ...(link && { linkId: link.id }),
event: "clicks",
groupBy: endpoint,
});
diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.ts
index 0ae4a1a0d1..5662bb6a4d 100644
--- a/apps/web/app/api/analytics/route.ts
+++ b/apps/web/app/api/analytics/route.ts
@@ -1,6 +1,7 @@
import { VALID_ANALYTICS_ENDPOINTS } from "@/lib/analytics/constants";
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { validDateRangeForPlan } from "@/lib/analytics/utils";
+import { getLink } from "@/lib/api/links/get-link";
import { withWorkspace } from "@/lib/auth";
import {
analyticsPathParamsSchema,
@@ -10,7 +11,7 @@ import { NextResponse } from "next/server";
// GET /api/analytics – get analytics
export const GET = withWorkspace(
- async ({ params, searchParams, workspace, link }) => {
+ async ({ params, searchParams, workspace }) => {
let { eventType: oldEvent, endpoint: oldType } =
analyticsPathParamsSchema.parse(params);
@@ -22,7 +23,25 @@ export const GET = withWorkspace(
const parsedParams = analyticsQuerySchema.parse(searchParams);
- let { event, groupBy, interval, start, end } = parsedParams;
+ let {
+ event,
+ groupBy,
+ interval,
+ start,
+ end,
+ linkId,
+ externalId,
+ domain,
+ key,
+ } = parsedParams;
+
+ const link = await getLink({
+ workspace: workspace,
+ linkId,
+ externalId,
+ domain,
+ key,
+ });
event = oldEvent || event;
groupBy = oldType || groupBy;
@@ -35,8 +54,6 @@ export const GET = withWorkspace(
throwError: true,
});
- const linkId = link ? link.id : null;
-
// Identify the request is from deprecated clicks endpoint
// (/api/analytics/clicks)
// (/api/analytics/count)
@@ -49,7 +66,7 @@ export const GET = withWorkspace(
...parsedParams,
event,
groupBy,
- ...(linkId && { linkId }),
+ ...(link && { linkId: link.id }),
workspaceId: workspace.id,
isDeprecatedClicksEndpoint,
});
diff --git a/apps/web/app/api/domains/[domain]/primary/route.ts b/apps/web/app/api/domains/[domain]/primary/route.ts
index 00f9a4a67f..2e41bfaa42 100644
--- a/apps/web/app/api/domains/[domain]/primary/route.ts
+++ b/apps/web/app/api/domains/[domain]/primary/route.ts
@@ -1,3 +1,4 @@
+import { getDomain } from "@/lib/api/domains/get-domain";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { DomainSchema } from "@/lib/zod/schemas/domains";
@@ -5,7 +6,12 @@ import { NextResponse } from "next/server";
// POST /api/domains/[domain]/primary – set a domain as primary
export const POST = withWorkspace(
- async ({ headers, workspace, domain }) => {
+ async ({ headers, workspace, params }) => {
+ const { slug: domain } = await getDomain({
+ workspace,
+ slug: params.domain,
+ });
+
const [domainRecord] = await Promise.all([
prisma.domain.update({
where: {
@@ -15,6 +21,7 @@ export const POST = withWorkspace(
primary: true,
},
}),
+
// Set all other domains as not primary
prisma.domain.updateMany({
where: {
@@ -33,7 +40,6 @@ export const POST = withWorkspace(
return NextResponse.json(DomainSchema.parse(domainRecord), { headers });
},
{
- domainChecks: true,
requiredRole: ["owner"],
},
);
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.ts
index deedc2d140..ba41ed6e1a 100644
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@ -4,6 +4,7 @@ import {
removeDomainFromVercel,
validateDomain,
} from "@/lib/api/domains";
+import { getDomain } from "@/lib/api/domains/get-domain";
import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
@@ -18,27 +19,24 @@ import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// GET /api/domains/[domain] – get a workspace's domain
-export const GET = withWorkspace(
- async ({ domain, workspace }) => {
- const domainRecord = await prisma.domain.findUnique({
- where: {
- slug: domain,
- projectId: workspace.id,
- },
- });
+export const GET = withWorkspace(async ({ workspace, params }) => {
+ const domainRecord = await getDomain({
+ workspace,
+ slug: params.domain,
+ });
- return NextResponse.json(DomainSchema.parse(domainRecord));
- },
- {
- domainChecks: true,
- },
-);
+ return NextResponse.json(DomainSchema.parse(domainRecord));
+});
// PUT /api/domains/[domain] – edit a workspace's domain
export const PATCH = withWorkspace(
- async ({ req, workspace, domain }) => {
- const body = await parseRequestBody(req);
- const payload = updateDomainBodySchema.parse(body);
+ async ({ req, workspace, params }) => {
+ const { slug: domain } = await getDomain({
+ workspace,
+ slug: params.domain,
+ });
+
+ const payload = updateDomainBodySchema.parse(await parseRequestBody(req));
const { slug: newDomain, placeholder, expiredUrl, archived } = payload;
@@ -122,19 +120,23 @@ export const PATCH = withWorkspace(
return NextResponse.json(DomainSchema.parse(domainRecord));
},
{
- domainChecks: true,
requiredRole: ["owner"],
},
);
// DELETE /api/domains/[domain] - delete a workspace's domain
export const DELETE = withWorkspace(
- async ({ domain }) => {
+ async ({ workspace, params }) => {
+ const { slug: domain } = await getDomain({
+ workspace,
+ slug: params.domain,
+ });
+
await deleteDomainAndLinks(domain);
+
return NextResponse.json({ slug: domain });
},
{
- domainChecks: true,
requiredRole: ["owner"],
},
);
diff --git a/apps/web/app/api/domains/[domain]/verify/route.ts b/apps/web/app/api/domains/[domain]/verify/route.ts
index dc4e10de55..8e1d639a15 100644
--- a/apps/web/app/api/domains/[domain]/verify/route.ts
+++ b/apps/web/app/api/domains/[domain]/verify/route.ts
@@ -3,6 +3,7 @@ import {
getDomainResponse,
verifyDomain,
} from "@/lib/api/domains";
+import { getDomain } from "@/lib/api/domains/get-domain";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { DomainVerificationStatusProps } from "@/lib/types";
@@ -11,7 +12,12 @@ import { NextResponse } from "next/server";
export const maxDuration = 30;
// GET /api/domains/[domain]/verify - get domain verification status
-export const GET = withWorkspace(async ({ domain }) => {
+export const GET = withWorkspace(async ({ workspace, params }) => {
+ const { slug: domain } = await getDomain({
+ workspace,
+ slug: params.domain,
+ });
+
let status: DomainVerificationStatusProps = "Valid Configuration";
const [domainJson, configJson] = await Promise.all([
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index 3e0aa77b7b..2699d8806c 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -5,6 +5,7 @@ import {
transformLink,
updateLink,
} from "@/lib/api/links";
+import { getLink } from "@/lib/api/links/get-link";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
@@ -14,13 +15,11 @@ import { deepEqual } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/links/[linkId] – get a link
-export const GET = withWorkspace(async ({ headers, link }) => {
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: "Link not found.",
- });
- }
+export const GET = withWorkspace(async ({ headers, workspace, params }) => {
+ const link = await getLink({
+ workspace,
+ linkId: params.linkId,
+ });
const tags = await prisma.tag.findMany({
where: {
@@ -49,16 +48,13 @@ export const GET = withWorkspace(async ({ headers, link }) => {
// PATCH /api/links/[linkId] – update a link
export const PATCH = withWorkspace(
- async ({ req, headers, workspace, link }) => {
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: "Link not found.",
- });
- }
+ async ({ req, headers, workspace, params }) => {
+ const link = await getLink({
+ workspace,
+ linkId: params.linkId,
+ });
- const bodyRaw = await parseRequestBody(req);
- const body = updateLinkBodySchema.parse(bodyRaw);
+ const body = updateLinkBodySchema.parse(await parseRequestBody(req));
// Add body onto existing link but maintain NewLinkProps form for processLink
const updatedLink = {
@@ -140,11 +136,16 @@ export const PATCH = withWorkspace(
export const PUT = PATCH;
// DELETE /api/links/[linkId] – delete a link
-export const DELETE = withWorkspace(async ({ headers, link }) => {
- await deleteLink(link!.id);
+export const DELETE = withWorkspace(async ({ headers, workspace, params }) => {
+ const link = await getLink({
+ workspace,
+ linkId: params.linkId,
+ });
+
+ await deleteLink(link.id);
return NextResponse.json(
- { id: link!.id },
+ { id: link.id },
{
headers,
},
diff --git a/apps/web/app/api/links/[linkId]/transfer/route.ts b/apps/web/app/api/links/[linkId]/transfer/route.ts
index bbdac7166a..490919b561 100644
--- a/apps/web/app/api/links/[linkId]/transfer/route.ts
+++ b/apps/web/app/api/links/[linkId]/transfer/route.ts
@@ -1,5 +1,6 @@
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { DubApiError } from "@/lib/api/errors";
+import { getLink } from "@/lib/api/links/get-link";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { recordLink } from "@/lib/tinybird";
@@ -19,6 +20,11 @@ const transferLinkBodySchema = z.object({
// POST /api/links/[linkId]/transfer – transfer a link to another workspace
export const POST = withWorkspace(
async ({ req, headers, session, params, workspace }) => {
+ const link = await getLink({
+ workspace,
+ linkId: params.linkId,
+ });
+
const { newWorkspaceId } = transferLinkBodySchema.parse(await req.json());
const newWorkspace = await prisma.project.findUnique({
@@ -37,22 +43,6 @@ export const POST = withWorkspace(
},
});
- const link = await prisma.link.findUnique({
- where: {
- id: params.linkId,
- },
- include: {
- tags: true,
- },
- });
- // technically this is not needed since the link is already checked in withWorkspace
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: "Link not found.",
- });
- }
-
if (!newWorkspace || newWorkspace.users.length === 0) {
throw new DubApiError({
code: "not_found",
diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.ts
index 6bdfb9544f..bc1b39fc88 100644
--- a/apps/web/app/api/links/info/route.ts
+++ b/apps/web/app/api/links/info/route.ts
@@ -1,60 +1,58 @@
import { DubApiError } from "@/lib/api/errors";
import { transformLink } from "@/lib/api/links";
+import { getLink } from "@/lib/api/links/get-link";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getLinkInfoQuerySchema } from "@/lib/zod/schemas/links";
import { NextResponse } from "next/server";
// GET /api/links/info – get the info for a link
-export const GET = withWorkspace(async ({ headers, searchParams, link }) => {
- const { domain, key, linkId, externalId } =
- getLinkInfoQuerySchema.parse(searchParams);
+export const GET = withWorkspace(
+ async ({ headers, searchParams, workspace }) => {
+ const { domain, key, linkId, externalId } =
+ getLinkInfoQuerySchema.parse(searchParams);
- if (!domain && !key && !linkId && !externalId) {
- throw new DubApiError({
- code: "bad_request",
- message:
- "You must provide a domain and a key or a linkId or an externalId to retrieve a link.",
- docUrl: "https://dub.co/docs/api-reference/endpoint/retrieve-a-link",
- });
- }
-
- if (!link) {
- if (externalId && !externalId.startsWith("ext_")) {
+ if (!domain && !key && !linkId && !externalId) {
throw new DubApiError({
code: "bad_request",
- message: "Invalid externalId. Did you forget to prefix it with `ext_`?",
+ message:
+ "You must provide a domain and a key or a linkId or an externalId to retrieve a link.",
+ docUrl: "https://dub.co/docs/api-reference/endpoint/retrieve-a-link",
});
}
- throw new DubApiError({
- code: "not_found",
- message: "Link not found.",
+
+ const link = await getLink({
+ workspace,
+ linkId,
+ externalId,
+ domain,
+ key,
});
- }
- const tags = await prisma.tag.findMany({
- where: {
- links: {
- some: {
- linkId: link.id,
+ const tags = await prisma.tag.findMany({
+ where: {
+ links: {
+ some: {
+ linkId: link.id,
+ },
},
},
- },
- select: {
- id: true,
- name: true,
- color: true,
- },
- });
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ });
- const response = transformLink({
- ...link,
- tags: tags.map((tag) => {
- return { tag };
- }),
- });
+ const response = transformLink({
+ ...link,
+ tags: tags.map((tag) => {
+ return { tag };
+ }),
+ });
- return NextResponse.json(response, {
- headers,
- });
-});
+ return NextResponse.json(response, {
+ headers,
+ });
+ },
+);
diff --git a/apps/web/lib/api/domains/get-domain.ts b/apps/web/lib/api/domains/get-domain.ts
new file mode 100644
index 0000000000..acc95022ff
--- /dev/null
+++ b/apps/web/lib/api/domains/get-domain.ts
@@ -0,0 +1,45 @@
+import { prisma } from "@/lib/prisma";
+import { WorkspaceProps } from "@/lib/types";
+import { Domain } from "@prisma/client";
+import { DubApiError } from "../errors";
+
+interface GetDomainParams {
+ workspace: WorkspaceProps;
+ linkId?: string;
+ slug?: string;
+ key?: string;
+}
+
+// Find domain
+export const getDomain = async ({
+ workspace,
+ slug,
+ linkId,
+ key,
+}: GetDomainParams) => {
+ let domain: Domain | null = null;
+
+ if (slug) {
+ domain = await prisma.domain.findUnique({
+ where: {
+ slug,
+ },
+ });
+ }
+
+ if (!domain) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Domain not found",
+ });
+ }
+
+ if (domain.projectId !== workspace.id) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Domain not found",
+ });
+ }
+
+ return domain;
+};
diff --git a/apps/web/lib/api/links/get-link.ts b/apps/web/lib/api/links/get-link.ts
new file mode 100644
index 0000000000..161d787aa5
--- /dev/null
+++ b/apps/web/lib/api/links/get-link.ts
@@ -0,0 +1,78 @@
+import { prisma } from "@/lib/prisma";
+import { WorkspaceProps } from "@/lib/types";
+import { Link } from "@prisma/client";
+import { DubApiError } from "../errors";
+
+interface GetLinkParams {
+ workspace: WorkspaceProps;
+ linkId?: string;
+ externalId?: string;
+ domain?: string;
+ key?: string;
+}
+
+// Find link
+export const getLink = async (params: GetLinkParams) => {
+ const { workspace, domain, key, externalId } = params;
+ const linkId = params.linkId || params.externalId || undefined;
+
+ // if (!linkId || !externalId || !domain || !key) {
+ // return null;
+ // }
+
+ const { id: workspaceId } = workspace;
+ let link: Link | null = null;
+
+ // Get link by linkId or externalId
+ if (linkId) {
+ link = await prisma.link.findUnique({
+ where: {
+ ...(linkId.startsWith("ext_") && workspaceId
+ ? {
+ projectId_externalId: {
+ projectId: workspaceId,
+ externalId: linkId.replace("ext_", ""),
+ },
+ }
+ : { id: linkId }),
+ },
+ });
+ }
+
+ // Get link by domain and key
+ else if (domain && key) {
+ link = await prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain,
+ key,
+ },
+ },
+ });
+ }
+
+ if (!link) {
+ if (externalId && !externalId.startsWith("ext_")) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invalid externalId. Did you forget to prefix it with `ext_`?",
+ });
+ }
+
+ throw new DubApiError({
+ code: "not_found",
+ message: "Link not found.",
+ });
+ }
+
+ if (link.projectId !== workspaceId) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "You do not have permission to access this link.",
+ });
+ }
+
+ console.log("Link found:", link);
+
+ return link;
+};
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index f62b621b0a..5f56f2ec88 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -6,13 +6,7 @@ import {
import { prisma } from "@/lib/prisma";
import { PlanProps, WorkspaceProps } from "@/lib/types";
import { ratelimit } from "@/lib/upstash";
-import {
- API_DOMAIN,
- DUB_WORKSPACE_ID,
- getSearchParams,
- isDubDomain,
-} from "@dub/utils";
-import { Link as LinkProps } from "@prisma/client";
+import { API_DOMAIN, getSearchParams } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { isBetaTester } from "../edge-config";
import { hashToken } from "./hash-token";
@@ -26,8 +20,6 @@ interface WithWorkspaceHandler {
headers,
session,
workspace,
- domain,
- link,
}: {
req: Request;
params: Record<string, string>;
@@ -35,8 +27,6 @@ interface WithWorkspaceHandler {
headers?: Record<string, string>;
session: Session;
workspace: WorkspaceProps;
- domain: string;
- link?: LinkProps;
}): Promise<Response>;
}
@@ -57,8 +47,6 @@ export const withWorkspace = (
needNotExceededLinks, // if the action needs the user to not have exceeded their links usage
allowAnonymous, // special case for /api/links (POST /api/links) – allow no session
allowSelf, // special case for removing yourself from a workspace
- skipLinkChecks, // special case for /api/links/exists – skip link checks
- domainChecks, // if the action needs to check if the domain belongs to the workspace
betaFeature, // if the action is a beta feature
}: {
requiredPlan?: Array<PlanProps>;
@@ -67,8 +55,6 @@ export const withWorkspace = (
needNotExceededLinks?: boolean;
allowAnonymous?: boolean;
allowSelf?: boolean;
- skipLinkChecks?: boolean;
- domainChecks?: boolean;
betaFeature?: boolean;
} = {},
) => {
@@ -94,14 +80,6 @@ export const withWorkspace = (
apiKey = authorizationHeader.replace("Bearer ", "");
}
- const domain = params?.domain || searchParams.domain;
- const key = searchParams.key;
- const linkId =
- params?.linkId ||
- searchParams.linkId ||
- searchParams.externalId ||
- undefined;
-
let session: Session | undefined;
let workspaceId: string | undefined;
let workspaceSlug: string | undefined;
@@ -166,6 +144,7 @@ export const withWorkspace = (
600,
"1 m",
).limit(apiKey);
+
headers = {
"Retry-After": reset.toString(),
"X-RateLimit-Limit": limit.toString(),
@@ -179,6 +158,7 @@ export const withWorkspace = (
message: "Too many requests.",
});
}
+
waitUntil(
prisma.token.update({
where: {
@@ -189,6 +169,7 @@ export const withWorkspace = (
},
}),
);
+
session = {
user: {
id: user.id,
@@ -198,6 +179,7 @@ export const withWorkspace = (
};
} else {
session = await getSession();
+
if (!session?.user?.id) {
throw new DubApiError({
code: "unauthorized",
@@ -206,57 +188,32 @@ export const withWorkspace = (
}
}
- let [workspace, link] = (await Promise.all([
- prisma.project.findUnique({
- where: {
- id: workspaceId || undefined,
- slug: workspaceSlug || undefined,
- },
- include: {
- users: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
- },
+ let workspace = (await prisma.project.findUnique({
+ where: {
+ id: workspaceId || undefined,
+ slug: workspaceSlug || undefined,
+ },
+ include: {
+ users: {
+ where: {
+ userId: session.user.id,
},
- domains: {
- select: {
- id: true,
- slug: true,
- primary: true,
- },
+ select: {
+ role: true,
},
},
- }),
- linkId
- ? prisma.link.findUnique({
- where: {
- ...(linkId.startsWith("ext_") && workspaceId
- ? {
- projectId_externalId: {
- projectId: workspaceId,
- externalId: linkId.replace("ext_", ""),
- },
- }
- : { id: linkId }),
- },
- })
- : domain && key
- ? prisma.link.findUnique({
- where: {
- domain_key: {
- domain,
- key,
- },
- },
- })
- : undefined,
- ])) as [WorkspaceProps, LinkProps | undefined];
+ domains: {
+ select: {
+ id: true,
+ slug: true,
+ primary: true,
+ },
+ },
+ },
+ })) as WorkspaceProps;
+ // workspace doesn't exist
if (!workspace || !workspace.users) {
- // workspace doesn't exist
throw new DubApiError({
code: "not_found",
message: "Workspace not found.",
@@ -274,38 +231,6 @@ export const withWorkspace = (
}
}
- // edge case where linkId is an externalId and workspaceId was not provided (they must've used projectSlug instead)
- // in this case, we need to try fetching the link again
- if (linkId && linkId.startsWith("ext_") && !link && !workspaceId) {
- link = (await prisma.link.findUnique({
- where: {
- projectId_externalId: {
- projectId: workspace.id,
- externalId: linkId.replace("ext_", ""),
- },
- },
- })) as LinkProps;
- }
-
- // if domain is defined:
- // - it's a dub domain and domainChecks is required, check if the user is part of the dub workspace
- // - it's a custom domain, check if the domain belongs to the workspace
- if (domain) {
- if (isDubDomain(domain)) {
- if (domainChecks && workspace.id !== DUB_WORKSPACE_ID) {
- throw new DubApiError({
- code: "forbidden",
- message: "Domain does not belong to workspace.",
- });
- }
- } else if (!workspace.domains.find((d) => d.slug === domain)) {
- throw new DubApiError({
- code: "forbidden",
- message: "Domain does not belong to workspace.",
- });
- }
- }
-
// workspace exists but user is not part of it
if (workspace.users.length === 0) {
const pendingInvites = await prisma.projectInvite.findUnique({
@@ -397,17 +322,6 @@ export const withWorkspace = (
});
}
- // link checks (if linkId or domain and key are provided)
- if ((linkId || (domain && key && key !== "_root")) && !skipLinkChecks) {
- // make sure the link is owned by the workspace
- if (!link || link.projectId !== workspace?.id) {
- throw new DubApiError({
- code: "not_found",
- message: "Link not found.",
- });
- }
- }
-
return await handler({
req,
params,
@@ -415,8 +329,6 @@ export const withWorkspace = (
headers,
session,
workspace,
- domain,
- link,
});
} catch (error) {
return handleAndReturnErrorResponse(error, headers);
diff --git a/apps/web/package.json b/apps/web/package.json
index 95d033f88e..c2e78549ea 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -79,7 +79,6 @@
"openapi-types": "^12.1.3",
"openapi3-ts": "^4.2.1",
"postmark": "^4.0.2",
- "prisma": "^5.15.1",
"react": "^18.2.0",
"react-colorful": "^5.6.1",
"react-dom": "^18.2.0",
@@ -124,6 +123,7 @@
"papaparse": "^5.4.1",
"postcss": "^8.4.31",
"postcss-import": "^15.1.0",
+ "prisma": "^5.15.1",
"tailwindcss": "^3.3.3",
"tsx": "^3.14.0",
"turbo": "^1.10.14",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 721d93b175..6194e9bd7c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -235,9 +235,6 @@ importers:
postmark:
specifier: ^4.0.2
version: 4.0.2
- prisma:
- specifier: ^5.15.1
- version: 5.15.1
react:
specifier: ^18.2.0
version: 18.2.0
@@ -365,6 +362,9 @@ importers:
postcss-import:
specifier: ^15.1.0
version: 15.1.0([email protected])
+ prisma:
+ specifier: ^5.15.1
+ version: 5.15.1
tailwindcss:
specifier: ^3.3.3
version: 3.3.3
@@ -4772,7 +4772,6 @@ packages:
resolution: {integrity: sha512-NQjdEplhXEcPvf84ghxExC+LD+iTimbg3sZvA3BhybVQIocBEBxFf9GTHhmRVPmjrWoBaYJBVgEEBXZT27JTbQ==}
- dev: false
resolution: {integrity: sha512-SaimwvGuvXJTsWH+FOfl7PlkZZlPiRGeMEchC0kvB08Xw9B3CLYo/Q7zaY5Fp+u5D8asrpcFQmCjXEgDvOmPkg==}
@@ -4782,7 +4781,6 @@ packages:
/@prisma/engines-version@5.15.1-1.5675a3182f972f1a8f31d16eee6abf4fd54910e3:
resolution: {integrity: sha512-7csphKGCG6n/cN1MkT1mJvQ78Ir18IknlYZ8eyEoLKdQBb0HscR/6TyPmzqrMA7Rz01K1KeXqctwAqxtA/lKQg==}
- dev: false
resolution: {integrity: sha512-1iTRxJEFvpBpEWf2bYiMG6LBBQhX7X+GA5piH+tmPWgc/v+/ElxQf2kjQxby8AErmZqtZkdoKJ7FSRjNjBPE9Q==}
@@ -4792,7 +4790,6 @@ packages:
'@prisma/engines-version': 5.15.1-1.5675a3182f972f1a8f31d16eee6abf4fd54910e3
'@prisma/fetch-engine': 5.15.1
'@prisma/get-platform': 5.15.1
- dev: false
resolution: {integrity: sha512-mj0wfsJ+mAdDp1ynT2JKxAXa+CoYMT267qF7g2Uv+oaVTI2CMfGWouMARht8T2QLTgl+gpXSFTwIYbcR+oWEtw==}
@@ -4800,13 +4797,11 @@ packages:
'@prisma/debug': 5.15.1
'@prisma/engines-version': 5.15.1-1.5675a3182f972f1a8f31d16eee6abf4fd54910e3
'@prisma/get-platform': 5.15.1
- dev: false
resolution: {integrity: sha512-oFccp7bYys+ZYkmtYzjR+0cRrGKvSuF+h5QhSkyEsYQ9kzJzQRvuWt2SiHRPt8xOQ4MTmujM+bP5uOexnnAHdQ==}
dependencies:
'@prisma/debug': 5.15.1
- dev: false
/@protobufjs/[email protected]:
resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}
@@ -16297,7 +16292,6 @@ packages:
requiresBuild: true
dependencies:
'@prisma/engines': 5.15.1
- dev: false
resolution: {integrity: sha512-Kx/1w86q/epKcmte75LNrEoT+lX8pBpavuAbvJWRXar7Hz8jrtF+e3vY751p0R8H9HdArwaCTNDDzHg/ScJK1Q==}