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.

split auth/index, withAuth → withWorkspace

Steven Tey164e357bddac
diff --git a/apps/web/app/api/analytics/[endpoint]/route.ts b/apps/web/app/api/analytics/[endpoint]/route.ts
index c3f8ca2766..ca6153283e 100644
--- a/apps/web/app/api/analytics/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/[endpoint]/route.ts
@@ -1,6 +1,6 @@
import { getAnalytics } from "@/lib/analytics";
import { DubApiError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
import {
analyticsEndpointSchema,
@@ -9,7 +9,7 @@ import {
import { NextResponse } from "next/server";
// GET /api/analytics/[endpoint] – get analytics for a specific endpoint
-export const GET = withAuth(
+export const GET = withWorkspace(
async ({ params, searchParams, workspace, link }) => {
const { endpoint } = analyticsEndpointSchema.parse(params);
const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.ts
index b9d0b58cb2..c0337a1587 100644
--- a/apps/web/app/api/analytics/export/route.ts
+++ b/apps/web/app/api/analytics/export/route.ts
@@ -1,6 +1,6 @@
import { VALID_TINYBIRD_ENDPOINTS, getAnalytics } from "@/lib/analytics";
import { DubApiError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
import prisma from "@/lib/prisma";
import { getAnalyticsQuerySchema } from "@/lib/zod/schemas";
@@ -21,7 +21,7 @@ const convertToCSV = (data: object[]) => {
};
// GET /api/analytics/[endpoint]/export – get export data for analytics
-export const GET = withAuth(
+export const GET = withWorkspace(
async ({ searchParams, workspace, link }) => {
const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
const { domain, key, interval } = parsedParams;
diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.ts
index a4815515c6..b4cf3131a0 100644
--- a/apps/web/app/api/analytics/route.ts
+++ b/apps/web/app/api/analytics/route.ts
@@ -1,4 +1,4 @@
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { getDomainOrLink } from "@/lib/planetscale";
import prisma from "@/lib/prisma";
import z from "@/lib/zod";
@@ -10,14 +10,14 @@ const updatePublicStatsSchema = z.object({
});
// GET /api/analytics – get the publicStats setting for a link
-export const GET = withAuth(async ({ searchParams }) => {
+export const GET = withWorkspace(async ({ searchParams }) => {
const { domain, key } = domainKeySchema.parse(searchParams);
const response = await getDomainOrLink({ domain, key });
return NextResponse.json(response);
});
// PUT /api/analytics – update the publicStats setting for a link
-export const PUT = withAuth(async ({ req, searchParams }) => {
+export const PUT = withWorkspace(async ({ req, searchParams }) => {
const { domain, key } = domainKeySchema.parse(searchParams);
const { publicStats } = updatePublicStatsSchema.parse(await req.json());
const response =
diff --git a/apps/web/app/api/auth/[...nextauth]/route.tsx b/apps/web/app/api/auth/[...nextauth]/route.tsx
index 6f6b0d5548..ca0b5b4a86 100644
--- a/apps/web/app/api/auth/[...nextauth]/route.tsx
+++ b/apps/web/app/api/auth/[...nextauth]/route.tsx
@@ -1,4 +1,4 @@
-import { authOptions } from "@/lib/auth/options";
+import { authOptions } from "@/lib/auth";
import NextAuth from "next-auth";
const handler = NextAuth(authOptions);
diff --git a/apps/web/app/api/domains/[domain]/primary/route.ts b/apps/web/app/api/domains/[domain]/primary/route.ts
index 85fa5b2682..36e407a73b 100644
--- a/apps/web/app/api/domains/[domain]/primary/route.ts
+++ b/apps/web/app/api/domains/[domain]/primary/route.ts
@@ -1,10 +1,10 @@
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { DomainSchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// POST /api/domains/[domain]/primary – set a domain as primary
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ headers, workspace, domain }) => {
const responses = await Promise.all([
prisma.domain.update({
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.ts
index c31a49d0d5..9e03fa5872 100644
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@ -7,13 +7,13 @@ import {
} from "@/lib/api/domains";
import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { DomainSchema, updateDomainBodySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// GET /api/domains/[domain] – get a workspace's domain
-export const GET = withAuth(
+export const GET = withWorkspace(
async ({ domain }) => {
const data = await prisma.domain.findUnique({
where: {
@@ -47,7 +47,7 @@ export const GET = withAuth(
);
// PUT /api/domains/[domain] – edit a workspace's domain
-export const PATCH = withAuth(
+export const PATCH = withWorkspace(
async ({ req, workspace, domain }) => {
const body = await parseRequestBody(req);
const {
@@ -118,7 +118,7 @@ export const PATCH = withAuth(
);
// DELETE /api/domains/[domain] - delete a workspace's domain
-export const DELETE = withAuth(
+export const DELETE = withWorkspace(
async ({ domain }) => {
await deleteDomainAndLinks(domain);
return NextResponse.json({ slug: domain });
diff --git a/apps/web/app/api/domains/[domain]/transfer/route.ts b/apps/web/app/api/domains/[domain]/transfer/route.ts
index 58d68631c3..86224467f3 100644
--- a/apps/web/app/api/domains/[domain]/transfer/route.ts
+++ b/apps/web/app/api/domains/[domain]/transfer/route.ts
@@ -1,7 +1,7 @@
import { getAnalytics } from "@/lib/analytics";
import { setRootDomain } from "@/lib/api/domains";
import { DubApiError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { DomainSchema, transferDomainBodySchema } from "@/lib/zod/schemas";
@@ -9,7 +9,7 @@ import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
// POST /api/domains/[domain]/transfer – transfer a domain to another workspace
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ req, headers, session, params, workspace }) => {
const { domain } = params;
const { newWorkspaceId } = transferDomainBodySchema.parse(await req.json());
diff --git a/apps/web/app/api/domains/[domain]/verify/route.ts b/apps/web/app/api/domains/[domain]/verify/route.ts
index ccbc19c018..e0dc0cd4df 100644
--- a/apps/web/app/api/domains/[domain]/verify/route.ts
+++ b/apps/web/app/api/domains/[domain]/verify/route.ts
@@ -3,7 +3,7 @@ import {
getDomainResponse,
verifyDomain,
} from "@/lib/api/domains";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { DomainVerificationStatusProps } from "@/lib/types";
import { NextResponse } from "next/server";
@@ -11,7 +11,7 @@ import { NextResponse } from "next/server";
export const maxDuration = 30;
// GET /api/domains/[domain]/verify - get domain verification status
-export const GET = withAuth(async ({ domain }) => {
+export const GET = withWorkspace(async ({ domain }) => {
let status: DomainVerificationStatusProps = "Valid Configuration";
const [domainJson, configJson] = await Promise.all([
diff --git a/apps/web/app/api/domains/default/route.ts b/apps/web/app/api/domains/default/route.ts
index d8064cef3b..0579507e62 100644
--- a/apps/web/app/api/domains/default/route.ts
+++ b/apps/web/app/api/domains/default/route.ts
@@ -1,11 +1,11 @@
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import z from "@/lib/zod";
import { DUB_DOMAINS_ARRAY } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/domains/default - get default domains
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const defaultDomains = await prisma.defaultDomains.findUnique({
where: {
projectId: workspace.id,
@@ -38,7 +38,7 @@ const updateDefaultDomainsSchema = z.object({
});
// PUT /api/domains/default - edit default domains
-export const PUT = withAuth(async ({ req, workspace }) => {
+export const PUT = withWorkspace(async ({ req, workspace }) => {
const { defaultDomains } = await updateDefaultDomainsSchema.parseAsync(
await req.json(),
);
diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.ts
index 243ec3696a..160695ab01 100644
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@ -5,13 +5,13 @@ import {
} from "@/lib/api/domains";
import { exceededLimitError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { DomainSchema, addDomainBodySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// GET /api/domains – get all domains for a workspace
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const domains = await prisma.domain.findMany({
where: {
projectId: workspace.id,
@@ -32,7 +32,7 @@ export const GET = withAuth(async ({ workspace }) => {
});
// POST /api/domains - add a domain
-export const POST = withAuth(async ({ req, workspace }) => {
+export const POST = withWorkspace(async ({ req, workspace }) => {
const body = await parseRequestBody(req);
const {
slug: domain,
diff --git a/apps/web/app/api/links/[linkId]/archive/route.ts b/apps/web/app/api/links/[linkId]/archive/route.ts
index d4d136670a..b89fc3b48b 100644
--- a/apps/web/app/api/links/[linkId]/archive/route.ts
+++ b/apps/web/app/api/links/[linkId]/archive/route.ts
@@ -1,15 +1,15 @@
import { archiveLink } from "@/lib/api/links";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { NextResponse } from "next/server";
// POST /api/links/[linkId]/archive – archive a link
-export const POST = withAuth(async ({ headers, link }) => {
+export const POST = withWorkspace(async ({ headers, link }) => {
const response = await archiveLink({ linkId: link!.id, archived: true });
return NextResponse.json(response, { headers });
});
// DELETE /api/links/[linkId]/archive – unarchive a link
-export const DELETE = withAuth(async ({ headers, link }) => {
+export const DELETE = withWorkspace(async ({ headers, link }) => {
const response = await archiveLink({ linkId: link!.id, archived: false });
return NextResponse.json(response, { headers });
});
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index 0e58921952..953d6f5cbe 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -1,13 +1,13 @@
import { DubApiError, ErrorCodes } from "@/lib/api/errors";
import { deleteLink, editLink, processLink } from "@/lib/api/links";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { LinkWithTagIdsProps } from "@/lib/types";
import { updateLinkBodySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// GET /api/links/[linkId] – get a link
-export const GET = withAuth(async ({ headers, link }) => {
+export const GET = withWorkspace(async ({ headers, link }) => {
if (!link) {
throw new DubApiError({
code: "not_found",
@@ -42,7 +42,7 @@ export const GET = withAuth(async ({ headers, link }) => {
});
// PUT /api/links/[linkId] – update a link
-export const PUT = withAuth(async ({ req, headers, workspace, link }) => {
+export const PUT = withWorkspace(async ({ req, headers, workspace, link }) => {
if (!link) {
throw new DubApiError({
code: "not_found",
@@ -97,7 +97,7 @@ export const PUT = withAuth(async ({ req, headers, workspace, link }) => {
});
// DELETE /api/links/[linkId] – delete a link
-export const DELETE = withAuth(async ({ headers, link }) => {
+export const DELETE = withWorkspace(async ({ headers, link }) => {
await deleteLink(link!.id);
return NextResponse.json(
diff --git a/apps/web/app/api/links/[linkId]/transfer/route.ts b/apps/web/app/api/links/[linkId]/transfer/route.ts
index 3f88430c56..bc0dabdda8 100644
--- a/apps/web/app/api/links/[linkId]/transfer/route.ts
+++ b/apps/web/app/api/links/[linkId]/transfer/route.ts
@@ -1,6 +1,6 @@
import { getAnalytics } from "@/lib/analytics";
import { DubApiError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { recordLink } from "@/lib/tinybird";
import { formatRedisLink, redis } from "@/lib/upstash";
@@ -16,7 +16,7 @@ const transferLinkBodySchema = z.object({
});
// POST /api/links/[linkId]/transfer – transfer a link to another workspace
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ req, headers, session, params, workspace }) => {
const { newWorkspaceId } = transferLinkBodySchema.parse(await req.json());
@@ -44,7 +44,7 @@ export const POST = withAuth(
tags: true,
},
});
- // technically this is not needed since the link is already checked in withAuth
+ // technically this is not needed since the link is already checked in withWorkspace
if (!link) {
throw new DubApiError({
code: "not_found",
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index 6b42df5063..993245be4a 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -1,13 +1,13 @@
import { DubApiError, exceededLimitError } from "@/lib/api/errors";
import { bulkCreateLinks, combineTagIds, processLink } from "@/lib/api/links";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { LinkWithTagIdsProps } from "@/lib/types";
import { bulkCreateLinksBodySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// POST /api/links/bulk – bulk create up to 100 links
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ req, headers, session, workspace }) => {
if (!workspace) {
throw new DubApiError({
diff --git a/apps/web/app/api/links/count/route.ts b/apps/web/app/api/links/count/route.ts
index c1edd6a8c0..c6467aaf0f 100644
--- a/apps/web/app/api/links/count/route.ts
+++ b/apps/web/app/api/links/count/route.ts
@@ -1,19 +1,21 @@
import { getLinksCount } from "@/lib/api/links";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { getLinksCountQuerySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// GET /api/links/count – get the number of links for a workspace
-export const GET = withAuth(async ({ headers, searchParams, workspace }) => {
- const { userId, ...params } = getLinksCountQuerySchema.parse(searchParams);
+export const GET = withWorkspace(
+ async ({ headers, searchParams, workspace }) => {
+ const { userId, ...params } = getLinksCountQuerySchema.parse(searchParams);
- const count = await getLinksCount({
- searchParams: params,
- workspaceId: workspace.id,
- userId,
- });
+ const count = await getLinksCount({
+ searchParams: params,
+ workspaceId: workspace.id,
+ userId,
+ });
- return NextResponse.json(count, {
- headers,
- });
-});
+ return NextResponse.json(count, {
+ headers,
+ });
+ },
+);
diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.ts
index 9ad7955986..0484430306 100644
--- a/apps/web/app/api/links/info/route.ts
+++ b/apps/web/app/api/links/info/route.ts
@@ -1,12 +1,12 @@
import { DubApiError } from "@/lib/api/errors";
import { transformLink } from "@/lib/api/links";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { domainKeySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// GET /api/links/info – get the info for a link
-export const GET = withAuth(async ({ headers, searchParams }) => {
+export const GET = withWorkspace(async ({ headers, searchParams }) => {
const { domain, key } = domainKeySchema.parse(searchParams);
const link = await prisma.link.findUnique({
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index 9f4629bb9e..574ae6fb47 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -1,6 +1,6 @@
import { DubApiError, ErrorCodes } from "@/lib/api/errors";
import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { LinkWithTagIdsProps } from "@/lib/types";
import { ratelimit } from "@/lib/upstash";
import { createLinkBodySchema, getLinksQuerySchema } from "@/lib/zod/schemas";
@@ -8,39 +8,41 @@ import { LOCALHOST_IP } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/links – get all links for a workspace
-export const GET = withAuth(async ({ headers, searchParams, workspace }) => {
- const {
- domain,
- tagId,
- tagIds,
- search,
- sort,
- page,
- userId,
- showArchived,
- withTags,
- } = getLinksQuerySchema.parse(searchParams);
+export const GET = withWorkspace(
+ async ({ headers, searchParams, workspace }) => {
+ const {
+ domain,
+ tagId,
+ tagIds,
+ search,
+ sort,
+ page,
+ userId,
+ showArchived,
+ withTags,
+ } = getLinksQuerySchema.parse(searchParams);
- const response = await getLinksForWorkspace({
- workspaceId: workspace.id,
- domain,
- tagId,
- tagIds,
- search,
- sort,
- page,
- userId,
- showArchived,
- withTags,
- });
+ const response = await getLinksForWorkspace({
+ workspaceId: workspace.id,
+ domain,
+ tagId,
+ tagIds,
+ search,
+ sort,
+ page,
+ userId,
+ showArchived,
+ withTags,
+ });
- return NextResponse.json(response, {
- headers,
- });
-});
+ return NextResponse.json(response, {
+ headers,
+ });
+ },
+);
// POST /api/links – create a new link
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ req, headers, session, workspace }) => {
let bodyRaw;
try {
diff --git a/apps/web/app/api/links/sync/route.ts b/apps/web/app/api/links/sync/route.ts
index e6cdebd727..d195d40ec1 100644
--- a/apps/web/app/api/links/sync/route.ts
+++ b/apps/web/app/api/links/sync/route.ts
@@ -1,12 +1,12 @@
import { exceededLimitError } from "@/lib/api/errors";
import { propagateBulkLinkChanges } from "@/lib/api/links";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { SimpleLinkProps } from "@/lib/types";
import { NextResponse } from "next/server";
// POST /api/links/sync – sync user's publicly created links to their accounts
-export const POST = withAuth(async ({ req, session, workspace }) => {
+export const POST = withWorkspace(async ({ req, session, workspace }) => {
let links: SimpleLinkProps[] = [];
try {
links = await req.json();
diff --git a/apps/web/app/api/tags/[id]/route.ts b/apps/web/app/api/tags/[id]/route.ts
index e29af52fbe..4368352533 100644
--- a/apps/web/app/api/tags/[id]/route.ts
+++ b/apps/web/app/api/tags/[id]/route.ts
@@ -1,12 +1,12 @@
import { DubApiError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { recordLink } from "@/lib/tinybird";
import { updateTagBodySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// PUT /api/workspaces/[idOrSlug]/tags/[id] – update a tag for a workspace
-export const PUT = withAuth(async ({ req, params, workspace }) => {
+export const PUT = withWorkspace(async ({ req, params, workspace }) => {
const { id } = params;
const { name, color } = updateTagBodySchema.parse(await req.json());
@@ -48,7 +48,7 @@ export const PUT = withAuth(async ({ req, params, workspace }) => {
});
// DELETE /api/workspaces/[idOrSlug]/tags/[id] – delete a tag for a workspace
-export const DELETE = withAuth(async ({ params, workspace }) => {
+export const DELETE = withWorkspace(async ({ params, workspace }) => {
const { id } = params;
try {
const response = await prisma.tag.delete({
diff --git a/apps/web/app/api/tags/route.ts b/apps/web/app/api/tags/route.ts
index 13af3b4287..82e8d01457 100644
--- a/apps/web/app/api/tags/route.ts
+++ b/apps/web/app/api/tags/route.ts
@@ -1,12 +1,12 @@
import { DubApiError, exceededLimitError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { createTagBodySchema } from "@/lib/zod/schemas";
import { COLORS_LIST, randomBadgeColor } from "@/ui/links/tag-badge";
import { NextResponse } from "next/server";
// GET /api/tags - get all tags for a workspace
-export const GET = withAuth(async ({ workspace, headers }) => {
+export const GET = withWorkspace(async ({ workspace, headers }) => {
const tags = await prisma.tag.findMany({
where: {
projectId: workspace.id,
@@ -24,7 +24,7 @@ export const GET = withAuth(async ({ workspace, headers }) => {
});
// POST /api/workspaces/[idOrSlug]/tags - create a tag for a workspace
-export const POST = withAuth(async ({ req, workspace, headers }) => {
+export const POST = withWorkspace(async ({ req, workspace, headers }) => {
const tagsCount = await prisma.tag.count({
where: {
projectId: workspace.id,
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/manage/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/manage/route.ts
index f3af82b48d..27eb7de714 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/manage/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/manage/route.ts
@@ -1,10 +1,10 @@
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
// POST /api/workspaces/[idOrSlug]/billing/manage - create a Stripe billing portal session
-export const POST = withAuth(async ({ workspace }) => {
+export const POST = withWorkspace(async ({ workspace }) => {
if (!workspace.stripeId) {
return new Response("No Stripe customer ID", { status: 400 });
}
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
index 9ecdb257f2..7e207fa290 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
@@ -1,9 +1,9 @@
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
-export const POST = withAuth(async ({ req, workspace, session }) => {
+export const POST = withWorkspace(async ({ req, workspace, session }) => {
let { plan, period, baseUrl, comparePlans } = await req.json();
if (!plan || !period) {
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/import/bitly/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/import/bitly/route.ts
index a235840f1c..85074ace6c 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/import/bitly/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/import/bitly/route.ts
@@ -1,5 +1,5 @@
import { addDomainToVercel } from "@/lib/api/domains";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { BitlyGroupProps } from "@/lib/types";
@@ -8,7 +8,7 @@ import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/workspaces/[idOrSlug]/import/bitly – get all bitly groups for a workspace
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const accessToken = await redis.get(`import:bitly:${workspace.id}`);
if (!accessToken) {
return new Response("No Bitly access token found", { status: 400 });
@@ -49,7 +49,7 @@ export const GET = withAuth(async ({ workspace }) => {
});
// POST /api/workspaces/[idOrSlug]/import/bitly - create job to import links from bitly
-export const POST = withAuth(async ({ req, workspace, session }) => {
+export const POST = withWorkspace(async ({ req, workspace, session }) => {
const { selectedDomains, selectedGroupTags } = await req.json();
// check if there are domains that are not in the workspace
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/import/rebrandly/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/import/rebrandly/route.ts
index 22c43a3492..1708ba89ad 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/import/rebrandly/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/import/rebrandly/route.ts
@@ -1,5 +1,5 @@
import { addDomainToVercel } from "@/lib/api/domains";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { redis } from "@/lib/upstash";
@@ -7,7 +7,7 @@ import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/workspaces/[idOrSlug]/import/rebrandly – get all Rebrandly domains for a workspace
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const accessToken = await redis.get(`import:rebrandly:${workspace.id}`);
if (!accessToken) {
return new Response("No Rebrandly access token found", { status: 400 });
@@ -58,14 +58,14 @@ export const GET = withAuth(async ({ workspace }) => {
});
// PUT /api/workspaces/[idOrSlug]/import/rebrandly - save Rebrandly API key
-export const PUT = withAuth(async ({ req, workspace }) => {
+export const PUT = withWorkspace(async ({ req, workspace }) => {
const { apiKey } = await req.json();
const response = await redis.set(`import:rebrandly:${workspace.id}`, apiKey);
return NextResponse.json(response);
});
// POST /api/workspaces/[idOrSlug]/import/rebrandly - create job to import links from Rebrandly
-export const POST = withAuth(async ({ req, workspace, session }) => {
+export const POST = withWorkspace(async ({ req, workspace, session }) => {
const { selectedDomains, importTags } = await req.json();
// check if there are domains that are not in the workspace
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/import/short/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/import/short/route.ts
index 2e98b18dcf..2f435139d3 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/import/short/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/import/short/route.ts
@@ -1,5 +1,5 @@
import { addDomainToVercel } from "@/lib/api/domains";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { redis } from "@/lib/upstash";
@@ -7,7 +7,7 @@ import { APP_DOMAIN_WITH_NGROK, fetchWithTimeout } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/workspaces/[idOrSlug]/import/short – get all short.io domains for a workspace
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const accessToken = await redis.get(`import:short:${workspace.id}`);
if (!accessToken) {
return new Response("No Short.io access token found", { status: 400 });
@@ -52,14 +52,14 @@ export const GET = withAuth(async ({ workspace }) => {
});
// PUT /api/workspaces/[idOrSlug]/import/short - save Short.io API key
-export const PUT = withAuth(async ({ req, workspace }) => {
+export const PUT = withWorkspace(async ({ req, workspace }) => {
const { apiKey } = await req.json();
const response = await redis.set(`import:short:${workspace.id}`, apiKey);
return NextResponse.json(response);
});
// POST /api/workspaces/[idOrSlug]/import/short - create job to import links from Short.io
-export const POST = withAuth(async ({ req, workspace, session }) => {
+export const POST = withWorkspace(async ({ req, workspace, session }) => {
const { selectedDomains, importTags } = await req.json();
// check if there are domains that are not in the workspace
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
index 9b86d98f1b..7a0591aa43 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
@@ -1,9 +1,9 @@
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { nanoid } from "@dub/utils";
import { NextResponse } from "next/server";
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ workspace }) => {
const response = await prisma.project.update({
where: {
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx
index e6b119a636..7f0798b406 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx
@@ -1,6 +1,6 @@
import { DubApiError, exceededLimitError } from "@/lib/api/errors";
import { inviteUser } from "@/lib/api/users";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import z from "@/lib/zod";
import { NextResponse } from "next/server";
@@ -10,7 +10,7 @@ const emailInviteSchema = z.object({
});
// GET /api/workspaces/[idOrSlug]/invites – get invites for a specific workspace
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const invites = await prisma.projectInvite.findMany({
where: {
projectId: workspace.id,
@@ -24,7 +24,7 @@ export const GET = withAuth(async ({ workspace }) => {
});
// POST /api/workspaces/[idOrSlug]/invites – invite a teammate
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ req, workspace, session }) => {
const { email } = emailInviteSchema.parse(await req.json());
@@ -82,7 +82,7 @@ export const POST = withAuth(
);
// DELETE /api/workspaces/[idOrSlug]/invites – delete a pending invite
-export const DELETE = withAuth(
+export const DELETE = withWorkspace(
async ({ searchParams, workspace }) => {
const { email } = emailInviteSchema.parse(searchParams);
const response = await prisma.projectInvite.delete({
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
index 15afd2d63e..1314bb0120 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
@@ -1,4 +1,4 @@
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { storage } from "@/lib/storage";
import z from "@/lib/zod";
@@ -9,7 +9,7 @@ const uploadLogoSchema = z.object({
});
// POST /api/workspaces/[idOrSlug]/logo – upload a new workspace logo
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ req, workspace }) => {
const { image } = uploadLogoSchema.parse(await req.json());
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index 1819be7ecc..2637df8b06 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -1,6 +1,6 @@
import { DubApiError } from "@/lib/api/errors";
import { deleteWorkspace } from "@/lib/api/workspaces";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import { isReservedKey } from "@/lib/edge-config";
import prisma from "@/lib/prisma";
import z from "@/lib/zod";
@@ -32,7 +32,7 @@ const updateWorkspaceSchema = z.object({
});
// GET /api/workspaces/[idOrSlug] – get a specific workspace by id or slug
-export const GET = withAuth(async ({ workspace, headers }) => {
+export const GET = withWorkspace(async ({ workspace, headers }) => {
return NextResponse.json(
{
...workspace,
@@ -43,7 +43,7 @@ export const GET = withAuth(async ({ workspace, headers }) => {
});
// PUT /api/workspaces/[idOrSlug] – update a specific workspace by id or slug
-export const PUT = withAuth(
+export const PUT = withWorkspace(
async ({ req, workspace }) => {
try {
const { name, slug } = await updateWorkspaceSchema.parseAsync(
@@ -77,7 +77,7 @@ export const PUT = withAuth(
);
// DELETE /api/workspaces/[idOrSlug] – delete a specific project
-export const DELETE = withAuth(
+export const DELETE = withWorkspace(
async ({ workspace }) => {
const response = await deleteWorkspace(workspace);
return NextResponse.json(response);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
index 9345387c56..9e0c80ac04 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
@@ -1,4 +1,4 @@
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import jackson, { samlAudience } from "@/lib/jackson";
import z from "@/lib/zod";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
@@ -24,7 +24,7 @@ const deleteSAMLConnectionSchema = z.object({
});
// GET /api/workspaces/[idOrSlug]/saml – get SAML connections for a specific workspace
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const { apiController } = await jackson();
const connections = await apiController.getConnections({
@@ -45,7 +45,7 @@ export const GET = withAuth(async ({ workspace }) => {
});
// POST /api/workspaces/[idOrSlug]/saml – create a new SAML connection
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ req, workspace }) => {
const { metadataUrl, encodedRawMetadata } =
createSAMLConnectionSchema.parse(await req.json());
@@ -71,7 +71,7 @@ export const POST = withAuth(
// DELETE /api/workspaces/[idOrSlug]/saml – delete all SAML connections
-export const DELETE = withAuth(
+export const DELETE = withWorkspace(
async ({ searchParams }) => {
const { clientID, clientSecret } =
deleteSAMLConnectionSchema.parse(searchParams);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts
index 2e4790be7a..86539b9523 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts
@@ -1,5 +1,5 @@
import { DubApiError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import jackson from "@/lib/jackson";
import z from "@/lib/zod";
import { NextResponse } from "next/server";
@@ -14,7 +14,7 @@ const deleteDirectorySchema = z.object({
});
// GET /api/workspaces/[idOrSlug]/scim – get all SCIM directories
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const { directorySyncController } = await jackson();
const { data, error } =
@@ -35,7 +35,7 @@ export const GET = withAuth(async ({ workspace }) => {
});
// POST /api/workspaces/[idOrSlug]/scim – create a new SCIM directory
-export const POST = withAuth(
+export const POST = withWorkspace(
async ({ req, workspace }) => {
const { provider = "okta-scim-v2", currentDirectoryId } =
createDirectorySchema.parse(await req.json());
@@ -63,7 +63,7 @@ export const POST = withAuth(
// DELETE /api/workspaces/[idOrSlug]/scim – delete a SCIM directory
-export const DELETE = withAuth(
+export const DELETE = withWorkspace(
async ({ searchParams }) => {
const { directoryId } = deleteDirectorySchema.parse(searchParams);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
index 957b944c07..63e6b79f32 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
@@ -1,5 +1,5 @@
import { DubApiError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
+import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { roles } from "@/lib/types";
import z from "@/lib/zod";
@@ -19,7 +19,7 @@ const removeUserSchema = z.object({
});
// GET /api/workspaces/[idOrSlug]/users – get users for a specific workspace
-export const GET = withAuth(async ({ workspace }) => {
+export const GET = withWorkspace(async ({ workspace }) => {
const users = await prisma.projectUsers.findMany({
where: {
projectId: workspace.id,
@@ -46,7 +46,7 @@ export const GET = withAuth(async ({ workspace }) => {
});
// PUT /api/workspaces/[idOrSlug]/users – update a user's role for a specific workspace
-export const PUT = withAuth(
+export const PUT = withWorkspace(
async ({ req, workspace }) => {
const { userId, role } = updateRoleSchema.parse(await req.json());
const response = await prisma.projectUsers.update({
@@ -69,7 +69,7 @@ export const PUT = withAuth(
// DELETE /api/workspaces/[idOrSlug]/users – remove a user from a workspace
-export const DELETE = withAuth(
+export const DELETE = withWorkspace(
async ({ searchParams, workspace, session }) => {
const { userId } = removeUserSchema.parse(searchParams);
const [projectUser, totalOwners] = await Promise.all([
diff --git a/apps/web/lib/auth/admin.ts b/apps/web/lib/auth/admin.ts
new file mode 100644
index 0000000000..8784970d07
--- /dev/null
+++ b/apps/web/lib/auth/admin.ts
@@ -0,0 +1,40 @@
+import prisma from "@/lib/prisma";
+import { DUB_WORKSPACE_ID, getSearchParams } from "@dub/utils";
+import { getSession } from "./utils";
+
+// Internal use only (for admin portal)
+interface WithAdminHandler {
+ ({
+ req,
+ params,
+ searchParams,
+ }: {
+ req: Request;
+ params: Record<string, string>;
+ searchParams: Record<string, string>;
+ }): Promise<Response>;
+}
+
+export const withAdmin =
+ (handler: WithAdminHandler) =>
+ async (req: Request, { params }: { params: Record<string, string> }) => {
+ const session = await getSession();
+ if (!session?.user) {
+ return new Response("Unauthorized: Login required.", { status: 401 });
+ }
+
+ const response = await prisma.projectUsers.findUnique({
+ where: {
+ userId_projectId: {
+ userId: session.user.id,
+ projectId: DUB_WORKSPACE_ID,
+ },
+ },
+ });
+ if (!response) {
+ return new Response("Unauthorized: Not an admin.", { status: 401 });
+ }
+
+ const searchParams = getSearchParams(req.url);
+ return handler({ req, params, searchParams });
+ };
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index ddbee3da5a..56caca89ac 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -1,595 +1,5 @@
-import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import prisma from "@/lib/prisma";
-import {
- API_DOMAIN,
- DUB_WORKSPACE_ID,
- getSearchParams,
- isDubDomain,
-} from "@dub/utils";
-import { Link as LinkProps } from "@prisma/client";
-import { createHash } from "crypto";
-import { getServerSession } from "next-auth/next";
-import { exceededLimitError } from "../api/errors";
-import { PlanProps, WorkspaceProps } from "../types";
-import { ratelimit } from "../upstash";
-import { authOptions } from "./options";
-
-export interface Session {
- user: {
- email: string;
- id: string;
- name: string;
- image?: string;
- };
-}
-
-export const getSession = async () => {
- return getServerSession(authOptions) as Promise<Session>;
-};
-
-export const hashToken = (
- token: string,
- {
- noSecret = false,
- }: {
- noSecret?: boolean;
- } = {},
-) => {
- return createHash("sha256")
- .update(`${token}${noSecret ? "" : process.env.NEXTAUTH_SECRET}`)
- .digest("hex");
-};
-
-interface WithAuthHandler {
- ({
- req,
- params,
- searchParams,
- headers,
- session,
- workspace,
- domain,
- link,
- }: {
- req: Request;
- params: Record<string, string>;
- searchParams: Record<string, string>;
- headers?: Record<string, string>;
- session: Session;
- workspace: WorkspaceProps;
- domain: string;
- link?: LinkProps;
- }): Promise<Response>;
-}
-
-export const withAuth = (
- handler: WithAuthHandler,
- {
- requiredPlan = [
- "free",
- "pro",
- "business",
- "business plus",
- "business max",
- "business extra",
- "enterprise",
- ], // if the action needs a specific plan
- requiredRole = ["owner", "member"],
- needNotExceededClicks, // if the action needs the user to not have exceeded their clicks usage
- 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,
- }: {
- requiredPlan?: Array<PlanProps>;
- requiredRole?: Array<"owner" | "member">;
- needNotExceededClicks?: boolean;
- needNotExceededLinks?: boolean;
- allowAnonymous?: boolean;
- allowSelf?: boolean;
- skipLinkChecks?: boolean;
- domainChecks?: boolean;
- } = {},
-) => {
- return async (
- req: Request,
- { params }: { params: Record<string, string> | undefined },
- ) => {
- const searchParams = getSearchParams(req.url);
- const { linkId } = params || {};
-
- let apiKey: string | undefined = undefined;
-
- const authorizationHeader = req.headers.get("Authorization");
- if (authorizationHeader) {
- if (!authorizationHeader.includes("Bearer ")) {
- return new Response(
- "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth ",
- {
- status: 400,
- },
- );
- }
- apiKey = authorizationHeader.replace("Bearer ", "");
- }
-
- const domain = params?.domain || searchParams.domain;
- const key = searchParams.key;
-
- let session: Session | undefined;
- let headers = {};
- let id: string | undefined;
- let slug: string | undefined;
-
- const idOrSlug =
- params?.idOrSlug ||
- searchParams.workspaceId ||
- params?.slug ||
- searchParams.projectSlug;
-
- try {
- // if there's no workspace ID or slug
- if (!idOrSlug) {
- // for /api/links (POST /api/links) – allow no session (but warn if user provides apiKey)
- if (allowAnonymous && !apiKey) {
- // @ts-expect-error
- return await handler({
- req,
- params: params || {},
- searchParams,
- headers,
- });
- } else {
- throw new DubApiError({
- code: "not_found",
- message:
- "Workspace id not found. Did you forget to include a `workspaceId` query parameter? Learn more: https://d.to/id",
- });
- }
- }
-
- if (idOrSlug.startsWith("ws_")) {
- id = idOrSlug.replace("ws_", "");
- } else {
- slug = idOrSlug;
- }
-
- if (apiKey) {
- const hashedKey = hashToken(apiKey, {
- noSecret: true,
- });
-
- const user = await prisma.user.findFirst({
- where: {
- tokens: {
- some: {
- hashedKey,
- },
- },
- },
- select: {
- id: true,
- name: true,
- email: true,
- },
- });
- if (!user) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Invalid API key.",
- });
- }
-
- const { success, limit, reset, remaining } = await ratelimit(
- 10,
- "1 s",
- ).limit(apiKey);
-
- headers = {
- "Retry-After": reset.toString(),
- "X-RateLimit-Limit": limit.toString(),
- "X-RateLimit-Remaining": remaining.toString(),
- "X-RateLimit-Reset": reset.toString(),
- };
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Too many requests.",
- });
- }
- await prisma.token.update({
- where: {
- hashedKey,
- },
- data: {
- lastUsed: new Date(),
- },
- });
- session = {
- user: {
- id: user.id,
- name: user.name || "",
- email: user.email || "",
- },
- };
- } else {
- session = await getSession();
- if (!session?.user?.id) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Login required.",
- });
- }
- }
-
- let [workspace, link] = (await Promise.all([
- prisma.project.findUnique({
- where: {
- id: id || undefined,
- slug: slug || undefined,
- },
- select: {
- id: true,
- name: true,
- slug: true,
- logo: true,
- usage: true,
- usageLimit: true,
- linksUsage: true,
- linksLimit: true,
- domainsLimit: true,
- tagsLimit: true,
- usersLimit: true,
- plan: true,
- stripeId: true,
- billingCycleStart: true,
- createdAt: true,
- users: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
- },
- },
- domains: {
- select: {
- slug: true,
- primary: true,
- },
- },
- inviteCode: true,
- },
- }),
- linkId
- ? prisma.link.findUnique({
- where: {
- id: linkId,
- },
- })
- : domain &&
- key &&
- (key === "_root"
- ? prisma.domain.findUnique({
- where: {
- slug: domain,
- },
- })
- : prisma.link.findUnique({
- where: {
- domain_key: {
- domain,
- key,
- },
- },
- })),
- ])) as [WorkspaceProps, LinkProps | undefined];
-
- if (!workspace || !workspace.users) {
- // workspace doesn't exist
- throw new DubApiError({
- code: "not_found",
- message: "Workspace not found.",
- });
- }
-
- // 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({
- where: {
- email_projectId: {
- email: session.user.email,
- projectId: workspace.id,
- },
- },
- select: {
- expires: true,
- },
- });
- if (!pendingInvites) {
- throw new DubApiError({
- code: "not_found",
- message: "Workspace not found.",
- });
- } else if (pendingInvites.expires < new Date()) {
- throw new DubApiError({
- code: "invite_expired",
- message: "Workspace invite expired.",
- });
- } else {
- throw new DubApiError({
- code: "invite_pending",
- message: "Workspace invite pending.",
- });
- }
- }
-
- // workspace role checks
- if (
- !requiredRole.includes(workspace.users[0].role) &&
- !(allowSelf && searchParams.userId === session.user.id)
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: "Unauthorized: Insufficient permissions.",
- });
- }
-
- // clicks usage overage checks
- if (needNotExceededClicks && workspace.usage > workspace.usageLimit) {
- throw new DubApiError({
- code: "forbidden",
- message: exceededLimitError({
- plan: workspace.plan,
- limit: workspace.usageLimit,
- type: "clicks",
- }),
- });
- }
-
- // links usage overage checks
- if (
- needNotExceededLinks &&
- workspace.linksUsage > workspace.linksLimit &&
- (workspace.plan === "free" || workspace.plan === "pro")
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: exceededLimitError({
- plan: workspace.plan,
- limit: workspace.linksLimit,
- type: "links",
- }),
- });
- }
-
- // plan checks
- if (!requiredPlan.includes(workspace.plan)) {
- throw new DubApiError({
- code: "forbidden",
- message: "Unauthorized: Need higher plan.",
- });
- }
-
- // analytics API checks
- const url = new URL(req.url || "", API_DOMAIN);
- if (
- workspace.plan === "free" &&
- apiKey &&
- url.pathname.includes("/analytics")
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: "Analytics API is only available on paid plans.",
- });
- }
-
- // link checks (if linkId or domain and key are provided)
- if ((linkId || (domain && key && key !== "_root")) && !skipLinkChecks) {
- // special case for getting domain by ID
- // TODO: refactor domains to use the same logic as links
- if (!link && searchParams.checkDomain === "true") {
- const domain = await prisma.domain.findUnique({
- where: {
- id: linkId,
- },
- });
- if (domain) {
- link = {
- ...domain,
- domain: domain.slug,
- key: "_root",
- url: domain.target || "",
- } as unknown as LinkProps;
- }
- }
-
- // 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: params || {},
- searchParams,
- headers,
- session,
- workspace,
- domain,
- link,
- });
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
- };
-};
-
-interface WithSessionHandler {
- ({
- req,
- params,
- searchParams,
- session,
- }: {
- req: Request;
- params: Record<string, string>;
- searchParams: Record<string, string>;
- session: Session;
- }): Promise<Response>;
-}
-
-export const withSession =
- (handler: WithSessionHandler) =>
- async (req: Request, { params }: { params: Record<string, string> }) => {
- try {
- let session: Session | undefined;
- let headers = {};
-
- const authorizationHeader = req.headers.get("Authorization");
- if (authorizationHeader) {
- if (!authorizationHeader.includes("Bearer ")) {
- throw new DubApiError({
- code: "bad_request",
- message:
- "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
- });
- }
- const apiKey = authorizationHeader.replace("Bearer ", "");
-
- const hashedKey = hashToken(apiKey, {
- noSecret: true,
- });
-
- const user = await prisma.user.findFirst({
- where: {
- tokens: {
- some: {
- hashedKey,
- },
- },
- },
- select: {
- id: true,
- name: true,
- email: true,
- },
- });
- if (!user) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Invalid API key.",
- });
- }
-
- const { success, limit, reset, remaining } = await ratelimit(
- 10,
- "1 s",
- ).limit(apiKey);
-
- headers = {
- "Retry-After": reset.toString(),
- "X-RateLimit-Limit": limit.toString(),
- "X-RateLimit-Remaining": remaining.toString(),
- "X-RateLimit-Reset": reset.toString(),
- };
-
- if (!success) {
- return new Response("Too many requests.", {
- status: 429,
- headers,
- });
- }
- await prisma.token.update({
- where: {
- hashedKey,
- },
- data: {
- lastUsed: new Date(),
- },
- });
- session = {
- user: {
- id: user.id,
- name: user.name || "",
- email: user.email || "",
- },
- };
- } else {
- session = await getSession();
- if (!session?.user.id) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Login required.",
- });
- }
- }
-
- const searchParams = getSearchParams(req.url);
- return await handler({ req, params, searchParams, session });
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
- };
-
-// Internal use only (for admin portal)
-interface WithAdminHandler {
- ({
- req,
- params,
- searchParams,
- }: {
- req: Request;
- params: Record<string, string>;
- searchParams: Record<string, string>;
- }): Promise<Response>;
-}
-
-export const withAdmin =
- (handler: WithAdminHandler) =>
- async (req: Request, { params }: { params: Record<string, string> }) => {
- const session = await getSession();
- if (!session?.user) {
- return new Response("Unauthorized: Login required.", { status: 401 });
- }
-
- const response = await prisma.projectUsers.findUnique({
- where: {
- userId_projectId: {
- userId: session.user.id,
- projectId: DUB_WORKSPACE_ID,
- },
- },
- });
- if (!response) {
- return new Response("Unauthorized: Not an admin.", { status: 401 });
- }
-
- const searchParams = getSearchParams(req.url);
- return handler({ req, params, searchParams });
- };
+export * from "./admin";
+export * from "./options";
+export * from "./session";
+export * from "./utils";
+export * from "./workspace";
diff --git a/apps/web/lib/auth/session.ts b/apps/web/lib/auth/session.ts
new file mode 100644
index 0000000000..b5da093f19
--- /dev/null
+++ b/apps/web/lib/auth/session.ts
@@ -0,0 +1,112 @@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import prisma from "@/lib/prisma";
+import { getSearchParams } from "@dub/utils";
+import { ratelimit } from "../upstash";
+import { Session, getSession, hashToken } from "./utils";
+
+interface WithSessionHandler {
+ ({
+ req,
+ params,
+ searchParams,
+ session,
+ }: {
+ req: Request;
+ params: Record<string, string>;
+ searchParams: Record<string, string>;
+ session: Session;
+ }): Promise<Response>;
+}
+
+export const withSession =
+ (handler: WithSessionHandler) =>
+ async (req: Request, { params }: { params: Record<string, string> }) => {
+ try {
+ let session: Session | undefined;
+ let headers = {};
+
+ const authorizationHeader = req.headers.get("Authorization");
+ if (authorizationHeader) {
+ if (!authorizationHeader.includes("Bearer ")) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
+ });
+ }
+ const apiKey = authorizationHeader.replace("Bearer ", "");
+
+ const hashedKey = hashToken(apiKey, {
+ noSecret: true,
+ });
+
+ const user = await prisma.user.findFirst({
+ where: {
+ tokens: {
+ some: {
+ hashedKey,
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ });
+ if (!user) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Invalid API key.",
+ });
+ }
+
+ const { success, limit, reset, remaining } = await ratelimit(
+ 10,
+ "1 s",
+ ).limit(apiKey);
+
+ headers = {
+ "Retry-After": reset.toString(),
+ "X-RateLimit-Limit": limit.toString(),
+ "X-RateLimit-Remaining": remaining.toString(),
+ "X-RateLimit-Reset": reset.toString(),
+ };
+
+ if (!success) {
+ return new Response("Too many requests.", {
+ status: 429,
+ headers,
+ });
+ }
+ await prisma.token.update({
+ where: {
+ hashedKey,
+ },
+ data: {
+ lastUsed: new Date(),
+ },
+ });
+ session = {
+ user: {
+ id: user.id,
+ name: user.name || "",
+ email: user.email || "",
+ },
+ };
+ } else {
+ session = await getSession();
+ if (!session?.user.id) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Login required.",
+ });
+ }
+ }
+
+ const searchParams = getSearchParams(req.url);
+ return await handler({ req, params, searchParams, session });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+ };
diff --git a/apps/web/lib/auth/utils.ts b/apps/web/lib/auth/utils.ts
new file mode 100644
index 0000000000..215fef07fd
--- /dev/null
+++ b/apps/web/lib/auth/utils.ts
@@ -0,0 +1,29 @@
+import { createHash } from "crypto";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "./options";
+
+export interface Session {
+ user: {
+ email: string;
+ id: string;
+ name: string;
+ image?: string;
+ };
+}
+
+export const getSession = async () => {
+ return getServerSession(authOptions) as Promise<Session>;
+};
+
+export const hashToken = (
+ token: string,
+ {
+ noSecret = false,
+ }: {
+ noSecret?: boolean;
+ } = {},
+) => {
+ return createHash("sha256")
+ .update(`${token}${noSecret ? "" : process.env.NEXTAUTH_SECRET}`)
+ .digest("hex");
+};
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
new file mode 100644
index 0000000000..ee6be14a87
--- /dev/null
+++ b/apps/web/lib/auth/workspace.ts
@@ -0,0 +1,422 @@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import prisma from "@/lib/prisma";
+import {
+ API_DOMAIN,
+ DUB_WORKSPACE_ID,
+ getSearchParams,
+ isDubDomain,
+} from "@dub/utils";
+import { Link as LinkProps } from "@prisma/client";
+import { exceededLimitError } from "../api/errors";
+import { PlanProps, WorkspaceProps } from "../types";
+import { ratelimit } from "../upstash";
+import { Session, getSession, hashToken } from "./utils";
+
+interface WithWorkspaceHandler {
+ ({
+ req,
+ params,
+ searchParams,
+ headers,
+ session,
+ workspace,
+ domain,
+ link,
+ }: {
+ req: Request;
+ params: Record<string, string>;
+ searchParams: Record<string, string>;
+ headers?: Record<string, string>;
+ session: Session;
+ workspace: WorkspaceProps;
+ domain: string;
+ link?: LinkProps;
+ }): Promise<Response>;
+}
+
+export const withWorkspace = (
+ handler: WithWorkspaceHandler,
+ {
+ requiredPlan = [
+ "free",
+ "pro",
+ "business",
+ "business plus",
+ "business max",
+ "business extra",
+ "enterprise",
+ ], // if the action needs a specific plan
+ requiredRole = ["owner", "member"],
+ needNotExceededClicks, // if the action needs the user to not have exceeded their clicks usage
+ 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,
+ }: {
+ requiredPlan?: Array<PlanProps>;
+ requiredRole?: Array<"owner" | "member">;
+ needNotExceededClicks?: boolean;
+ needNotExceededLinks?: boolean;
+ allowAnonymous?: boolean;
+ allowSelf?: boolean;
+ skipLinkChecks?: boolean;
+ domainChecks?: boolean;
+ } = {},
+) => {
+ return async (
+ req: Request,
+ { params }: { params: Record<string, string> | undefined },
+ ) => {
+ const searchParams = getSearchParams(req.url);
+ const { linkId } = params || {};
+
+ let apiKey: string | undefined = undefined;
+
+ try {
+ const authorizationHeader = req.headers.get("Authorization");
+ if (authorizationHeader) {
+ if (!authorizationHeader.includes("Bearer ")) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
+ });
+ }
+ apiKey = authorizationHeader.replace("Bearer ", "");
+ }
+
+ const domain = params?.domain || searchParams.domain;
+ const key = searchParams.key;
+
+ let session: Session | undefined;
+ let headers = {};
+ let id: string | undefined;
+ let slug: string | undefined;
+
+ const idOrSlug =
+ params?.idOrSlug ||
+ searchParams.workspaceId ||
+ params?.slug ||
+ searchParams.projectSlug;
+
+ // if there's no workspace ID or slug
+ if (!idOrSlug) {
+ // for /api/links (POST /api/links) – allow no session (but warn if user provides apiKey)
+ if (allowAnonymous && !apiKey) {
+ // @ts-expect-error
+ return await handler({
+ req,
+ params: params || {},
+ searchParams,
+ headers,
+ });
+ } else {
+ throw new DubApiError({
+ code: "not_found",
+ message:
+ "Workspace id not found. Did you forget to include a `workspaceId` query parameter? Learn more: https://d.to/id",
+ });
+ }
+ }
+
+ if (idOrSlug.startsWith("ws_")) {
+ id = idOrSlug.replace("ws_", "");
+ } else {
+ slug = idOrSlug;
+ }
+
+ if (apiKey) {
+ const hashedKey = hashToken(apiKey, {
+ noSecret: true,
+ });
+
+ const user = await prisma.user.findFirst({
+ where: {
+ tokens: {
+ some: {
+ hashedKey,
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ });
+ if (!user) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Invalid API key.",
+ });
+ }
+
+ const { success, limit, reset, remaining } = await ratelimit(
+ 10,
+ "1 s",
+ ).limit(apiKey);
+
+ headers = {
+ "Retry-After": reset.toString(),
+ "X-RateLimit-Limit": limit.toString(),
+ "X-RateLimit-Remaining": remaining.toString(),
+ "X-RateLimit-Reset": reset.toString(),
+ };
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Too many requests.",
+ });
+ }
+ await prisma.token.update({
+ where: {
+ hashedKey,
+ },
+ data: {
+ lastUsed: new Date(),
+ },
+ });
+ session = {
+ user: {
+ id: user.id,
+ name: user.name || "",
+ email: user.email || "",
+ },
+ };
+ } else {
+ session = await getSession();
+ if (!session?.user?.id) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Login required.",
+ });
+ }
+ }
+
+ let [workspace, link] = (await Promise.all([
+ prisma.project.findUnique({
+ where: {
+ id: id || undefined,
+ slug: slug || undefined,
+ },
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ logo: true,
+ usage: true,
+ usageLimit: true,
+ linksUsage: true,
+ linksLimit: true,
+ domainsLimit: true,
+ tagsLimit: true,
+ usersLimit: true,
+ plan: true,
+ stripeId: true,
+ billingCycleStart: true,
+ createdAt: true,
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ role: true,
+ },
+ },
+ domains: {
+ select: {
+ slug: true,
+ primary: true,
+ },
+ },
+ inviteCode: true,
+ },
+ }),
+ linkId
+ ? prisma.link.findUnique({
+ where: {
+ id: linkId,
+ },
+ })
+ : domain &&
+ key &&
+ (key === "_root"
+ ? prisma.domain.findUnique({
+ where: {
+ slug: domain,
+ },
+ })
+ : prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain,
+ key,
+ },
+ },
+ })),
+ ])) as [WorkspaceProps, LinkProps | undefined];
+
+ if (!workspace || !workspace.users) {
+ // workspace doesn't exist
+ throw new DubApiError({
+ code: "not_found",
+ message: "Workspace not found.",
+ });
+ }
+
+ // 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({
+ where: {
+ email_projectId: {
+ email: session.user.email,
+ projectId: workspace.id,
+ },
+ },
+ select: {
+ expires: true,
+ },
+ });
+ if (!pendingInvites) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Workspace not found.",
+ });
+ } else if (pendingInvites.expires < new Date()) {
+ throw new DubApiError({
+ code: "invite_expired",
+ message: "Workspace invite expired.",
+ });
+ } else {
+ throw new DubApiError({
+ code: "invite_pending",
+ message: "Workspace invite pending.",
+ });
+ }
+ }
+
+ // workspace role checks
+ if (
+ !requiredRole.includes(workspace.users[0].role) &&
+ !(allowSelf && searchParams.userId === session.user.id)
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Unauthorized: Insufficient permissions.",
+ });
+ }
+
+ // clicks usage overage checks
+ if (needNotExceededClicks && workspace.usage > workspace.usageLimit) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.usageLimit,
+ type: "clicks",
+ }),
+ });
+ }
+
+ // links usage overage checks
+ if (
+ needNotExceededLinks &&
+ workspace.linksUsage > workspace.linksLimit &&
+ (workspace.plan === "free" || workspace.plan === "pro")
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.linksLimit,
+ type: "links",
+ }),
+ });
+ }
+
+ // plan checks
+ if (!requiredPlan.includes(workspace.plan)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Unauthorized: Need higher plan.",
+ });
+ }
+
+ // analytics API checks
+ const url = new URL(req.url || "", API_DOMAIN);
+ if (
+ workspace.plan === "free" &&
+ apiKey &&
+ url.pathname.includes("/analytics")
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Analytics API is only available on paid plans.",
+ });
+ }
+
+ // link checks (if linkId or domain and key are provided)
+ if ((linkId || (domain && key && key !== "_root")) && !skipLinkChecks) {
+ // special case for getting domain by ID
+ // TODO: refactor domains to use the same logic as links
+ if (!link && searchParams.checkDomain === "true") {
+ const domain = await prisma.domain.findUnique({
+ where: {
+ id: linkId,
+ },
+ });
+ if (domain) {
+ link = {
+ ...domain,
+ domain: domain.slug,
+ key: "_root",
+ url: domain.target || "",
+ } as unknown as LinkProps;
+ }
+ }
+
+ // 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: params || {},
+ searchParams,
+ headers,
+ session,
+ workspace,
+ domain,
+ link,
+ });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+ };
+};