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.

moved API routes to app router

Steven Teyf980147460e4
diff --git a/apps/web/app/api/domains/[domain]/exists/route.ts b/apps/web/app/api/domains/[domain]/exists/route.ts
new file mode 100644
index 0000000000..41d0913a2d
--- /dev/null
+++ b/apps/web/app/api/domains/[domain]/exists/route.ts
@@ -0,0 +1,17 @@
+import { withSession } from "@/lib/auth";
+import { domainExists } from "@/lib/api/domains";
+import { NextResponse } from "next/server";
+
+// GET /api/domains/[domain]/exists – check if a domain exists
+export const GET = withSession(async ({ params }) => {
+ const { domain } = params;
+
+ // This is used for project creation only, if you add a domain within an existing project,
+ // use the /api/projects/[slug]/domains/[domain]/exists endpoint instead
+ const exists = await domainExists(domain);
+ if (exists) {
+ return NextResponse.json(1);
+ } else {
+ return NextResponse.json(0);
+ }
+});
diff --git a/apps/web/app/api/edge/stats/[endpoint]/route.ts b/apps/web/app/api/edge/stats/[endpoint]/route.ts
index b628fa4aef..f53810915e 100644
--- a/apps/web/app/api/edge/stats/[endpoint]/route.ts
+++ b/apps/web/app/api/edge/stats/[endpoint]/route.ts
@@ -1,4 +1,4 @@
-import { getSearchParams } from "@/lib/auth-app";
+import { getSearchParams } from "@/lib/auth";
import { isBlacklistedReferrer } from "@/lib/edge-config";
import { getLinkViaEdge } from "@/lib/planetscale";
import { getStats } from "@/lib/stats";
diff --git a/apps/web/app/api/projects/[slug]/billing/manage/route.ts b/apps/web/app/api/projects/[slug]/billing/manage/route.ts
new file mode 100644
index 0000000000..4d33564b17
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/billing/manage/route.ts
@@ -0,0 +1,16 @@
+import { withAuth } from "@/lib/auth";
+import { stripe } from "@/lib/stripe";
+import { APP_DOMAIN } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// POST /api/projects/[slug]/billing/manage - create a Stripe billing portal session
+export const POST = withAuth(async ({ project }) => {
+ if (!project.stripeId) {
+ return new Response("No Stripe customer ID", { status: 400 });
+ }
+ const { url } = await stripe.billingPortal.sessions.create({
+ customer: project.stripeId,
+ return_url: `${APP_DOMAIN}/${project.slug}/settings/billing`,
+ });
+ return NextResponse.json(url);
+});
diff --git a/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts b/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts
new file mode 100644
index 0000000000..4924ac5d86
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts
@@ -0,0 +1,30 @@
+import { withAuth } from "@/lib/auth";
+import { stripe } from "@/lib/stripe";
+import { APP_DOMAIN } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+export const POST = withAuth(async ({ searchParams, project, session }) => {
+ const { priceId } = searchParams;
+
+ if (!priceId) {
+ return new Response("Missing price ID", { status: 400 });
+ }
+
+ const stripeSession = await stripe.checkout.sessions.create({
+ customer_email: session.user.email,
+ billing_address_collection: "required",
+ success_url: `${APP_DOMAIN}/${project.slug}/settings/billing?success=true`,
+ cancel_url: `${APP_DOMAIN}/${project.slug}/settings/billing`,
+ line_items: [{ price: priceId, quantity: 1 }],
+ automatic_tax: {
+ enabled: true,
+ },
+ tax_id_collection: {
+ enabled: true,
+ },
+ mode: "subscription",
+ allow_promotion_codes: true,
+ client_reference_id: project.id,
+ });
+ return NextResponse.json(stripeSession);
+});
diff --git a/apps/web/app/api/projects/[slug]/domains/[domain]/exists/route.ts b/apps/web/app/api/projects/[slug]/domains/[domain]/exists/route.ts
new file mode 100644
index 0000000000..0db04c8ef4
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/domains/[domain]/exists/route.ts
@@ -0,0 +1,13 @@
+import { withAuth } from "@/lib/auth";
+import { domainExists } from "@/lib/api/domains";
+import { NextResponse } from "next/server";
+
+// GET /api/projects/[slug]/domains/[domain]/exists – check if a domain exists
+export const GET = withAuth(async ({ domain, project }) => {
+ const exists = await domainExists(domain);
+ if (exists) {
+ return NextResponse.json(1);
+ } else {
+ return NextResponse.json(0);
+ }
+});
diff --git a/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts b/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts
new file mode 100644
index 0000000000..502e273a11
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts
@@ -0,0 +1,105 @@
+import { withAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { redis } from "@/lib/upstash";
+import {
+ addDomainToVercel,
+ changeDomainForImages,
+ changeDomainForLinks,
+ deleteDomainAndLinks,
+ removeDomainFromVercel,
+ setRootDomain,
+ validateDomain,
+} from "@/lib/api/domains";
+import { NextResponse } from "next/server";
+
+// PUT /api/projects/[slug]/domains/[domain] – edit a project's domain
+export const PUT = withAuth(async ({ req, project, domain }) => {
+ const { slug: newDomain, target, type, primary } = await req.json();
+
+ const validDomain = await validateDomain(newDomain);
+ if (validDomain !== true) {
+ return new Response(validDomain, { status: 422 });
+ }
+
+ if (newDomain !== domain) {
+ const vercelResponse = await addDomainToVercel(newDomain);
+ if (vercelResponse.error) {
+ return new Response(vercelResponse.error.message, { status: 422 });
+ }
+ }
+
+ const response = await Promise.allSettled([
+ // if the domain is being changed, we need to:
+ // 1. Remove the old domain from Vercel
+ // 2. Add the new domain to Vercel
+ // 3. Update all links in the project to point to the new domain
+ // 4. Update all images in the project to point to the new domain
+ ...(newDomain !== domain
+ ? [
+ removeDomainFromVercel(domain),
+ changeDomainForLinks(domain, newDomain),
+ changeDomainForImages(domain, newDomain),
+ ]
+ : []),
+ /*
+ if the project is not a free plan:
+ - if the domain is being set:
+ - Set the root domain to the target in Redis
+ - if the domain is being changed, also change the root domain key in Redis
+ - if the domain is being unset:
+ - delete the root domain key in Redis
+ */
+ project.plan !== "free" &&
+ (target
+ ? setRootDomain({
+ domain,
+ target,
+ rewrite: type === "rewrite",
+ ...(newDomain !== domain && {
+ newDomain,
+ }),
+ })
+ : redis.del(`root:${domain}`)),
+ // if the domain is being set as the primary domain, set the current primary domain to false
+ primary &&
+ prisma.domain.updateMany({
+ where: {
+ projectId: project.id,
+ primary: true,
+ },
+ data: {
+ primary: false,
+ },
+ }),
+ // Update the domain in the database along with its primary status
+ prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ ...(newDomain !== domain && {
+ slug: newDomain,
+ }),
+ // same logic as the redis part above
+ ...(project.plan !== "free" &&
+ (target
+ ? {
+ target,
+ }
+ : {
+ target: null,
+ })),
+ type,
+ primary,
+ },
+ }),
+ ]);
+
+ return NextResponse.json(response);
+});
+
+// DELETE /api/projects/[slug]/domains/[domain] - delete a project's domain
+export const DELETE = withAuth(async ({ domain }) => {
+ const response = await deleteDomainAndLinks(domain);
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/projects/[slug]/domains/[domain]/verify/route.ts b/apps/web/app/api/projects/[slug]/domains/[domain]/verify/route.ts
new file mode 100644
index 0000000000..6202750d3e
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/domains/[domain]/verify/route.ts
@@ -0,0 +1,85 @@
+import { withAuth } from "@/lib/auth";
+import {
+ getConfigResponse,
+ getDomainResponse,
+ verifyDomain,
+} from "@/lib/api/domains";
+import prisma from "@/lib/prisma";
+import { DomainVerificationStatusProps } from "@/lib/types";
+import { NextResponse } from "next/server";
+
+// GET /api/projects/[slug]/domains/[domain]/verify - get domain verification status
+export const GET = withAuth(async ({ domain }) => {
+ let status: DomainVerificationStatusProps = "Valid Configuration";
+
+ const [domainJson, configJson] = await Promise.all([
+ getDomainResponse(domain),
+ getConfigResponse(domain),
+ ]);
+
+ if (domainJson?.error?.code === "not_found") {
+ // domain not found on Vercel project
+ status = "Domain Not Found";
+ return NextResponse.json({ status, response: { configJson, domainJson } });
+ } else if (domainJson.error) {
+ status = "Unknown Error";
+ return NextResponse.json({ status, response: { configJson, domainJson } });
+ }
+
+ /**
+ * Domain has DNS conflicts
+ */
+ if (configJson?.conflicts.length > 0) {
+ status = "Conflicting DNS Records";
+ return NextResponse.json({ status, response: { configJson, domainJson } });
+ }
+
+ /**
+ * If domain is not verified, we try to verify now
+ */
+ if (!domainJson.verified) {
+ status = "Pending Verification";
+ const verificationJson = await verifyDomain(domain);
+
+ if (verificationJson && verificationJson.verified) {
+ /**
+ * Domain was just verified
+ */
+ status = "Valid Configuration";
+ }
+
+ return NextResponse.json({
+ status,
+ response: { configJson, domainJson, verificationJson },
+ });
+ }
+
+ let prismaResponse: any = null;
+ if (!configJson.misconfigured) {
+ prismaResponse = await prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ verified: true,
+ lastChecked: new Date(),
+ },
+ });
+ } else {
+ status = "Invalid Configuration";
+ prismaResponse = await prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ verified: false,
+ lastChecked: new Date(),
+ },
+ });
+ }
+
+ return NextResponse.json({
+ status,
+ response: { configJson, domainJson, prismaResponse },
+ });
+});
diff --git a/apps/web/app/api/projects/[slug]/domains/route.ts b/apps/web/app/api/projects/[slug]/domains/route.ts
new file mode 100644
index 0000000000..fa079deb55
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/domains/route.ts
@@ -0,0 +1,74 @@
+import { withAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { NextResponse } from "next/server";
+import {
+ addDomainToVercel,
+ setRootDomain,
+ validateDomain,
+} from "@/lib/api/domains";
+
+// GET /api/projects/[slug]/domains – get all domains for a project
+export const GET = withAuth(async ({ project }) => {
+ const domains = await prisma.domain.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ slug: true,
+ verified: true,
+ primary: true,
+ target: true,
+ type: true,
+ },
+ });
+ return NextResponse.json(domains);
+});
+
+// POST /api/projects/[slug]/domains - add a domain
+export const POST = withAuth(async ({ req, project }) => {
+ const { slug: domain, primary, target, type } = await req.json();
+ const validDomain = await validateDomain(domain);
+ if (validDomain !== true) {
+ return new Response(validDomain, { status: 422 });
+ }
+ const vercelResponse = await addDomainToVercel(domain);
+ if (vercelResponse.error) {
+ return new Response(vercelResponse.error.message, { status: 422 });
+ }
+ /*
+ If the domain is being added, we need to:
+ 1. Add the domain to Vercel
+ 2. If there's a landing page set, update the root domain in Redis
+ 3. If the domain is being set as the primary domain, set all other domains to not be the primary domain
+ 4. Add the domain to the database along with its primary status
+ */
+ const response = await Promise.allSettled([
+ target &&
+ setRootDomain({
+ domain,
+ target,
+ rewrite: type === "rewrite",
+ }),
+ primary &&
+ prisma.domain.updateMany({
+ where: {
+ projectId: project.id,
+ primary: true,
+ },
+ data: {
+ primary: false,
+ },
+ }),
+ prisma.domain.create({
+ data: {
+ slug: domain,
+ target,
+ type,
+ projectId: project.id,
+ primary,
+ },
+ }),
+ ]);
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/projects/[slug]/exists/route.ts b/apps/web/app/api/projects/[slug]/exists/route.ts
new file mode 100644
index 0000000000..e60db6355b
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/exists/route.ts
@@ -0,0 +1,26 @@
+import { withSession } from "@/lib/auth";
+import { isReservedKey } from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { DEFAULT_REDIRECTS } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// GET /api/projects/[slug]/exists – check if a project exists
+export const GET = withSession(async ({ params }) => {
+ const { slug } = params;
+ if ((await isReservedKey(slug)) || DEFAULT_REDIRECTS[slug]) {
+ return NextResponse.json(1);
+ }
+ const project = await prisma.project.findUnique({
+ where: {
+ slug,
+ },
+ select: {
+ slug: true,
+ },
+ });
+ if (project) {
+ return NextResponse.json(1);
+ } else {
+ return NextResponse.json(0);
+ }
+});
diff --git a/apps/web/app/api/projects/[slug]/import/bitly/route.ts b/apps/web/app/api/projects/[slug]/import/bitly/route.ts
new file mode 100644
index 0000000000..dc4d85c24f
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/import/bitly/route.ts
@@ -0,0 +1,108 @@
+import { addDomainToVercel } from "@/lib/api/domains";
+import { withAuth } from "@/lib/auth";
+import { qstash } from "@/lib/cron";
+import prisma from "@/lib/prisma";
+import { BitlyGroupProps } from "@/lib/types";
+import { redis } from "@/lib/upstash";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// GET /api/projects/[slug]/import/bitly – get all bitly groups for a project
+export const GET = withAuth(async ({ project }) => {
+ const accessToken = await redis.get(`import:bitly:${project.id}`);
+ if (!accessToken) {
+ return new Response("No Bitly access token found", { status: 400 });
+ }
+ const response = await fetch(`https://api-ssl.bitly.com/v4/groups`, {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${accessToken}`,
+ },
+ });
+ const data = await response.json();
+ if (data.message === "FORBIDDEN") {
+ return new Response("Invalid Bitly access token", { status: 403 });
+ }
+
+ const groups = data.groups
+ // filter for active groups only
+ .filter(({ is_active }) => is_active) as BitlyGroupProps[];
+
+ const groupsWithTags = await Promise.all(
+ groups.map(async (group) => ({
+ ...group,
+ tags: await fetch(
+ `https://api-ssl.bitly.com/v4/groups/${group.guid}/tags`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${accessToken}`,
+ },
+ },
+ )
+ .then((r) => r.json())
+ .then((r) => r.tags),
+ })),
+ );
+
+ return NextResponse.json(groupsWithTags);
+});
+
+// POST /api/projects/[slug]/import/bitly - create job to import links from bitly
+export const POST = withAuth(async ({ req, project }) => {
+ const { selectedDomains, selectedGroupTags } = await req.json();
+
+ // check if there are domains that are not in the project
+ // if yes, add them to the project
+ const domainsNotInProject = selectedDomains.filter(
+ ({ domain }) => !project.domains?.find((d) => d.slug === domain),
+ );
+ if (domainsNotInProject.length > 0) {
+ await Promise.allSettled([
+ prisma.domain.createMany({
+ data: domainsNotInProject.map(({ domain }) => ({
+ slug: domain,
+ target: null,
+ type: "redirect",
+ projectId: project.id,
+ primary: false,
+ })),
+ skipDuplicates: true,
+ }),
+ domainsNotInProject.map(({ slug }) => addDomainToVercel(slug)),
+ ]);
+ }
+
+ // convert data to array of groups with their respective domains
+ const groups = selectedDomains.reduce((result, { domain, bitlyGroup }) => {
+ const existingGroup = result.find((item) => item.bitlyGroup === bitlyGroup);
+ if (existingGroup) {
+ existingGroup.domains.push(domain);
+ } else {
+ result.push({
+ bitlyGroup,
+ domains: [domain],
+ keepTags: selectedGroupTags.includes(bitlyGroup),
+ });
+ }
+ return result;
+ }, []);
+
+ const response = await Promise.all(
+ groups
+ // only add groups that have at least 1 domain selected for import
+ .filter(({ domains }) => domains.length > 0)
+ .map(({ bitlyGroup, domains, keepTags }) =>
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/bitly`,
+ body: {
+ projectId: project.id,
+ bitlyGroup,
+ domains,
+ keepTags,
+ },
+ }),
+ ),
+ );
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/projects/[slug]/import/short/route.ts b/apps/web/app/api/projects/[slug]/import/short/route.ts
new file mode 100644
index 0000000000..096033c41e
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/import/short/route.ts
@@ -0,0 +1,95 @@
+import { addDomainToVercel } from "@/lib/api/domains";
+import { withAuth } from "@/lib/auth";
+import { qstash } from "@/lib/cron";
+import prisma from "@/lib/prisma";
+import { ShortioDomainProps } from "@/lib/types";
+import { redis } from "@/lib/upstash";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// GET /api/projects/[slug]/import/short – get all short.io domains for a project
+export const GET = withAuth(async ({ project }) => {
+ const accessToken = await redis.get(`import:short:${project.id}`);
+ if (!accessToken) {
+ return new Response("No Short.io access token found", { status: 400 });
+ }
+
+ const response = await fetch(`https://api.short.io/api/domains`, {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: accessToken as string,
+ },
+ });
+ const data = await response.json();
+ if (data.error === "Unauthorized") {
+ return new Response("Invalid Short.io access token", { status: 403 });
+ }
+
+ const domains = await Promise.all(
+ data.map(async ({ id, hostname }: { id: number; hostname: string }) => ({
+ id,
+ domain: hostname,
+ links: await fetch(
+ `https://api-v2.short.cm/statistics/domain/${id}?period=total`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: accessToken as string,
+ },
+ },
+ )
+ .then((r) => r.json())
+ .then((data) => data.links - 1) // subtract 1 to exclude root domain
+ .catch((e) => 0),
+ })),
+ );
+
+ return NextResponse.json(domains);
+});
+
+// PUT /api/projects/[slug]/import/short - save Short.io API key
+export const PUT = withAuth(async ({ req, project }) => {
+ const { apiKey } = await req.json();
+ const response = await redis.set(`import:short:${project.id}`, apiKey);
+ return NextResponse.json(response);
+});
+
+// POST /api/projects/[slug]/import/short - create job to import links from Short.io
+export const POST = withAuth(async ({ req, project }) => {
+ const { selectedDomains } = await req.json();
+
+ // check if there are domains that are not in the project
+ // if yes, add them to the project
+ const domainsNotInProject = selectedDomains.filter(
+ ({ domain }) => !project.domains?.find((d) => d.slug === domain),
+ );
+ if (domainsNotInProject.length > 0) {
+ await Promise.allSettled([
+ prisma.domain.createMany({
+ data: domainsNotInProject.map(({ domain }) => ({
+ slug: domain,
+ target: null,
+ type: "redirect",
+ projectId: project.id,
+ primary: false,
+ })),
+ skipDuplicates: true,
+ }),
+ domainsNotInProject.map(({ domain }) => addDomainToVercel(domain)),
+ ]);
+ }
+
+ const response = await Promise.all(
+ selectedDomains.map(({ id, domain }) =>
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/short`,
+ body: {
+ projectId: project.id,
+ domainId: id,
+ domain,
+ },
+ }),
+ ),
+ );
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/projects/[slug]/invites/accept/route.ts b/apps/web/app/api/projects/[slug]/invites/accept/route.ts
new file mode 100644
index 0000000000..8096af7927
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/invites/accept/route.ts
@@ -0,0 +1,43 @@
+import { withSession } from "@/lib/auth";
+import { NextResponse } from "next/server";
+import prisma from "@/lib/prisma";
+
+// POST /api/projects/[slug]/invites/accept – accept a project invite
+export const POST = withSession(async ({ session, params }) => {
+ const invite = await prisma.projectInvite.findFirst({
+ where: {
+ email: session.user.email,
+ project: {
+ slug: params.slug,
+ },
+ },
+ select: {
+ expires: true,
+ projectId: true,
+ },
+ });
+ if (!invite) {
+ return new Response("Invalid invite", { status: 404 });
+ } else if (invite.expires < new Date()) {
+ return new Response("Invite expired", { status: 410 });
+ } else {
+ const response = await Promise.all([
+ prisma.projectUsers.create({
+ data: {
+ userId: session.user.id,
+ role: "member",
+ projectId: invite.projectId,
+ },
+ }),
+ prisma.projectInvite.delete({
+ where: {
+ email_projectId: {
+ email: session.user.email,
+ projectId: invite.projectId,
+ },
+ },
+ }),
+ ]);
+ return NextResponse.json(response);
+ }
+});
diff --git a/apps/web/app/api/projects/[slug]/invites/route.tsx b/apps/web/app/api/projects/[slug]/invites/route.tsx
new file mode 100644
index 0000000000..efad5c7d73
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/invites/route.tsx
@@ -0,0 +1,99 @@
+import { withAuth } from "@/lib/auth";
+import { NextResponse } from "next/server";
+import { inviteUser } from "@/lib/api/users";
+import prisma from "@/lib/prisma";
+
+// GET /api/projects/[slug]/invites – get invites for a specific project
+export const GET = withAuth(async ({ project }) => {
+ const invites = await prisma.projectInvite.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ email: true,
+ createdAt: true,
+ },
+ });
+ return NextResponse.json(invites);
+});
+
+// POST /api/projects/[slug]/invites – invite a teammate
+export const POST = withAuth(
+ async ({ req, project, session }) => {
+ const { email } = await req.json();
+ const alreadyInTeam = await prisma.projectUsers.findFirst({
+ where: {
+ projectId: project.id,
+ user: {
+ email,
+ },
+ },
+ });
+ if (alreadyInTeam) {
+ return new Response("User already exists in this project.", {
+ status: 400,
+ });
+ }
+
+ if (project.plan === "free") {
+ const users = await prisma.projectUsers.count({
+ where: {
+ projectId: project.id,
+ },
+ });
+ const invites = await prisma.projectInvite.count({
+ where: {
+ projectId: project.id,
+ },
+ });
+ if (users + invites >= 3) {
+ return new Response(
+ "You've reached the maximum number of users for the free plan.",
+ {
+ status: 400,
+ },
+ );
+ }
+ }
+
+ try {
+ await inviteUser({
+ email,
+ project,
+ session,
+ });
+ return NextResponse.json({ message: "Invite sent" });
+ } catch (error) {
+ return new Response(error.message, {
+ status: 400,
+ });
+ }
+ },
+ {
+ requiredRole: ["owner"],
+ },
+);
+
+// DELETE /api/projects/[slug]/invites – delete a pending invite
+export const DELETE = withAuth(
+ async ({ searchParams, project }) => {
+ const { email } = searchParams;
+ if (!email) {
+ return new Response("Missing email", {
+ status: 400,
+ });
+ }
+ const response = await prisma.projectInvite.delete({
+ where: {
+ email_projectId: {
+ email,
+ projectId: project.id,
+ },
+ },
+ });
+ return NextResponse.json(response);
+ },
+ {
+ requiredRole: ["owner"],
+ },
+);
diff --git a/apps/web/app/api/projects/[slug]/logo/route.ts b/apps/web/app/api/projects/[slug]/logo/route.ts
new file mode 100644
index 0000000000..a2268e3c51
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/logo/route.ts
@@ -0,0 +1,28 @@
+import { withAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import cloudinary from "cloudinary";
+import { NextResponse } from "next/server";
+
+// POST /api/projects/[slug]/logo – upload a new project logo
+export const POST = withAuth(
+ async ({ req, project }) => {
+ const { image } = await req.json();
+
+ const { secure_url } = await cloudinary.v2.uploader.upload(image, {
+ public_id: project.id,
+ folder: "logos",
+ overwrite: true,
+ invalidate: true,
+ });
+
+ const response = await prisma.project.update({
+ where: { id: project.id },
+ data: { logo: secure_url },
+ });
+
+ return NextResponse.json(response);
+ },
+ {
+ requiredRole: ["owner"],
+ },
+);
diff --git a/apps/web/app/api/projects/[slug]/route.ts b/apps/web/app/api/projects/[slug]/route.ts
new file mode 100644
index 0000000000..294c105048
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/route.ts
@@ -0,0 +1,47 @@
+import { withAuth } from "@/lib/auth";
+import { NextResponse } from "next/server";
+import prisma from "@/lib/prisma";
+import { deleteProject } from "@/lib/api/project";
+
+// GET /api/projects/[slug] – get a specific project
+export const GET = withAuth(async ({ project }) => {
+ return NextResponse.json(project);
+});
+
+// PUT /api/projects/[slug] – update a specific project
+export const PUT = withAuth(
+ async ({ req, project }) => {
+ const { name, slug } = await req.json();
+ try {
+ const response = await prisma.project.update({
+ where: {
+ slug: project.slug,
+ },
+ data: {
+ ...(name && { name }),
+ ...(slug && { slug }),
+ },
+ });
+ return NextResponse.json(response);
+ } catch (error) {
+ if (error.code === "P2002") {
+ return new Response("Project slug already exists.", { status: 422 });
+ }
+ return new Response(error.message, { status: 500 });
+ }
+ },
+ {
+ requiredRole: ["owner"],
+ },
+);
+
+// DELETE /api/projects/[slug] – delete a specific project
+export const DELETE = withAuth(
+ async ({ project }) => {
+ const response = await deleteProject(project);
+ return NextResponse.json(response);
+ },
+ {
+ requiredRole: ["owner"],
+ },
+);
diff --git a/apps/web/app/api/projects/[slug]/saml/route.ts b/apps/web/app/api/projects/[slug]/saml/route.ts
new file mode 100644
index 0000000000..12b41df4a0
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/saml/route.ts
@@ -0,0 +1,70 @@
+import { withAuth } from "@/lib/auth";
+import { NextResponse } from "next/server";
+import jackson, { samlAudience } from "@/lib/jackson";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+
+// GET /api/projects/[slug]/saml – get SAML connections for a specific project
+export const GET = withAuth(async ({ project }) => {
+ const { apiController } = await jackson();
+
+ const connections = await apiController.getConnections({
+ tenant: project.id,
+ product: "Dub",
+ });
+
+ const response = {
+ connections,
+ issuer: samlAudience,
+ acs:
+ process.env.NODE_ENV === "production"
+ ? "https://api.dub.co/auth/saml/callback"
+ : `${APP_DOMAIN_WITH_NGROK}/api/auth/saml/callback`,
+ };
+
+ return NextResponse.json(response);
+});
+
+// POST /api/projects/[slug]/saml – create a new SAML connection
+export const POST = withAuth(
+ async ({ req, project }) => {
+ const { metadataUrl, encodedRawMetadata } = await req.json();
+
+ const { apiController } = await jackson();
+
+ const data = await apiController.createSAMLConnection({
+ encodedRawMetadata,
+ metadataUrl,
+ defaultRedirectUrl: `${process.env.NEXTAUTH_URL}/auth/saml`,
+ redirectUrl: process.env.NEXTAUTH_URL as string,
+ tenant: project.id,
+ product: "Dub",
+ });
+
+ return NextResponse.json(data);
+ },
+ {
+ requiredRole: ["owner"],
+ requiredPlan: ["enterprise"],
+ },
+);
+
+// DELETE /api/projects/[slug]/saml – delete all SAML connections
+
+export const DELETE = withAuth(
+ async ({ searchParams }) => {
+ const { clientID, clientSecret } = searchParams;
+
+ const { apiController } = await jackson();
+
+ await apiController.deleteConnections({
+ clientID,
+ clientSecret,
+ });
+
+ return NextResponse.json({ response: "removed SAML connection" });
+ },
+ {
+ requiredRole: ["owner"],
+ requiredPlan: ["enterprise"],
+ },
+);
diff --git a/apps/web/app/api/projects/[slug]/scim/route.ts b/apps/web/app/api/projects/[slug]/scim/route.ts
new file mode 100644
index 0000000000..6ebd95a086
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/scim/route.ts
@@ -0,0 +1,71 @@
+import { withAuth } from "@/lib/auth";
+import { NextResponse } from "next/server";
+import jackson from "@/lib/jackson";
+
+// GET /api/projects/[slug]/scim – get all SCIM directories
+export const GET = withAuth(async ({ project }) => {
+ const { directorySyncController } = await jackson();
+
+ const { data, error } =
+ await directorySyncController.directories.getByTenantAndProduct(
+ project.id,
+ "Dub",
+ );
+ if (error) {
+ return new Response(error.message, { status: 500 });
+ }
+
+ return NextResponse.json({
+ directories: data,
+ });
+});
+
+// POST /api/projects/[slug]/scim – create a new SCIM directory
+export const POST = withAuth(
+ async ({ req, project }) => {
+ const { provider = "okta-scim-v2", currentDirectoryId } = await req.json();
+
+ const { directorySyncController } = await jackson();
+
+ const [data, _] = await Promise.all([
+ directorySyncController.directories.create({
+ name: "Dub SCIM Directory",
+ tenant: project.id,
+ product: "Dub",
+ type: provider,
+ }),
+ currentDirectoryId &&
+ directorySyncController.directories.delete(currentDirectoryId),
+ ]);
+
+ return NextResponse.json(data);
+ },
+ {
+ requiredRole: ["owner"],
+ requiredPlan: ["enterprise"],
+ },
+);
+
+// DELETE /api/projects/[slug]/scim – delete a SCIM directory
+
+export const DELETE = withAuth(
+ async ({ searchParams }) => {
+ const { directoryId } = searchParams;
+
+ if (!directoryId) {
+ return new Response(`Missing SCIM directory ID`, { status: 400 });
+ }
+
+ const { directorySyncController } = await jackson();
+
+ const response = await directorySyncController.directories.delete(
+ directoryId,
+ );
+
+ return NextResponse.json(response);
+ },
+ {
+ requiredRole: ["owner"],
+ requiredPlan: ["enterprise"],
+ },
+);
diff --git a/apps/web/app/api/projects/[slug]/stats/[endpoint]/route.ts b/apps/web/app/api/projects/[slug]/stats/[endpoint]/route.ts
new file mode 100644
index 0000000000..33265a2e2a
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/stats/[endpoint]/route.ts
@@ -0,0 +1 @@
+export * from "../../../../stats/[endpoint]/route";
diff --git a/apps/web/app/api/projects/[slug]/stats/route.ts b/apps/web/app/api/projects/[slug]/stats/route.ts
new file mode 100644
index 0000000000..453e76454c
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/stats/route.ts
@@ -0,0 +1 @@
+export * from "../../../stats/route";
diff --git a/apps/web/app/api/projects/[slug]/tags/[id]/route.ts b/apps/web/app/api/projects/[slug]/tags/[id]/route.ts
new file mode 100644
index 0000000000..24d46c7545
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/tags/[id]/route.ts
@@ -0,0 +1,30 @@
+import { withAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { NextResponse } from "next/server";
+
+// PUT /api/projects/[slug]/tags/[id] – update a tag for a project
+export const PUT = withAuth(async ({ req, params, project }) => {
+ const { id } = params;
+ const { name, color } = await req.json();
+ const response = await prisma.tag.update({
+ where: {
+ id,
+ },
+ data: {
+ name,
+ color,
+ },
+ });
+ return NextResponse.json(response);
+});
+
+// DELETE /api/projects/[slug]/tags/[id] – delete a tag for a project
+export const DELETE = withAuth(async ({ params }) => {
+ const { id } = params;
+ const response = await prisma.tag.delete({
+ where: {
+ id,
+ },
+ });
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/projects/[slug]/tags/route.ts b/apps/web/app/api/projects/[slug]/tags/route.ts
new file mode 100644
index 0000000000..1fbacddd61
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/tags/route.ts
@@ -0,0 +1,48 @@
+import { withAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { randomBadgeColor } from "@/ui/links/tag-badge";
+import { NextResponse } from "next/server";
+
+// GET /api/projects/[slug]/tags - get all tags for a project
+export const GET = withAuth(async ({ project }) => {
+ const tags = await prisma.tag.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ orderBy: {
+ name: "asc",
+ },
+ });
+ return NextResponse.json(tags);
+});
+
+// POST /api/projects/[slug]/tags - create a tag for a project
+export const POST = withAuth(async ({ req, project }) => {
+ const tagsCount = await prisma.tag.count({
+ where: {
+ projectId: project.id,
+ },
+ });
+ if (project.plan === "free" && tagsCount >= 3) {
+ return new Response(
+ "You can only create 3 tags in the Free plan. Upgrade to Pro to create unlimited tags.",
+ {
+ status: 403,
+ },
+ );
+ }
+ const { tag } = await req.json();
+ const response = await prisma.tag.create({
+ data: {
+ name: tag,
+ color: randomBadgeColor(),
+ projectId: project.id,
+ },
+ });
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/projects/[slug]/users/route.ts b/apps/web/app/api/projects/[slug]/users/route.ts
new file mode 100644
index 0000000000..341a12e8aa
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/users/route.ts
@@ -0,0 +1,95 @@
+import { withAuth } from "@/lib/auth";
+import { NextResponse } from "next/server";
+import prisma from "@/lib/prisma";
+
+// GET /api/projects/[slug]/users – get users for a specific project
+export const GET = withAuth(async ({ project }) => {
+ const users = await prisma.projectUsers.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ role: true,
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
+ },
+ createdAt: true,
+ },
+ });
+ return NextResponse.json(
+ users.map((u) => ({
+ ...u.user,
+ role: u.role,
+ })),
+ );
+});
+
+// PUT /api/projects/[slug]/users – update a user's role for a specific project
+export const PUT = withAuth(
+ async ({ req, project }) => {
+ const { userId, role } = await req.json();
+ if (!userId || !role) {
+ return new Response("Missing userId or role", { status: 400 });
+ }
+ const response = await prisma.projectUsers.update({
+ where: {
+ userId_projectId: {
+ projectId: project.id,
+ userId,
+ },
+ },
+ data: {
+ role,
+ },
+ });
+ return NextResponse.json(response);
+ },
+ {
+ requiredRole: ["owner"],
+ },
+);
+
+// DELETE /api/projects/[slug]/users – remove a user from a project
+
+export const DELETE = withAuth(
+ async ({ searchParams, project }) => {
+ const { userId } = searchParams;
+ if (!userId) {
+ return new Response("Missing userId", { status: 400 });
+ }
+ const projectUser = await prisma.projectUsers.findUnique({
+ where: {
+ userId_projectId: {
+ projectId: project.id,
+ userId,
+ },
+ },
+ select: {
+ role: true,
+ },
+ });
+ if (projectUser?.role === "owner") {
+ return new Response(
+ "Cannot remove owner from project. Please transfer ownership to another user first.",
+ { status: 400 },
+ );
+ }
+ const response = await prisma.projectUsers.delete({
+ where: {
+ userId_projectId: {
+ projectId: project.id,
+ userId,
+ },
+ },
+ });
+ return NextResponse.json(response);
+ },
+ {
+ requiredRole: ["owner"],
+ },
+);
diff --git a/apps/web/app/api/projects/route.ts b/apps/web/app/api/projects/route.ts
index 0b83bb874d..dd297bf864 100644
--- a/apps/web/app/api/projects/route.ts
+++ b/apps/web/app/api/projects/route.ts
@@ -4,7 +4,7 @@ import {
domainExists,
validateDomain,
} from "@/lib/api/domains";
-import { withAuth } from "@/lib/auth-app";
+import { withAuth } from "@/lib/auth";
import { isReservedKey } from "@/lib/edge-config";
import prisma from "@/lib/prisma";
import { DEFAULT_REDIRECTS, validSlugRegex } from "@dub/utils";
diff --git a/apps/web/pages/api/scim/v2.0/[...directory].ts b/apps/web/app/api/scim/v2.0/[...directory]/route.ts
similarity index 74%
rename from apps/web/pages/api/scim/v2.0/[...directory].ts
rename to apps/web/app/api/scim/v2.0/[...directory]/route.ts
index c9a48f4ab6..dffb7d3859 100644
--- a/apps/web/pages/api/scim/v2.0/[...directory].ts
+++ b/apps/web/app/api/scim/v2.0/[...directory]/route.ts
@@ -1,4 +1,5 @@
import { inviteUser } from "@/lib/api/users";
+import { getSearchParams } from "@/lib/auth";
import jackson from "@/lib/jackson";
import prisma from "@/lib/prisma";
import { ProjectProps } from "@/lib/types";
@@ -6,40 +7,40 @@ import type {
DirectorySyncEvent,
DirectorySyncRequest,
} from "@boxyhq/saml-jackson";
-import type { NextApiRequest, NextApiResponse } from "next";
+import { NextResponse } from "next/server";
-// Fetch the auth token from the request headers
-export const extractAuthToken = (req: NextApiRequest): string | null => {
- const authHeader = req.headers.authorization || null;
+const handler = async (
+ req: Request,
+ { params }: { params: Record<string, string> },
+) => {
+ const authHeader = req.headers.get("Authorization");
+ const apiSecret = authHeader ? authHeader.split(" ")[1] : null;
- return authHeader ? authHeader.split(" ")[1] : null;
-};
+ const query = getSearchParams(req.url);
+ const [directoryId, path, resourceId] = params.directory;
+ let body;
+ try {
+ body = await req.json();
+ } catch (error) {
+ body = {};
+ }
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
const { directorySyncController } = await jackson();
- const { method, query, body } = req;
-
- const directory = query.directory as string[];
- const [directoryId, path, resourceId] = directory;
-
// Handle the SCIM API requests
const request: DirectorySyncRequest = {
- method: method as string,
- body: body ? JSON.parse(body) : undefined,
+ method: req.method,
+ body,
directoryId,
resourceId,
resourceType: path === "Users" ? "users" : "groups",
- apiSecret: extractAuthToken(req),
+ apiSecret,
query: {
- count: req.query.count ? parseInt(req.query.count as string) : undefined,
- startIndex: req.query.startIndex
- ? parseInt(req.query.startIndex as string)
+ count: query.count ? parseInt(query.count as string) : undefined,
+ startIndex: query.startIndex
+ ? parseInt(query.startIndex as string)
: undefined,
- filter: req.query.filter as string,
+ filter: query.filter as string,
},
};
@@ -48,8 +49,10 @@ export default async function handler(
handleEvents,
);
- res.status(status).json(data);
-}
+ return NextResponse.json(data, { status });
+};
+
+export { handler as GET, handler as POST, handler as PUT, handler as DELETE };
// Handle the SCIM events
const handleEvents = async (event: DirectorySyncEvent) => {
diff --git a/apps/web/app/api/stats/[endpoint]/route.ts b/apps/web/app/api/stats/[endpoint]/route.ts
index 2909c85524..b3e19a2cdc 100644
--- a/apps/web/app/api/stats/[endpoint]/route.ts
+++ b/apps/web/app/api/stats/[endpoint]/route.ts
@@ -1,16 +1,22 @@
-import { withAuth } from "@/lib/auth-app";
+import { withAuth } from "@/lib/auth";
import { getStats } from "@/lib/stats";
import { NextResponse } from "next/server";
-export const GET = withAuth(async ({ params, searchParams }) => {
- const { endpoint } = params;
- const { domain, key, interval } = searchParams;
+// GET /api/stats/[endpoint] – get stats for a specific endpoint
+export const GET = withAuth(
+ async ({ params, searchParams }) => {
+ const { endpoint } = params;
+ const { domain, key, interval } = searchParams;
- const response = await getStats({
- domain,
- key,
- endpoint,
- interval,
- });
- return NextResponse.json(response);
-});
+ const response = await getStats({
+ domain,
+ key,
+ endpoint,
+ interval,
+ });
+ return NextResponse.json(response);
+ },
+ {
+ needNotExceededUsage: true,
+ },
+);
diff --git a/apps/web/app/api/stats/route.ts b/apps/web/app/api/stats/route.ts
index a30e2d7b4a..e7d8019005 100644
--- a/apps/web/app/api/stats/route.ts
+++ b/apps/web/app/api/stats/route.ts
@@ -1,7 +1,8 @@
-import { withAuth } from "@/lib/auth-app";
+import { withAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
+// GET /api/stats – get the publicStats setting for a link
export const GET = withAuth(async ({ searchParams }) => {
const { domain, key } = searchParams;
const response = await prisma.link.findUnique({
@@ -18,6 +19,7 @@ export const GET = withAuth(async ({ searchParams }) => {
return NextResponse.json(response);
});
+// PUT /api/stats – update the publicStats setting for a link
export const PUT = withAuth(async ({ req, searchParams }) => {
const { domain, key } = searchParams;
const { publicStats } = await req.json();
diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.ts
new file mode 100644
index 0000000000..dc24ffacc2
--- /dev/null
+++ b/apps/web/app/api/user/route.ts
@@ -0,0 +1,67 @@
+import { deleteUserLinks } from "@/lib/api/links";
+import { withSession } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import cloudinary from "cloudinary";
+import { NextResponse } from "next/server";
+
+// PUT /api/user – edit a specific user
+export const PUT = withSession(async ({ req, session }) => {
+ let { name, email, image } = await req.json();
+ try {
+ if (image) {
+ const { secure_url } = await cloudinary.v2.uploader.upload(image, {
+ public_id: session.user.id,
+ folder: "avatars",
+ overwrite: true,
+ invalidate: true,
+ });
+ image = secure_url;
+ }
+ const response = await prisma.user.update({
+ where: {
+ id: session.user.id,
+ },
+ data: {
+ ...(name && { name }),
+ ...(email && { email }),
+ ...(image && { image }),
+ },
+ });
+ return NextResponse.json(response);
+ } catch (error) {
+ if (error.code === "P2002") {
+ // return res.status(422).end("Email is already in use.");
+ return new Response("Email is already in use.", { status: 422 });
+ }
+ return new Response(error.message, { status: 500 });
+ }
+});
+
+// DELETE /api/user – delete a specific user
+export const DELETE = withSession(async ({ session }) => {
+ const userIsOwnerOfProjects = await prisma.projectUsers.findMany({
+ where: {
+ userId: session.user.id,
+ role: "owner",
+ },
+ });
+ if (userIsOwnerOfProjects.length > 0) {
+ return new Response(
+ "You must transfer ownership of your projects or delete them before you can delete your account.",
+ { status: 422 },
+ );
+ } else {
+ const [deleteLinks, _] = await Promise.allSettled([
+ deleteUserLinks(session.user.id),
+ cloudinary.v2.uploader.destroy(`avatars/${session?.user?.id}`, {
+ invalidate: true,
+ }),
+ ]);
+ const response = await prisma.user.delete({
+ where: {
+ id: session.user.id,
+ },
+ });
+ return NextResponse.json({ deleteLinks, response });
+ }
+});
diff --git a/apps/web/app/api/user/tokens/route.ts b/apps/web/app/api/user/tokens/route.ts
new file mode 100644
index 0000000000..4d8c841469
--- /dev/null
+++ b/apps/web/app/api/user/tokens/route.ts
@@ -0,0 +1,66 @@
+import { hashToken, withSession } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { customAlphabet } from "nanoid";
+import { NextResponse } from "next/server";
+
+const generateToken = customAlphabet(
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
+ 24,
+);
+
+// GET /api/user/tokens – get all tokens for a specific user
+export const GET = withSession(async ({ session }) => {
+ const tokens = await prisma.token.findMany({
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ id: true,
+ name: true,
+ partialKey: true,
+ createdAt: true,
+ lastUsed: true,
+ },
+ orderBy: [
+ {
+ lastUsed: "desc",
+ },
+ {
+ createdAt: "desc",
+ },
+ ],
+ });
+ return NextResponse.json(tokens);
+});
+
+// POST /api/user/tokens – create a new token for a specific user
+export const POST = withSession(async ({ req, session }) => {
+ const { name } = await req.json();
+ const token = generateToken();
+ const hashedKey = hashToken(token, {
+ noSecret: true,
+ });
+ // take first 3 and last 4 characters of the key
+ const partialKey = `${token.slice(0, 3)}...${token.slice(-4)}`;
+ await prisma.token.create({
+ data: {
+ name,
+ hashedKey,
+ partialKey,
+ userId: session.user.id,
+ },
+ });
+ return NextResponse.json({ token });
+});
+
+// DELETE /api/user/tokens – delete a token for a specific user
+export const DELETE = withSession(async ({ searchParams, session }) => {
+ const { id } = searchParams;
+ const response = await prisma.token.delete({
+ where: {
+ id,
+ userId: session.user.id,
+ },
+ });
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx b/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx
index f3b9e1148b..d1acebe774 100644
--- a/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx
@@ -1,18 +1,21 @@
-import { getSession } from "@/lib/auth-app";
+import { getSession } from "@/lib/auth";
import { getLink } from "@/lib/fetchers";
import LinkNotFound from "@/ui/links/link-not-found";
import Stats from "@/ui/stats";
+import { cache } from "react";
+
+const cachedGetSession = cache(getSession);
export default async function LinkAnalytics({
searchParams,
}: {
searchParams: { [key: string]: string | undefined };
}) {
- if (!searchParams?.key) {
+ if (searchParams.domain !== "dub.sh" || !searchParams?.key) {
return <LinkNotFound />;
}
const [session, link] = await Promise.all([
- getSession(),
+ cachedGetSession(),
getLink({
domain: searchParams.domain || "dub.sh",
key: searchParams.key || "github",
diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.ts
index 21d83be05b..ec728b5a1c 100644
--- a/apps/web/lib/api/domains.ts
+++ b/apps/web/lib/api/domains.ts
@@ -8,10 +8,7 @@ import {
import cloudinary from "cloudinary";
import { isIframeable } from "../middleware/utils";
-export const validateDomain = async (
- domain: string,
- projectId?: string | null,
-) => {
+export const validateDomain = async (domain: string) => {
if (!domain || typeof domain !== "string") {
return "Missing domain";
}
@@ -23,42 +20,23 @@ export const validateDomain = async (
if (!validDomain) {
return "Invalid domain";
}
- const exists = await domainExists(domain, projectId);
+ const exists = await domainExists(domain);
if (exists) {
return "Domain is already in use.";
}
return true;
};
-export const domainExists = async (
- domain: string,
- projectId?: string | null,
-) => {
- const apexDomain = getApexDomain(`https://${domain}`);
- const response = await prisma.domain.findFirst({
+export const domainExists = async (domain: string) => {
+ const response = await prisma.domain.findUnique({
where: {
- OR: [
- // if someone tries to add "sub.domain.com" but "domain.com" is already in use
- {
- slug: apexDomain,
- },
- // if someone tries to add "domain.com" but "sub.domain.com" is already in use
- {
- slug: {
- endsWith: `.${apexDomain}`,
- },
- },
- ],
+ slug: domain,
},
select: {
slug: true,
- ...(projectId && { projectId: true }),
},
});
if (response) {
- if (projectId && response.projectId === projectId) {
- return false;
- }
return true;
}
return false;
diff --git a/apps/web/lib/auth-app.ts b/apps/web/lib/auth-app.ts
deleted file mode 100644
index 97f70d5bf4..0000000000
--- a/apps/web/lib/auth-app.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-import prisma from "@/lib/prisma";
-import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { Link as LinkProps } from "@prisma/client";
-import { PlanProps, ProjectProps } from "./types";
-import { getServerSession } from "next-auth/next";
-
-export interface Session {
- user: {
- email: string;
- id: string;
- name: string;
- image?: string;
- };
-}
-
-export async function getSession() {
- return getServerSession(authOptions) as Promise<Session>;
-}
-
-export function getSearchParams(url: string) {
- // Create a params object
- let params = {} as any;
-
- new URL(url).searchParams.forEach(function (val, key) {
- params[key] = val;
- });
-
- return params;
-}
-
-interface WithAuthHandler {
- ({
- req,
- params,
- searchParams,
- session,
- project,
- link,
- }: {
- req: Request;
- params: Record<string, string>;
- searchParams: Record<string, string>;
- session: Session;
- project?: ProjectProps;
- link?: LinkProps;
- }): Promise<Response>;
-}
-const withAuth =
- (
- handler: WithAuthHandler,
- {
- requiredPlan = ["free", "pro", "enterprise"], // if the action needs a specific plan
- requiredRole = ["owner", "member"],
- needNotExceededUsage, // if the action needs the user to not have exceeded their usage
- }: {
- requiredPlan?: Array<PlanProps>;
- requiredRole?: Array<"owner" | "member">;
- needNotExceededUsage?: boolean;
- } = {},
- ) =>
- async (req: Request, { params }: { params: Record<string, string> }) => {
- const session = await getSession();
- if (!session?.user.id) {
- return new Response("Unauthorized: Login required.", { status: 401 });
- }
-
- const searchParams = getSearchParams(req.url);
- const { slug, domain, key } = searchParams;
-
- const [project, link] = (await Promise.all([
- slug &&
- (await prisma.project.findUnique({
- where: {
- slug,
- },
- select: {
- id: true,
- name: true,
- slug: true,
- logo: true,
- usage: true,
- usageLimit: true,
- plan: true,
- stripeId: true,
- billingCycleStart: true,
- createdAt: true,
- domains: true,
- users: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
- },
- },
- },
- })),
- domain &&
- key &&
- prisma.link.findUnique({
- where: {
- domain_key: {
- domain,
- key,
- },
- },
- }),
- ])) as [ProjectProps | undefined, LinkProps | undefined];
-
- // it's a project
- if (slug) {
- if (!project || !project.users) {
- // project doesn't exist
- return new Response("Project not found.", {
- status: 404,
- });
- }
-
- if (domain && !project.domains!.find((d) => d.slug === domain)) {
- return new Response("Unauthorized: Invalid domain.", {
- status: 401,
- });
- }
-
- if (link && link.projectId !== project.id) {
- return new Response("Unauthorized: Invalid link.", {
- status: 401,
- });
- }
-
- // project exists but user is not part of it
- if (project.users.length === 0) {
- const pendingInvites = await prisma.projectInvite.findUnique({
- where: {
- email_projectId: {
- email: session.user.email,
- projectId: project.id,
- },
- },
- select: {
- expires: true,
- },
- });
- if (!pendingInvites) {
- return new Response("Project not found.", {
- status: 404,
- });
- } else if (pendingInvites.expires < new Date()) {
- return new Response("Project invite expired.", {
- status: 410,
- });
- } else {
- return new Response("Project invite pending.", {
- status: 409,
- });
- }
- }
-
- if (
- project.plan === "enterprise" &&
- !requiredRole.includes(project.users[0].role) &&
- // removing self from project should be allowed (DELETE /api/projects/[slug]/users?userId=...)
- !(
- req.url === `/api/projects/${slug}/users?userId=${session.user.id}` &&
- req.method === "DELETE"
- )
- ) {
- return new Response("Unauthorized: Insufficient permissions.", {
- status: 403,
- });
- }
-
- if (needNotExceededUsage && project.usage > project.usageLimit) {
- return new Response("Unauthorized: Usage limits exceeded.", {
- status: 403,
- });
- }
-
- if (!requiredPlan.includes(project.plan)) {
- // return res.status(403).end("Unauthorized: Need higher plan.");
- return new Response("Unauthorized: Need higher plan.", {
- status: 403,
- });
- }
- } else if (link) {
- // no slug means it's a generic Dub.sh link
- // thus, we need to make sure the user is the owner of the link
- if (link.userId !== session.user.id) {
- return new Response("Unauthorized: Invalid link.", {
- status: 401,
- });
- }
- }
-
- return handler({ req, params, searchParams, session, project, link });
- };
-
-export { withAuth };
diff --git a/apps/web/lib/auth-links.ts b/apps/web/lib/auth-links.ts
new file mode 100644
index 0000000000..1fe94e3606
--- /dev/null
+++ b/apps/web/lib/auth-links.ts
@@ -0,0 +1,249 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { API_DOMAIN } from "@dub/utils";
+import { ratelimit } from "./upstash";
+import { Session, hashToken } from "./auth";
+import { Link as LinkProps } from "@prisma/client";
+import { PlanProps, ProjectProps } from "./types";
+import prisma from "@/lib/prisma";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+
+interface WithLinksAuthNextApiHandler {
+ (
+ req: NextApiRequest,
+ res: NextApiResponse,
+ session: Session,
+ project?: ProjectProps,
+ domain?: string,
+ link?: LinkProps,
+ ): any;
+}
+
+/*
+ This is the auth handler for all link-related actions.
+
+ In the future, we might want to combine this with other endpoints as well (e.g. /projects, /domains, etc.)
+
+ Here's an outline of the flow:
+ 1. Check if user is logged in, if not, return 401 right away.
+ 2. Check if there's a `slug` in the query params:
+ a. If there is no slug, it means that it's the generic dub.sh links
+ i. Make sure the domain is `dub.sh` (prevent query injection)
+ ii. If link `key` is provided, make sure user is the owner of the link
+ b. If there is a slug, it means that it's a custom project
+ i. Make sure the project exists
+ ii. Make sure the user is part of the project
+ iii. Make sure the project is within its usage limits
+ iv. Make sure the action is allowed for the project's plan
+ v. Make sure the domain is part of the project (prevent query injection)
+ */
+
+const withLinksAuth =
+ (
+ handler: WithLinksAuthNextApiHandler,
+ {
+ needNotExceededUsage, // if the action needs the user to not have exceeded their usage
+ excludeGet, // if the action doesn't need to be gated for GET requests
+ requiredPlan = ["free", "pro", "enterprise"], // if the action needs a specific plan
+ skipKeyCheck, // if the action doesn't need to check if the user is the owner of the link (/exists endpoint)
+ }: {
+ needNotExceededUsage?: boolean;
+ excludeGet?: boolean;
+ requiredPlan?: Array<PlanProps>;
+ skipKeyCheck?: boolean;
+ } = {},
+ ) =>
+ async (req: NextApiRequest, res: NextApiResponse) => {
+ const { slug, domain, key } = req.query as {
+ slug?: string; // project slug (query param)
+ domain?: string; // link domain (query param)
+ key?: string; // link key (path param)
+ };
+
+ // if slug is misconfgured
+ if (slug && typeof slug !== "string") {
+ return res.status(400).end("Missing or misconfigured project slug.");
+ }
+
+ let session: Session | undefined;
+
+ const authorizationHeader = req.headers.authorization;
+ if (authorizationHeader) {
+ if (!authorizationHeader.includes("Bearer ")) {
+ return res
+ .status(400)
+ .end(
+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://dub.sh/auth ",
+ );
+ }
+ const apiKey = authorizationHeader.replace("Bearer ", "");
+ // if there is no slug, it's the default dub.sh link
+ if (!slug) {
+ return res
+ .status(403)
+ .end("Unauthorized: API is not supported for dub.sh links yet.");
+ }
+
+ const url = new URL(req.url || "", API_DOMAIN);
+
+ if (url.pathname.includes("/stats/")) {
+ return res.status(403).end("Unauthorized: Invalid route.");
+ }
+
+ 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) {
+ return res.status(401).end("Unauthorized: Invalid API key.");
+ }
+
+ const { success, limit, reset, remaining } = await ratelimit(
+ 10,
+ "1 s",
+ ).limit(apiKey);
+ res.setHeader("X-RateLimit-Limit", limit.toString());
+ res.setHeader("X-RateLimit-Remaining", remaining.toString());
+ res.setHeader("X-RateLimit-Reset", reset.toString());
+ res.setHeader("Retry-After", reset.toString());
+
+ if (!success) {
+ return res.status(429).end("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 getServerSession(req, res, authOptions)) as Session;
+ if (!session?.user.id) {
+ return res.status(401).end("Unauthorized: Login required.");
+ }
+ }
+
+ let project: ProjectProps | undefined;
+ let link: LinkProps | undefined;
+
+ // if there is no slug, it's the default dub.sh link
+ if (!slug) {
+ // prevent domain from being query injected by
+ // making sure that all instances of `domain` are `dub.sh`
+ if (
+ (domain && domain !== "dub.sh") ||
+ (req.body.domain && req.body.domain !== "dub.sh")
+ ) {
+ return res.status(403).end("Unauthorized: Invalid domain.");
+ }
+
+ // if project slug is defined, that means it's a custom project on Dub
+ } else {
+ project = (await prisma.project.findUnique({
+ where: {
+ slug,
+ },
+ include: {
+ domains: {
+ select: {
+ slug: true,
+ },
+ },
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ role: true,
+ },
+ },
+ },
+ })) as ProjectProps;
+
+ // if project doesn't exist
+ if (!project) {
+ return res.status(404).end("Project not found.");
+
+ // if project exists but user is not part of it
+ } else if (project.users && project.users.length === 0) {
+ // TODO: check if user has pending invite
+ return res.status(401).end("Unauthorized: Not part of project.");
+
+ // project exists and user is part of it
+ } else {
+ // if the action requires the project to be within usage limits,
+ // and the action is not a GET request with excludeGet set to true,
+ // check if the project is within usage limits
+ if (
+ needNotExceededUsage &&
+ !(req.method === "GET" && excludeGet) &&
+ project.usage > project.usageLimit
+ ) {
+ return res.status(403).end("Unauthorized: Usage limits exceeded.");
+ }
+
+ if (requiredPlan && !requiredPlan.includes(project.plan)) {
+ return res.status(403).end("Unauthorized: Need higher plan.");
+ }
+
+ // prevent unauthorized access to domains
+ if (
+ (domain && !project.domains?.find((d) => d.slug === domain)) ||
+ (req.body.domain &&
+ !project.domains?.find((d) => d.slug === req.body.domain))
+ ) {
+ return res.status(403).end("Unauthorized: Invalid domain.");
+ }
+ }
+ }
+
+ if (key) {
+ if (typeof key !== "string") {
+ return res.status(400).end("Missing or misconfigured link key.");
+ }
+ link =
+ (await prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain: domain || "dub.sh",
+ key,
+ },
+ },
+ })) || undefined;
+
+ if (!link) {
+ return res.status(404).end("Link not found.");
+
+ // for dub.sh links, check if the user is the owner of the link
+ } else if (!slug && link.userId !== session.user.id && !skipKeyCheck) {
+ return res.status(404).end("Link not found.");
+ }
+ }
+
+ return handler(req, res, session, project, domain, link);
+ };
+
+export { withLinksAuth };
diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts
index 05c16cca3a..7a51ecb5c1 100644
--- a/apps/web/lib/auth.ts
+++ b/apps/web/lib/auth.ts
@@ -1,12 +1,9 @@
import prisma from "@/lib/prisma";
-import { PlanProps, ProjectProps, UserProps } from "@/lib/types";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { API_DOMAIN } from "@dub/utils";
-import { type Link as LinkProps } from "@prisma/client";
-import { createHash } from "crypto";
-import { NextApiRequest, NextApiResponse } from "next";
+import { Link as LinkProps } from "@prisma/client";
+import { PlanProps, ProjectProps } from "./types";
import { getServerSession } from "next-auth/next";
-import { ratelimit } from "./upstash";
+import { createHash } from "crypto";
export interface Session {
user: {
@@ -17,9 +14,19 @@ export interface Session {
};
}
-export async function getSession(req: NextApiRequest, res: NextApiResponse) {
- // @ts-ignore
- return (await getServerSession(req, res, authOptions)) as Session;
+export const getSession = async () => {
+ return getServerSession(authOptions) as Promise<Session>;
+};
+
+export function getSearchParams(url: string) {
+ // Create a params object
+ let params = {} as Record<string, string>;
+
+ new URL(url).searchParams.forEach(function (val, key) {
+ params[key] = val;
+ });
+
+ return params;
}
export const hashToken = (
@@ -34,67 +41,125 @@ export const hashToken = (
.update(`${token}${noSecret ? "" : process.env.NEXTAUTH_SECRET}`)
.digest("hex");
};
-interface WithProjectNextApiHandler {
- (
- req: NextApiRequest,
- res: NextApiResponse,
- project: ProjectProps,
- session: Session,
- ): any;
-}
-const withProjectAuth =
+interface WithAuthHandler {
+ ({
+ req,
+ params,
+ searchParams,
+ session,
+ project,
+ domain,
+ link,
+ }: {
+ req: Request;
+ params: Record<string, string>;
+ searchParams: Record<string, string>;
+ session: Session;
+ project: ProjectProps;
+ domain: string;
+ link?: LinkProps;
+ }): Promise<Response>;
+}
+export const withAuth =
(
- handler: WithProjectNextApiHandler,
+ handler: WithAuthHandler,
{
- excludeGet, // if the action doesn't need to be gated for GET requests
requiredPlan = ["free", "pro", "enterprise"], // if the action needs a specific plan
requiredRole = ["owner", "member"],
needNotExceededUsage, // if the action needs the user to not have exceeded their usage
}: {
- excludeGet?: boolean;
requiredPlan?: Array<PlanProps>;
requiredRole?: Array<"owner" | "member">;
needNotExceededUsage?: boolean;
} = {},
) =>
- async (req: NextApiRequest, res: NextApiResponse) => {
- const session = await getSession(req, res);
- if (!session?.user.id)
- return res.status(401).end("Unauthorized: Login required.");
-
- const { slug } = req.query;
- if (!slug || typeof slug !== "string") {
- return res.status(400).end("Missing or misconfigured project slug.");
+ async (
+ req: Request,
+ { params }: { params: Record<string, string> | undefined },
+ ) => {
+ const session = await getSession();
+ if (!session?.user.id) {
+ return new Response("Unauthorized: Login required.", { status: 401 });
}
- const project = (await prisma.project.findUnique({
- where: {
- slug,
- },
- select: {
- id: true,
- name: true,
- slug: true,
- logo: true,
- usage: true,
- usageLimit: true,
- plan: true,
- stripeId: true,
- billingCycleStart: true,
- createdAt: true,
- users: {
+ const searchParams = getSearchParams(req.url);
+ const { key } = searchParams;
+ const { slug } = params || {};
+ // domain can either be a path param or a query param
+ const domain = params?.domain || searchParams?.domain;
+
+ const [project, link] = (await Promise.all([
+ slug &&
+ prisma.project.findUnique({
where: {
- userId: session.user.id,
+ slug,
},
select: {
- role: true,
+ id: true,
+ name: true,
+ slug: true,
+ logo: true,
+ usage: true,
+ usageLimit: true,
+ plan: true,
+ stripeId: true,
+ billingCycleStart: true,
+ createdAt: true,
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ role: true,
+ },
+ },
},
- },
- },
- })) as ProjectProps;
+ }),
+ domain &&
+ key &&
+ prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain,
+ key,
+ },
+ },
+ }),
+ ])) as [ProjectProps | undefined, LinkProps | undefined];
+
+ // it's a project
+ if (slug) {
+ if (!project || !project.users) {
+ // project doesn't exist
+ return new Response("Project not found.", {
+ status: 404,
+ });
+ }
+
+ // prevent unauthorized access to domains that don't belong to the project
+ if (domain) {
+ const domainProjectId = await prisma.domain.findUnique({
+ where: {
+ slug: domain,
+ },
+ select: {
+ projectId: true,
+ },
+ });
+ if (domainProjectId?.projectId !== project.id) {
+ return new Response("Domain not found.", {
+ status: 404,
+ });
+ }
+ }
+
+ if (link && link.projectId !== project.id) {
+ return new Response("Unauthorized: Invalid link.", {
+ status: 401,
+ });
+ }
- if (project && project.users) {
// project exists but user is not part of it
if (project.users.length === 0) {
const pendingInvites = await prisma.projectInvite.findUnique({
@@ -109,329 +174,90 @@ const withProjectAuth =
},
});
if (!pendingInvites) {
- return res.status(404).end("Project not found.");
+ return new Response("Project not found.", {
+ status: 404,
+ });
} else if (pendingInvites.expires < new Date()) {
- return res.status(410).end("Project invite expired.");
+ return new Response("Project invite expired.", {
+ status: 410,
+ });
} else {
- return res.status(409).end("Project invite pending.");
+ return new Response("Project invite pending.", {
+ status: 409,
+ });
}
}
- } else {
- // project doesn't exist
- return res.status(404).end("Project not found.");
- }
-
- // if the action doesn't need to be gated for GET requests, return handler now
- if (req.method === "GET" && excludeGet) {
- return handler(req, res, project, session);
- }
-
- if (
- project.plan === "enterprise" &&
- !requiredRole.includes(project.users[0].role) &&
- // removing self from project should be allowed (DELETE /api/projects/[slug]/users?userId=...)
- !(
- req.url === `/api/projects/${slug}/users?userId=${session.user.id}` &&
- req.method === "DELETE"
- )
- ) {
- return res.status(403).end("Unauthorized: Insufficient permissions.");
- }
-
- if (needNotExceededUsage && project.usage > project.usageLimit) {
- return res.status(403).end("Unauthorized: Usage limits exceeded.");
- }
-
- if (!requiredPlan.includes(project.plan)) {
- return res.status(403).end("Unauthorized: Need higher plan.");
- }
-
- return handler(req, res, project, session);
- };
-
-export { withProjectAuth };
-
-interface WithUsertNextApiHandler {
- (
- req: NextApiRequest,
- res: NextApiResponse,
- session: Session,
- user?: UserProps,
- ): any;
-}
-
-const withUserAuth =
- (
- handler: WithUsertNextApiHandler,
- {
- needUserDetails, // if the action needs the user's details
- }: {
- needUserDetails?: boolean;
- } = {},
- ) =>
- async (req: NextApiRequest, res: NextApiResponse) => {
- const session = await getSession(req, res);
- if (!session?.user.id)
- return res.status(401).end("Unauthorized: Login required.");
-
- if (req.method === "GET") return handler(req, res, session);
-
- if (needUserDetails) {
- const user = (await prisma.user.findUnique({
- where: {
- id: session.user.id,
- },
- select: {
- id: true,
- name: true,
- email: true,
- },
- })) as UserProps;
-
- return handler(req, res, session, user);
- }
-
- return handler(req, res, session);
- };
-
-export { withUserAuth };
-
-interface WithLinksAuthNextApiHandler {
- (
- req: NextApiRequest,
- res: NextApiResponse,
- session: Session,
- project?: ProjectProps,
- domain?: string,
- link?: LinkProps,
- ): any;
-}
-/*
- This is the auth handler for all link-related actions.
-
- In the future, we might want to combine this with other endpoints as well (e.g. /projects, /domains, etc.)
-
- Here's an outline of the flow:
- 1. Check if user is logged in, if not, return 401 right away.
- 2. Check if there's a `slug` in the query params:
- a. If there is no slug, it means that it's the generic dub.sh links
- i. Make sure the domain is `dub.sh` (prevent query injection)
- ii. If link `key` is provided, make sure user is the owner of the link
- b. If there is a slug, it means that it's a custom project
- i. Make sure the project exists
- ii. Make sure the user is part of the project
- iii. Make sure the project is within its usage limits
- iv. Make sure the action is allowed for the project's plan
- v. Make sure the domain is part of the project (prevent query injection)
-*/
-
-const withLinksAuth =
- (
- handler: WithLinksAuthNextApiHandler,
- {
- needNotExceededUsage, // if the action needs the user to not have exceeded their usage
- excludeGet, // if the action doesn't need to be gated for GET requests
- requiredPlan = ["free", "pro", "enterprise"], // if the action needs a specific plan
- skipKeyCheck, // if the action doesn't need to check if the user is the owner of the link (/exists endpoint)
- }: {
- needNotExceededUsage?: boolean;
- excludeGet?: boolean;
- requiredPlan?: Array<PlanProps>;
- skipKeyCheck?: boolean;
- } = {},
- ) =>
- async (req: NextApiRequest, res: NextApiResponse) => {
- const { slug, domain, key } = req.query as {
- slug?: string; // project slug (query param)
- domain?: string; // link domain (query param)
- key?: string; // link key (path param)
- };
-
- // if slug is misconfgured
- if (slug && typeof slug !== "string") {
- return res.status(400).end("Missing or misconfigured project slug.");
- }
-
- let session: Session | undefined;
-
- const authorizationHeader = req.headers.authorization;
- if (authorizationHeader) {
- if (!authorizationHeader.includes("Bearer ")) {
- return res
- .status(400)
- .end(
- "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://dub.sh/auth ",
- );
- }
- const apiKey = authorizationHeader.replace("Bearer ", "");
- // if there is no slug, it's the default dub.sh link
- if (!slug) {
- return res
- .status(403)
- .end("Unauthorized: API is not supported for dub.sh links yet.");
- }
-
- const url = new URL(req.url || "", API_DOMAIN);
-
- if (url.pathname.includes("/stats/")) {
- return res.status(403).end("Unauthorized: Invalid route.");
- }
-
- 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) {
- return res.status(401).end("Unauthorized: Invalid API key.");
- }
-
- const { success, limit, reset, remaining } = await ratelimit(
- 10,
- "1 s",
- ).limit(apiKey);
- res.setHeader("X-RateLimit-Limit", limit.toString());
- res.setHeader("X-RateLimit-Remaining", remaining.toString());
- res.setHeader("X-RateLimit-Reset", reset.toString());
- res.setHeader("Retry-After", reset.toString());
-
- if (!success) {
- return res.status(429).end("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(req, res);
- if (!session?.user.id) {
- return res.status(401).end("Unauthorized: Login required.");
- }
- }
-
- let project: ProjectProps | undefined;
- let link: LinkProps | undefined;
-
- // if there is no slug, it's the default dub.sh link
- if (!slug) {
- // prevent domain from being query injected by
- // making sure that all instances of `domain` are `dub.sh`
if (
- (domain && domain !== "dub.sh") ||
- (req.body.domain && req.body.domain !== "dub.sh")
+ requiredRole &&
+ project.plan === "enterprise" &&
+ !requiredRole.includes(project.users[0].role) &&
+ // removing self from project should be allowed (DELETE /api/projects/[slug]/users?userId=...)
+ !(
+ req.url === `/api/projects/${slug}/users?userId=${session.user.id}` &&
+ req.method === "DELETE"
+ )
) {
- return res.status(403).end("Unauthorized: Invalid domain.");
+ return new Response("Unauthorized: Insufficient permissions.", {
+ status: 403,
+ });
}
- // if project slug is defined, that means it's a custom project on Dub
- } else {
- project = (await prisma.project.findUnique({
- where: {
- slug,
- },
- include: {
- domains: {
- select: {
- slug: true,
- },
- },
- users: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
- },
- },
- },
- })) as ProjectProps;
-
- // if project doesn't exist
- if (!project) {
- return res.status(404).end("Project not found.");
-
- // if project exists but user is not part of it
- } else if (project.users && project.users.length === 0) {
- // TODO: check if user has pending invite
- return res.status(401).end("Unauthorized: Not part of project.");
-
- // project exists and user is part of it
- } else {
- // if the action requires the project to be within usage limits,
- // and the action is not a GET request with excludeGet set to true,
- // check if the project is within usage limits
- if (
- needNotExceededUsage &&
- !(req.method === "GET" && excludeGet) &&
- project.usage > project.usageLimit
- ) {
- return res.status(403).end("Unauthorized: Usage limits exceeded.");
- }
-
- if (requiredPlan && !requiredPlan.includes(project.plan)) {
- return res.status(403).end("Unauthorized: Need higher plan.");
- }
+ if (needNotExceededUsage && project.usage > project.usageLimit) {
+ return new Response("Unauthorized: Usage limits exceeded.", {
+ status: 403,
+ });
+ }
- // prevent unauthorized access to domains
- if (
- (domain && !project.domains?.find((d) => d.slug === domain)) ||
- (req.body.domain &&
- !project.domains?.find((d) => d.slug === req.body.domain))
- ) {
- return res.status(403).end("Unauthorized: Invalid domain.");
- }
+ if (!requiredPlan.includes(project.plan)) {
+ // return res.status(403).end("Unauthorized: Need higher plan.");
+ return new Response("Unauthorized: Need higher plan.", {
+ status: 403,
+ });
+ }
+ } else if (link) {
+ // no slug means it's a generic Dub.sh link
+ // thus, we need to make sure the user is the owner of the link
+ if (link.userId !== session.user.id) {
+ return new Response("Unauthorized: Invalid link.", {
+ status: 401,
+ });
}
}
- if (key) {
- if (typeof key !== "string") {
- return res.status(400).end("Missing or misconfigured link key.");
- }
- link =
- (await prisma.link.findUnique({
- where: {
- domain_key: {
- domain: domain || "dub.sh",
- key,
- },
- },
- })) || undefined;
+ return handler({
+ req,
+ params: params || {},
+ searchParams,
+ session,
+ project: project as ProjectProps,
+ domain,
+ link,
+ });
+ };
- if (!link) {
- return res.status(404).end("Link not found.");
+interface WithSessionHandler {
+ ({
+ req,
+ params,
+ searchParams,
+ session,
+ }: {
+ req: Request;
+ params: Record<string, string>;
+ searchParams: Record<string, string>;
+ session: Session;
+ }): Promise<Response>;
+}
- // for dub.sh links, check if the user is the owner of the link
- } else if (!slug && link.userId !== session.user.id && !skipKeyCheck) {
- return res.status(404).end("Link not found.");
- }
+export const withSession =
+ (handler: WithSessionHandler) =>
+ async (req: Request, { params }: { params: Record<string, string> }) => {
+ const session = await getSession();
+ if (!session?.user.id) {
+ return new Response("Unauthorized: Login required.", { status: 401 });
}
- return handler(req, res, session, project, domain, link);
+ const searchParams = getSearchParams(req.url);
+ return handler({ req, params, searchParams, session });
};
-
-export { withLinksAuth };
diff --git a/apps/web/lib/fetchers.ts b/apps/web/lib/fetchers.ts
index a4f77981c3..0ca3193545 100644
--- a/apps/web/lib/fetchers.ts
+++ b/apps/web/lib/fetchers.ts
@@ -1,5 +1,5 @@
import { cache } from "react";
-import { getSession } from "./auth-app";
+import { getSession } from "./auth";
import prisma from "./prisma";
import { ProjectWithDomainProps } from "./types";
diff --git a/apps/web/pages/api/domains/[domain]/exists.ts b/apps/web/pages/api/domains/[domain]/exists.ts
deleted file mode 100644
index 5d7b027c52..0000000000
--- a/apps/web/pages/api/domains/[domain]/exists.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { domainExists } from "@/lib/api/domains";
-import { withUserAuth } from "@/lib/auth";
-
-export default withUserAuth(async (req, res) => {
- const { domain } = req.query as { domain: string };
-
- // GET /api/domains/[domain]/exists – check if a domain exists
- // This is used for project creation only, if you add a domain within an existing project,
- // use the /api/projects/[slug]/domains/[domain]/exists endpoint instead
- if (req.method === "GET") {
- const exists = await domainExists(domain);
- if (exists) {
- return res.status(200).json(1);
- } else {
- return res.status(200).json(0);
- }
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/links/[key]/archive.ts b/apps/web/pages/api/links/[key]/archive.ts
index 63de95ef53..b899b84071 100644
--- a/apps/web/pages/api/links/[key]/archive.ts
+++ b/apps/web/pages/api/links/[key]/archive.ts
@@ -1,5 +1,5 @@
import { archiveLink } from "@/lib/api/links";
-import { withLinksAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth-links";
export default withLinksAuth(async (req, res, _session, _project, domain) => {
const { key } = req.query as { key: string };
diff --git a/apps/web/pages/api/links/[key]/exists.ts b/apps/web/pages/api/links/[key]/exists.ts
index 6b091aef03..cb1e92a5a3 100644
--- a/apps/web/pages/api/links/[key]/exists.ts
+++ b/apps/web/pages/api/links/[key]/exists.ts
@@ -1,5 +1,5 @@
import { checkIfKeyExists } from "@/lib/api/links";
-import { withLinksAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth-links";
export default withLinksAuth(
async (req, res, _session, _project, domain) => {
diff --git a/apps/web/pages/api/links/[key]/index.ts b/apps/web/pages/api/links/[key]/index.ts
index 2f10f73790..7cfba274f2 100644
--- a/apps/web/pages/api/links/[key]/index.ts
+++ b/apps/web/pages/api/links/[key]/index.ts
@@ -1,5 +1,5 @@
import { deleteLink, editLink, processKey } from "@/lib/api/links";
-import { withLinksAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth-links";
import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/edge-config";
import { GOOGLE_FAVICON_URL, getApexDomain, log } from "@dub/utils";
diff --git a/apps/web/pages/api/links/_count.ts b/apps/web/pages/api/links/_count.ts
index 2d61ce95ed..b5cd1087f6 100644
--- a/apps/web/pages/api/links/_count.ts
+++ b/apps/web/pages/api/links/_count.ts
@@ -1,5 +1,5 @@
import { getLinksCount } from "@/lib/api/links";
-import { withLinksAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth-links";
import { DUB_PROJECT_ID } from "@dub/utils";
export default withLinksAuth(async (req, res, session, project) => {
diff --git a/apps/web/pages/api/links/_random.ts b/apps/web/pages/api/links/_random.ts
index 62a6ff3a86..59dab18b80 100644
--- a/apps/web/pages/api/links/_random.ts
+++ b/apps/web/pages/api/links/_random.ts
@@ -1,5 +1,5 @@
import { getRandomKey } from "@/lib/api/links";
-import { withLinksAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth-links";
export default withLinksAuth(async (req, res, _session, _project, domain) => {
// GET /api/links/_random – get a random key for a project
diff --git a/apps/web/pages/api/links/index.ts b/apps/web/pages/api/links/index.ts
index bca610c92b..f161ebda6f 100644
--- a/apps/web/pages/api/links/index.ts
+++ b/apps/web/pages/api/links/index.ts
@@ -4,7 +4,7 @@ import {
getRandomKey,
processKey,
} from "@/lib/api/links";
-import { withLinksAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth-links";
import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/edge-config";
import {
DUB_PROJECT_ID,
diff --git a/apps/web/pages/api/projects/[slug]/billing/manage.ts b/apps/web/pages/api/projects/[slug]/billing/manage.ts
deleted file mode 100644
index 6c01c049e3..0000000000
--- a/apps/web/pages/api/projects/[slug]/billing/manage.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import { stripe } from "@/lib/stripe";
-import { APP_DOMAIN } from "@dub/utils";
-
-export default withProjectAuth(async (req, res, project) => {
- // POST /api/projects/[slug]/billing/manage – manage a user's subscription
- if (req.method === "POST") {
- const { slug } = req.query as { slug: string };
- if (!project.stripeId) {
- return res.status(400).json({ error: "No Stripe customer ID" });
- }
- const { url } = await stripe.billingPortal.sessions.create({
- customer: project.stripeId,
- return_url: `${APP_DOMAIN}/${slug}/settings/billing`,
- });
- return res.status(200).json(url);
- } else {
- res.setHeader("Allow", ["POST"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/billing/upgrade.ts b/apps/web/pages/api/projects/[slug]/billing/upgrade.ts
deleted file mode 100644
index 30ecb88082..0000000000
--- a/apps/web/pages/api/projects/[slug]/billing/upgrade.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import { stripe } from "@/lib/stripe";
-import { APP_DOMAIN } from "@dub/utils";
-
-export default withProjectAuth(async (req, res, project, session) => {
- // POST /api/projects/[slug]/billing/upgrade – upgrade a project from free to pro
- if (req.method === "POST") {
- const { slug, priceId } = req.query as { slug: string; priceId: string };
-
- const stripeSession = await stripe.checkout.sessions.create({
- customer_email: session.user.email,
- billing_address_collection: "required",
- success_url: `${APP_DOMAIN}/${slug}/settings/billing?success=true`,
- cancel_url: `${APP_DOMAIN}/${slug}/settings/billing`,
- line_items: [{ price: priceId, quantity: 1 }],
- automatic_tax: {
- enabled: true,
- },
- tax_id_collection: {
- enabled: true,
- },
- mode: "subscription",
- allow_promotion_codes: true,
- client_reference_id: project.id,
- });
- return res.status(200).json(stripeSession);
- } else {
- res.setHeader("Allow", ["POST"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/domains/[domain]/clicks.ts b/apps/web/pages/api/projects/[slug]/domains/[domain]/clicks.ts
deleted file mode 100644
index 809d14456b..0000000000
--- a/apps/web/pages/api/projects/[slug]/domains/[domain]/clicks.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import { getStats } from "@/lib/stats";
-
-export default withProjectAuth(async (req, res) => {
- // GET /api/projects/[slug]/domains/[domain]/clicks - get # of clicks on root of domain (e.g. dub.sh, vercel.fyi)
- if (req.method === "GET") {
- const { domain } = req.query as {
- domain: string;
- };
- const response = await getStats({
- domain,
- key: "_root",
- endpoint: "clicks",
- });
-
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/domains/[domain]/exists.ts b/apps/web/pages/api/projects/[slug]/domains/[domain]/exists.ts
deleted file mode 100644
index b185ff5149..0000000000
--- a/apps/web/pages/api/projects/[slug]/domains/[domain]/exists.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { domainExists } from "@/lib/api/domains";
-import { withProjectAuth } from "@/lib/auth";
-
-export default withProjectAuth(async (req, res, project) => {
- const { domain } = req.query as { domain: string };
-
- // GET /api/projects/[slug]/domains/[domain]/exists – check if a domain exists
- if (req.method === "GET") {
- const exists = await domainExists(domain, project.id);
- if (exists) {
- return res.status(200).json(1);
- } else {
- return res.status(200).json(0);
- }
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/domains/[domain]/index.ts b/apps/web/pages/api/projects/[slug]/domains/[domain]/index.ts
deleted file mode 100644
index 20c7b5cc91..0000000000
--- a/apps/web/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import {
- addDomainToVercel,
- changeDomainForImages,
- changeDomainForLinks,
- deleteDomainAndLinks,
- removeDomainFromVercel,
- setRootDomain,
- validateDomain,
-} from "@/lib/api/domains";
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-import { redis } from "@/lib/upstash";
-
-export default withProjectAuth(
- async (req, res, project) => {
- const { slug, domain } = req.query as { slug: string; domain: string };
-
- if (
- !slug ||
- typeof slug !== "string" ||
- !domain ||
- typeof domain !== "string"
- ) {
- return res
- .status(400)
- .end("Missing or misconfigured project slug or domain");
- }
-
- // prevent unauthorized access to domains that don't belong to the project
- const domainBelongsToProject = await prisma.domain.findFirst({
- where: {
- slug: domain,
- projectId: project.id,
- },
- });
- if (!domainBelongsToProject) {
- return res.status(404).end("Domain not found");
- }
-
- // PUT /api/projects/[slug]/domains/[domain] edit a project's domain
- if (req.method === "PUT") {
- const { slug: newDomain, target, type, primary } = req.body;
-
- const validDomain = await validateDomain(newDomain, project.id);
- if (validDomain !== true) {
- return res.status(422).json({
- domainError: validDomain,
- });
- }
-
- if (newDomain !== domain) {
- const vercelResponse = await addDomainToVercel(newDomain);
- if (vercelResponse.error) {
- return res.status(422).json({
- domainError: vercelResponse.error.message,
- });
- }
- }
-
- const response = await Promise.allSettled([
- // if the domain is being changed, we need to:
- // 1. Remove the old domain from Vercel
- // 2. Add the new domain to Vercel
- // 3. Update all links in the project to point to the new domain
- // 4. Update all images in the project to point to the new domain
- ...(newDomain !== domain
- ? [
- removeDomainFromVercel(domain),
- changeDomainForLinks(domain, newDomain),
- changeDomainForImages(domain, newDomain),
- ]
- : []),
- /*
- if the project is not a free plan:
- - if the domain is being set:
- - Set the root domain to the target in Redis
- - if the domain is being changed, also change the root domain key in Redis
- - if the domain is being unset:
- - delete the root domain key in Redis
- */
- project.plan !== "free" &&
- (target
- ? setRootDomain({
- domain,
- target,
- rewrite: type === "rewrite",
- ...(newDomain !== domain && {
- newDomain,
- }),
- })
- : redis.del(`root:${domain}`)),
- // if the domain is being set as the primary domain, set the current primary domain to false
- primary &&
- prisma.domain.updateMany({
- where: {
- projectId: project.id,
- primary: true,
- },
- data: {
- primary: false,
- },
- }),
- // Update the domain in the database along with its primary status
- prisma.domain.update({
- where: {
- slug: domain,
- },
- data: {
- ...(newDomain !== domain && {
- slug: newDomain,
- }),
- // same logic as the redis part above
- ...(project.plan !== "free" &&
- (target
- ? {
- target,
- }
- : {
- target: null,
- })),
- type,
- primary,
- },
- }),
- ]);
-
- return res.status(200).json(response);
-
- // DELETE /api/projects/[slug]/domains/[domain] delete a project's domain
- } else if (req.method === "DELETE") {
- const response = await deleteDomainAndLinks(domain);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["PUT", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
- },
- {
- requiredRole: ["owner"],
- },
-);
diff --git a/apps/web/pages/api/projects/[slug]/domains/[domain]/stats/[endpoint].ts b/apps/web/pages/api/projects/[slug]/domains/[domain]/stats/[endpoint].ts
deleted file mode 100644
index 5075abd317..0000000000
--- a/apps/web/pages/api/projects/[slug]/domains/[domain]/stats/[endpoint].ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import { IntervalProps, getStats } from "@/lib/stats";
-
-export default withProjectAuth(async (req, res, project) => {
- // GET /api/projects/[slug]/domains/[domain]/clicks - get # of clicks on root of domain (e.g. dub.sh, vercel.fyi)
- if (req.method === "GET") {
- const { domain, endpoint, interval } = req.query as {
- domain: string;
- endpoint: string;
- interval: IntervalProps;
- };
- if (
- (interval === "all" || interval === "90d") &&
- (!project || project.plan === "free")
- ) {
- return res.status(403).end("Forbidden: Require higher plan");
- }
-
- const response = await getStats({
- domain,
- key: "_root",
- endpoint,
- interval,
- });
-
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/domains/[domain]/verify.ts b/apps/web/pages/api/projects/[slug]/domains/[domain]/verify.ts
deleted file mode 100644
index 644304e965..0000000000
--- a/apps/web/pages/api/projects/[slug]/domains/[domain]/verify.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import {
- getConfigResponse,
- getDomainResponse,
- verifyDomain,
-} from "@/lib/api/domains";
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-import { DomainVerificationStatusProps } from "@/lib/types";
-
-export default withProjectAuth(async (req, res) => {
- // GET /api/projects/[slug]/domains/[domain]/verify - get domain verification status
- if (req.method === "GET") {
- const { slug, domain } = req.query as { slug: string; domain: string };
- let status: DomainVerificationStatusProps = "Valid Configuration";
-
- const [domainJson, configJson] = await Promise.all([
- getDomainResponse(domain),
- getConfigResponse(domain),
- ]);
-
- if (domainJson?.error?.code === "not_found") {
- // domain not found on Vercel project
- status = "Domain Not Found";
- return res
- .status(200)
- .json({ status, response: { configJson, domainJson } });
- } else if (domainJson.error) {
- status = "Unknown Error";
- return res
- .status(200)
- .json({ status, response: { configJson, domainJson } });
- }
-
- /**
- * Domain has DNS conflicts
- */
- if (configJson?.conflicts.length > 0) {
- status = "Conflicting DNS Records";
- return res.status(200).json({
- status,
- response: {
- configJson,
- domainJson,
- },
- });
- }
-
- /**
- * If domain is not verified, we try to verify now
- */
- if (!domainJson.verified) {
- status = "Pending Verification";
- const verificationJson = await verifyDomain(domain);
-
- if (verificationJson && verificationJson.verified) {
- /**
- * Domain was just verified
- */
- status = "Valid Configuration";
- }
-
- return res.status(200).json({
- status,
- response: {
- configJson,
- domainJson,
- verificationJson,
- },
- });
- }
-
- let prismaResponse: any = null;
- if (!configJson.misconfigured) {
- prismaResponse = await prisma.domain.update({
- where: {
- slug: domain,
- },
- data: {
- verified: true,
- lastChecked: new Date(),
- },
- });
- } else {
- status = "Invalid Configuration";
- prismaResponse = await prisma.domain.update({
- where: {
- slug: domain,
- },
- data: {
- verified: false,
- lastChecked: new Date(),
- },
- });
- }
-
- return res.status(200).json({
- status,
- response: { configJson, domainJson, prismaResponse },
- });
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/domains/index.ts b/apps/web/pages/api/projects/[slug]/domains/index.ts
deleted file mode 100644
index 456993ef7c..0000000000
--- a/apps/web/pages/api/projects/[slug]/domains/index.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import {
- addDomainToVercel,
- setRootDomain,
- validateDomain,
-} from "@/lib/api/domains";
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-export default withProjectAuth(async (req, res, project) => {
- // GET /api/projects/[slug]/domains – get all domains for a project
- if (req.method === "GET") {
- const domains = await prisma.domain.findMany({
- where: {
- projectId: project.id,
- },
- select: {
- slug: true,
- verified: true,
- primary: true,
- target: true,
- type: true,
- },
- });
- return res.status(200).json(domains);
-
- // POST /api/projects/[slug]/domains - add a domain
- } else if (req.method === "POST") {
- const { slug: domain, primary, target, type } = req.body;
- const validDomain = await validateDomain(domain, project.id);
- if (validDomain !== true) {
- return res.status(422).json({
- domainError: validDomain,
- });
- }
- const vercelResponse = await addDomainToVercel(domain);
- if (vercelResponse.error) {
- return res.status(422).json({
- domainError: vercelResponse.error.message,
- });
- }
- /*
- If the domain is being added, we need to:
- 1. Add the domain to Vercel
- 2. If there's a landing page set, update the root domain in Redis
- 3. If the domain is being set as the primary domain, set all other domains to not be the primary domain
- 4. Add the domain to the database along with its primary status
- */
- const response = await Promise.allSettled([
- target &&
- setRootDomain({
- domain,
- target,
- rewrite: type === "rewrite",
- }),
- primary &&
- prisma.domain.updateMany({
- where: {
- projectId: project.id,
- primary: true,
- },
- data: {
- primary: false,
- },
- }),
- prisma.domain.create({
- data: {
- slug: domain,
- target,
- type,
- projectId: project.id,
- primary,
- },
- }),
- ]);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "POST"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/exists.ts b/apps/web/pages/api/projects/[slug]/exists.ts
deleted file mode 100644
index ba36c3cd90..0000000000
--- a/apps/web/pages/api/projects/[slug]/exists.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { withUserAuth } from "@/lib/auth";
-import { isReservedKey } from "@/lib/edge-config";
-import prisma from "@/lib/prisma";
-import { DEFAULT_REDIRECTS } from "@dub/utils";
-import { NextApiRequest, NextApiResponse } from "next";
-
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
- const { slug } = req.query as { slug: string };
-
- // GET /api/projects/[slug]/exists – check if a project exists
- if (req.method === "GET") {
- if ((await isReservedKey(slug)) || DEFAULT_REDIRECTS[slug]) {
- return res.status(200).json(1);
- }
- const project = await prisma.project.findUnique({
- where: {
- slug,
- },
- select: {
- slug: true,
- },
- });
- if (project) {
- return res.status(200).json(1);
- } else {
- return res.status(200).json(0);
- }
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
- },
-);
diff --git a/apps/web/pages/api/projects/[slug]/import/bitly.ts b/apps/web/pages/api/projects/[slug]/import/bitly.ts
deleted file mode 100644
index ad4879879e..0000000000
--- a/apps/web/pages/api/projects/[slug]/import/bitly.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { addDomainToVercel } from "@/lib/api/domains";
-import { withProjectAuth } from "@/lib/auth";
-import { qstash } from "@/lib/cron";
-import prisma from "@/lib/prisma";
-import { BitlyGroupProps } from "@/lib/types";
-import { redis } from "@/lib/upstash";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-
-export default withProjectAuth(async (req, res, project) => {
- // get bitly groups and their respective domains
- if (req.method === "GET") {
- const accessToken = await redis.get(`import:bitly:${project.id}`);
- if (!accessToken) {
- return res.status(400).end("No Bitly access token found");
- }
-
- const response = await fetch(`https://api-ssl.bitly.com/v4/groups`, {
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${accessToken}`,
- },
- });
- const data = await response.json();
- if (data.message === "FORBIDDEN") {
- return res.status(403).end("Invalid Bitly access token");
- }
-
- const groups = data.groups
- // filter for active groups only
- .filter(({ is_active }) => is_active) as BitlyGroupProps[];
-
- const groupsWithTags = await Promise.all(
- groups.map(async (group) => ({
- ...group,
- tags: await fetch(
- `https://api-ssl.bitly.com/v4/groups/${group.guid}/tags`,
- {
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${accessToken}`,
- },
- },
- )
- .then((r) => r.json())
- .then((r) => r.tags),
- })),
- );
-
- return res.status(200).json(groupsWithTags);
-
- // create job to import links from bitly
- } else if (req.method === "POST") {
- const { selectedDomains, selectedGroupTags } = req.body;
- console.log({
- selectedDomains,
- selectedGroupTags,
- });
-
- // check if there are domains that are not in the project
- // if yes, add them to the project
- const domainsNotInProject = selectedDomains.filter(
- ({ domain }) => !project.domains?.find((d) => d.slug === domain),
- );
- if (domainsNotInProject.length > 0) {
- await Promise.allSettled([
- prisma.domain.createMany({
- data: domainsNotInProject.map(({ domain }) => ({
- slug: domain,
- target: null,
- type: "redirect",
- projectId: project.id,
- primary: false,
- })),
- skipDuplicates: true,
- }),
- domainsNotInProject.map(({ slug }) => addDomainToVercel(slug)),
- ]);
- }
-
- // convert data to array of groups with their respective domains
- const groups = selectedDomains.reduce((result, { domain, bitlyGroup }) => {
- const existingGroup = result.find(
- (item) => item.bitlyGroup === bitlyGroup,
- );
- if (existingGroup) {
- existingGroup.domains.push(domain);
- } else {
- result.push({
- bitlyGroup,
- domains: [domain],
- keepTags: selectedGroupTags.includes(bitlyGroup),
- });
- }
- return result;
- }, []);
-
- const response = await Promise.all(
- groups
- // only add groups that have at least 1 domain selected for import
- .filter(({ domains }) => domains.length > 0)
- .map(({ bitlyGroup, domains, keepTags }) =>
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/bitly`,
- body: {
- projectId: project.id,
- bitlyGroup,
- domains,
- keepTags,
- },
- }),
- ),
- );
- return res.status(200).json(response);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/import/short.ts b/apps/web/pages/api/projects/[slug]/import/short.ts
deleted file mode 100644
index 45fb836d8d..0000000000
--- a/apps/web/pages/api/projects/[slug]/import/short.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { addDomainToVercel } from "@/lib/api/domains";
-import { withProjectAuth } from "@/lib/auth";
-import { qstash } from "@/lib/cron";
-import prisma from "@/lib/prisma";
-import { ShortioDomainProps } from "@/lib/types";
-import { redis } from "@/lib/upstash";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-
-export default withProjectAuth(async (req, res, project) => {
- // get Short.io domains and links count
- if (req.method === "GET") {
- const accessToken = await redis.get(`import:short:${project.id}`);
- if (!accessToken) {
- return res.status(400).end("No Short.io access token found");
- }
-
- const response = await fetch(`https://api.short.io/api/domains`, {
- headers: {
- "Content-Type": "application/json",
- Authorization: accessToken as string,
- },
- });
- const data = await response.json();
- if (data.error === "Unauthorized") {
- return res.status(403).end("Invalid Short.io access token");
- }
-
- const domains = await Promise.all(
- data.map(async ({ id, hostname }: { id: number; hostname: string }) => ({
- id,
- domain: hostname,
- links: await fetch(
- `https://api-v2.short.cm/statistics/domain/${id}?period=total`,
- {
- headers: {
- "Content-Type": "application/json",
- Authorization: accessToken as string,
- },
- },
- )
- .then((r) => r.json())
- .then((data) => data.links - 1) // subtract 1 to exclude root domain
- .catch((e) => 0),
- })),
- );
-
- return res.status(200).json(domains);
-
- // set the user's Short.io access token in Redis
- } else if (req.method === "PUT") {
- const { apiKey } = req.body;
-
- const response = await redis.set(`import:short:${project.id}`, apiKey);
- return res.status(200).json(response);
-
- // create job to import links from Short.io
- } else if (req.method === "POST") {
- const { selectedDomains } = req.body as {
- selectedDomains: ShortioDomainProps[];
- };
- console.log({
- selectedDomains,
- });
-
- // check if there are domains that are not in the project
- // if yes, add them to the project
- const domainsNotInProject = selectedDomains.filter(
- ({ domain }) => !project.domains?.find((d) => d.slug === domain),
- );
- if (domainsNotInProject.length > 0) {
- await Promise.allSettled([
- prisma.domain.createMany({
- data: domainsNotInProject.map(({ domain }) => ({
- slug: domain,
- target: null,
- type: "redirect",
- projectId: project.id,
- primary: false,
- })),
- skipDuplicates: true,
- }),
- domainsNotInProject.map(({ domain }) => addDomainToVercel(domain)),
- ]);
- }
-
- const response = await Promise.all(
- selectedDomains.map(({ id, domain }) =>
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/short`,
- body: {
- projectId: project.id,
- domainId: id,
- domain,
- },
- }),
- ),
- );
-
- return res.status(200).json(response);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/index.ts b/apps/web/pages/api/projects/[slug]/index.ts
deleted file mode 100644
index 89867eb618..0000000000
--- a/apps/web/pages/api/projects/[slug]/index.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { deleteProject } from "@/lib/api/project";
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-export default withProjectAuth(
- async (req, res, project) => {
- // GET /api/projects/[slug] – get a specific project
- if (req.method === "GET") {
- return res.status(200).json(project);
-
- // PUT /api/projects/[slug] – edit a specific project
- } else if (req.method === "PUT") {
- const { name, slug } = req.body;
- try {
- const response = await prisma.project.update({
- where: {
- slug: project.slug,
- },
- data: {
- ...(name && { name }),
- ...(slug && { slug }),
- },
- });
- return res.status(200).json(response);
- } catch (error) {
- if (error.code === "P2002") {
- return res.status(422).end("Project slug already exists.");
- }
- }
- // DELETE /api/projects/[slug] – delete a project
- } else if (req.method === "DELETE") {
- const response = await deleteProject(project);
-
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
- },
- {
- requiredRole: ["owner"],
- excludeGet: true,
- },
-);
diff --git a/apps/web/pages/api/projects/[slug]/invites/accept.ts b/apps/web/pages/api/projects/[slug]/invites/accept.ts
deleted file mode 100644
index 4cd5822271..0000000000
--- a/apps/web/pages/api/projects/[slug]/invites/accept.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { withUserAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-export default withUserAuth(async (req, res, session) => {
- const { slug } = req.query as { slug: string };
- if (!slug || typeof slug !== "string") {
- return res.status(400).end("Missing or misconfigured project slug");
- }
- if (req.method === "POST") {
- const invite = await prisma.projectInvite.findFirst({
- where: {
- email: session.user.email,
- project: {
- slug,
- },
- },
- select: {
- expires: true,
- projectId: true,
- },
- });
- if (!invite) {
- return res.status(404).json({ error: "Invalid invitation" });
- } else if (invite.expires < new Date()) {
- return res.status(410).json({ error: "Invitation expired" });
- } else {
- const response = await Promise.all([
- prisma.projectUsers.create({
- data: {
- userId: session.user.id,
- role: "member",
- projectId: invite.projectId,
- },
- }),
- prisma.projectInvite.delete({
- where: {
- email_projectId: {
- email: session.user.email,
- projectId: invite.projectId,
- },
- },
- }),
- ]);
- return res.status(200).json(response);
- }
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/invites/index.tsx b/apps/web/pages/api/projects/[slug]/invites/index.tsx
deleted file mode 100644
index d91f6b6cb6..0000000000
--- a/apps/web/pages/api/projects/[slug]/invites/index.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { inviteUser } from "@/lib/api/users";
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-export default withProjectAuth(async (req, res, project, session) => {
- // GET /api/projects/[slug]/invites - Get all pending invites for a project
- if (req.method === "GET") {
- const invites = await prisma.projectInvite.findMany({
- where: {
- projectId: project.id,
- },
- select: {
- email: true,
- createdAt: true,
- },
- });
- return res.status(200).json(invites);
-
- // POST /api/projects/[slug]/invites – invite a teammate
- } else if (req.method === "POST") {
- const { email } = req.body;
-
- const alreadyInTeam = await prisma.projectUsers.findFirst({
- where: {
- projectId: project.id,
- user: {
- email,
- },
- },
- });
- if (alreadyInTeam) {
- return res.status(400).end("User already exists in this project.");
- }
-
- if (project.plan === "free") {
- const users = await prisma.projectUsers.count({
- where: {
- projectId: project.id,
- },
- });
- const invites = await prisma.projectInvite.count({
- where: {
- projectId: project.id,
- },
- });
- if (users + invites >= 3) {
- return res
- .status(400)
- .end("You've reached the maximum number of users for the free plan.");
- }
- }
-
- try {
- await inviteUser({
- email,
- project,
- session,
- });
- return res.status(200).json({ message: "Invite sent" });
- } catch (error) {
- return res.status(400).end(error.message);
- }
-
- // DELETE /api/projects/[slug]/invites – delete a pending invite
- } else if (req.method === "DELETE") {
- const { email } = req.query as { email?: string };
- if (!email) {
- return res.status(400).end("Missing email");
- }
- const response = await prisma.projectInvite.delete({
- where: {
- email_projectId: {
- email,
- projectId: project.id,
- },
- },
- });
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "POST", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/logo.ts b/apps/web/pages/api/projects/[slug]/logo.ts
deleted file mode 100644
index 18461bb271..0000000000
--- a/apps/web/pages/api/projects/[slug]/logo.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-import cloudinary from "cloudinary";
-
-export const config = {
- api: {
- bodyParser: {
- sizeLimit: "3mb",
- },
- },
-};
-
-export default withProjectAuth(
- async (req, res, project) => {
- // POST /api/projects/[slug]/logo – upload a new logo
- if (req.method === "POST") {
- const { image } = req.body;
-
- const { secure_url } = await cloudinary.v2.uploader.upload(image, {
- public_id: project.id,
- folder: "logos",
- overwrite: true,
- invalidate: true,
- });
-
- const response = await prisma.project.update({
- where: { id: project.id },
- data: { logo: secure_url },
- });
-
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["POST"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
- },
- {
- requiredRole: ["owner"],
- excludeGet: true,
- },
-);
diff --git a/apps/web/pages/api/projects/[slug]/saml.ts b/apps/web/pages/api/projects/[slug]/saml.ts
deleted file mode 100644
index fafbd4962b..0000000000
--- a/apps/web/pages/api/projects/[slug]/saml.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import jackson, { samlAudience } from "@/lib/jackson";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-
-export default withProjectAuth(
- async (req, res, project) => {
- // GET /api/projects/[slug]/saml – get all SAML connections
- if (req.method === "GET") {
- const { apiController } = await jackson();
-
- const connections = await apiController.getConnections({
- tenant: project.id,
- product: "Dub",
- });
-
- const response = {
- connections,
- issuer: samlAudience,
- acs:
- process.env.NODE_ENV === "production"
- ? "https://api.dub.co/auth/saml/callback"
- : `${APP_DOMAIN_WITH_NGROK}/api/auth/saml/callback`,
- };
-
- return res.status(200).json(response);
-
- // POST /api/projects/[slug]/saml – create a new SAML connection
- } else if (req.method === "POST") {
- const { metadataUrl, encodedRawMetadata } = req.body;
-
- const { apiController } = await jackson();
-
- const data = await apiController.createSAMLConnection({
- encodedRawMetadata,
- metadataUrl,
- defaultRedirectUrl: `${process.env.NEXTAUTH_URL}/auth/saml`,
- redirectUrl: process.env.NEXTAUTH_URL as string,
- tenant: project.id,
- product: "Dub",
- });
-
- return res.status(200).json(data);
-
- // DELETE /api/projects/[slug]/saml – delete all SAML connections
- } else if (req.method === "DELETE") {
- const { clientID, clientSecret } = req.query as {
- clientID: string;
- clientSecret: string;
- };
-
- const { apiController } = await jackson();
-
- const response = await apiController.deleteConnections({
- clientID,
- clientSecret,
- });
-
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "POST", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
- },
- {
- requiredRole: ["owner"],
- requiredPlan: ["enterprise"],
- excludeGet: true,
- },
-);
diff --git a/apps/web/pages/api/projects/[slug]/scim.ts b/apps/web/pages/api/projects/[slug]/scim.ts
deleted file mode 100644
index d90d2c9261..0000000000
--- a/apps/web/pages/api/projects/[slug]/scim.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import jackson from "@/lib/jackson";
-import { SAMLProviderProps } from "@/lib/types";
-
-export default withProjectAuth(
- async (req, res, project) => {
- const { directorySyncController } = await jackson();
-
- // GET /api/projects/[slug]/scim – get all SCIM directories
- if (req.method === "GET") {
- const { data, error } =
- await directorySyncController.directories.getByTenantAndProduct(
- project.id,
- "Dub",
- );
- if (error) {
- return res.status(500).end(error.message);
- }
-
- return res.status(200).json({
- directories: data,
- });
-
- // POST /api/projects/[slug]/scim – create a new SCIM directory
- } else if (req.method === "POST") {
- const { provider = "okta-scim-v2", currentDirectoryId } = req.body as {
- provider: SAMLProviderProps["scim"];
- currentDirectoryId?: string;
- };
-
- const [data, _] = await Promise.all([
- directorySyncController.directories.create({
- name: "Dub SCIM Directory",
- tenant: project.id,
- product: "Dub",
- type: provider,
- }),
- currentDirectoryId &&
- directorySyncController.directories.delete(currentDirectoryId),
- ]);
-
- return res.status(200).json(data);
-
- // DELETE /api/projects/[slug]/scim – delete a SCIM directory
- } else if (req.method === "DELETE") {
- const { directoryId } = req.query as {
- directoryId?: string;
- };
-
- if (!directoryId) {
- return res.status(400).end(`Missing SCIM directory ID`);
- }
-
- const response = await directorySyncController.directories.delete(
- directoryId,
- );
-
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "POST", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
- },
- {
- requiredRole: ["owner"],
- requiredPlan: ["enterprise"],
- excludeGet: true,
- },
-);
diff --git a/apps/web/pages/api/projects/[slug]/tags/[id].ts b/apps/web/pages/api/projects/[slug]/tags/[id].ts
deleted file mode 100644
index cccbc51e09..0000000000
--- a/apps/web/pages/api/projects/[slug]/tags/[id].ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-export default withProjectAuth(async (req, res) => {
- const { id } = req.query as { id: string };
- // PUT /api/projects/[slug]/tags/[id] – update a tag for a project
- if (req.method === "PUT") {
- const { name, color } = req.body;
- const response = await prisma.tag.update({
- where: {
- id,
- },
- data: {
- name,
- color,
- },
- });
- return res.status(200).json(response);
-
- // DELETE /api/projects/[slug]/tags/[id] – delete a tag for a project
- } else if (req.method === "DELETE") {
- const response = await prisma.tag.delete({
- where: {
- id,
- },
- });
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["PUT", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/tags/index.ts b/apps/web/pages/api/projects/[slug]/tags/index.ts
deleted file mode 100644
index bc2f3e23e1..0000000000
--- a/apps/web/pages/api/projects/[slug]/tags/index.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-import { randomBadgeColor } from "@/ui/links/tag-badge";
-
-export default withProjectAuth(async (req, res, project) => {
- // GET /api/projects/[slug]/tags - get all tags for a project
- if (req.method === "GET") {
- const tags = await prisma.tag.findMany({
- where: {
- projectId: project.id,
- },
- select: {
- id: true,
- name: true,
- color: true,
- },
- orderBy: {
- name: "asc",
- },
- });
- return res.status(200).json(tags);
- } else if (req.method === "POST") {
- const tagsCount = await prisma.tag.count({
- where: {
- projectId: project.id,
- },
- });
- if (project.plan === "free" && tagsCount >= 3) {
- return res
- .status(403)
- .end(
- "You can only create 3 tags in the Free plan. Upgrade to Pro to create unlimited tags.",
- );
- }
- const { tag } = req.body;
- const response = await prisma.tag.create({
- data: {
- name: tag,
- color: randomBadgeColor(),
- projectId: project.id,
- },
- });
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "POST"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/projects/[slug]/users.ts b/apps/web/pages/api/projects/[slug]/users.ts
deleted file mode 100644
index 3d5afecd17..0000000000
--- a/apps/web/pages/api/projects/[slug]/users.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-export default withProjectAuth(
- async (req, res, project) => {
- // GET /api/projects/[slug]/users – get users for a specific project
- if (req.method === "GET") {
- const users = await prisma.projectUsers.findMany({
- where: {
- projectId: project.id,
- },
- select: {
- role: true,
- user: {
- select: {
- id: true,
- name: true,
- email: true,
- image: true,
- },
- },
- createdAt: true,
- },
- });
- return res.status(200).json(
- users.map((u) => ({
- ...u.user,
- role: u.role,
- })),
- );
- } else if (req.method === "PUT") {
- const { userId, role } = req.body as {
- userId?: string;
- role?: "owner" | "member";
- };
- if (!userId || !role) {
- return res.status(400).end("Missing userId or role");
- }
- const response = await prisma.projectUsers.update({
- where: {
- userId_projectId: {
- projectId: project.id,
- userId,
- },
- },
- data: {
- role,
- },
- });
-
- return res.status(200).json(response);
- } else if (req.method === "DELETE") {
- // DELETE /api/projects/[slug]/users – remove a user from a project
- const { userId } = req.query as { userId?: string };
- if (!userId) {
- return res.status(400).end("Missing userId");
- }
-
- const projectUser = await prisma.projectUsers.findUnique({
- where: {
- userId_projectId: {
- projectId: project.id,
- userId,
- },
- },
- select: {
- role: true,
- },
- });
-
- if (projectUser?.role === "owner") {
- return res
- .status(400)
- .end(
- "Cannot remove owner from project. Please transfer ownership to another user first.",
- );
- }
-
- const response = await prisma.projectUsers.delete({
- where: {
- userId_projectId: {
- projectId: project.id,
- userId,
- },
- },
- });
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
- },
- {
- requiredRole: ["owner"],
- excludeGet: true,
- },
-);
diff --git a/apps/web/pages/api/user/index.ts b/apps/web/pages/api/user/index.ts
deleted file mode 100644
index 9b6af7c111..0000000000
--- a/apps/web/pages/api/user/index.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { deleteUserLinks } from "@/lib/api/links";
-import { withUserAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-import cloudinary from "cloudinary";
-
-export const config = {
- api: {
- bodyParser: {
- sizeLimit: "3mb",
- },
- },
-};
-
-export default withUserAuth(async (req, res, session) => {
- // PUT /api/user – edit a specific user
- if (req.method === "PUT") {
- let { name, email, image } = req.body;
- try {
- if (image) {
- const { secure_url } = await cloudinary.v2.uploader.upload(image, {
- public_id: session.user.id,
- folder: "avatars",
- overwrite: true,
- invalidate: true,
- });
- image = secure_url;
- }
- const response = await prisma.user.update({
- where: {
- id: session.user.id,
- },
- data: {
- ...(name && { name }),
- ...(email && { email }),
- ...(image && { image }),
- },
- });
- return res.status(200).json(response);
- } catch (error) {
- if (error.code === "P2002") {
- return res.status(422).end("Email is already in use.");
- }
- }
- // DELETE /api/user – delete a specific user
- } else if (req.method === "DELETE") {
- const userIsOwnerOfProjects = await prisma.projectUsers.findMany({
- where: {
- userId: session.user.id,
- role: "owner",
- },
- });
- if (userIsOwnerOfProjects.length > 0) {
- return res
- .status(422)
- .end(
- "You must transfer ownership of your projects or delete them before you can delete your account.",
- );
- } else {
- const [deleteLinks, _] = await Promise.allSettled([
- deleteUserLinks(session.user.id),
- cloudinary.v2.uploader.destroy(`avatars/${session?.user?.id}`, {
- invalidate: true,
- }),
- ]);
- const response = await prisma.user.delete({
- where: {
- id: session.user.id,
- },
- });
- return res.status(200).json({ deleteLinks, response });
- }
- } else {
- res.setHeader("Allow", ["PUT", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/pages/api/user/tokens.ts b/apps/web/pages/api/user/tokens.ts
deleted file mode 100644
index c7d271a931..0000000000
--- a/apps/web/pages/api/user/tokens.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { hashToken, withUserAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-import { customAlphabet } from "nanoid";
-
-const generateToken = customAlphabet(
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
- 24,
-);
-
-export default withUserAuth(async (req, res, session) => {
- // GET /api/user/tokens – get all tokens for a specific user
- if (req.method === "GET") {
- const tokens = await prisma.token.findMany({
- where: {
- userId: session.user.id,
- },
- select: {
- id: true,
- name: true,
- partialKey: true,
- createdAt: true,
- lastUsed: true,
- },
- orderBy: [
- {
- lastUsed: "desc",
- },
- {
- createdAt: "desc",
- },
- ],
- });
- return res.status(200).json(tokens);
-
- // POST /api/user/tokens – create a new token for a specific user
- } else if (req.method === "POST") {
- const { name } = req.body;
- const token = generateToken();
- const hashedKey = hashToken(token, {
- noSecret: true,
- });
- // take first 3 and last 4 characters of the key
- const partialKey = `${token.slice(0, 3)}...${token.slice(-4)}`;
-
- await prisma.token.create({
- data: {
- name,
- hashedKey,
- partialKey,
- userId: session.user.id,
- },
- });
- return res.status(200).json({ token });
-
- // DELETE /api/user/tokens – delete a token for a specific user
- } else if (req.method === "DELETE") {
- const { id } = req.query;
- if (!id || typeof id !== "string") {
- return res.status(400).end("Invalid token ID");
- }
- const response = await prisma.token.delete({
- where: {
- id,
- userId: session.user.id,
- },
- });
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["PUT", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
diff --git a/apps/web/ui/domains/domain-card.tsx b/apps/web/ui/domains/domain-card.tsx
index 49b111711c..4a9db94186 100644
--- a/apps/web/ui/domains/domain-card.tsx
+++ b/apps/web/ui/domains/domain-card.tsx
@@ -29,7 +29,7 @@ export default function DomainCard({ props }: { props: DomainProps }) {
});
const { data: clicks } = useSWR<number>(
- slug && `/api/projects/${slug}/domains/${domain}/stats/clicks`,
+ slug && `/api/projects/${slug}/stats/clicks?domain=${domain}&key=_root`,
fetcher,
{
dedupingInterval: 15000,
diff --git a/apps/web/ui/domains/domain-configuration.tsx b/apps/web/ui/domains/domain-configuration.tsx
index 98f1d59121..ce28fd64d5 100644
--- a/apps/web/ui/domains/domain-configuration.tsx
+++ b/apps/web/ui/domains/domain-configuration.tsx
@@ -157,26 +157,34 @@ const DnsRecord = ({
<div>
<p className="text-sm font-bold">Type</p>
{records.map((record) => (
- <p className="mt-2 font-mono text-sm">{record.type}</p>
+ <p key={record.type} className="mt-2 font-mono text-sm">
+ {record.type}
+ </p>
))}
</div>
<div>
<p className="text-sm font-bold">Name</p>
{records.map((record) => (
- <p className="mt-2 font-mono text-sm">{record.name}</p>
+ <p key={record.name} className="mt-2 font-mono text-sm">
+ {record.name}
+ </p>
))}
</div>
<div>
<p className="text-sm font-bold">Value</p>
{records.map((record) => (
- <p className="mt-2 font-mono text-sm">{record.value}</p>
+ <p key={record.value} className="mt-2 font-mono text-sm">
+ {record.value}
+ </p>
))}
</div>
{hasTtl && (
<div>
<p className="text-sm font-bold">TTL</p>
{records.map((record) => (
- <p className="mt-2 font-mono text-sm">{record.ttl}</p>
+ <p key={record.ttl} className="mt-2 font-mono text-sm">
+ {record.ttl}
+ </p>
))}
</div>
)}
diff --git a/apps/web/ui/links/link-filters.tsx b/apps/web/ui/links/link-filters.tsx
index 2e9995dbf8..08abc9f9b5 100644
--- a/apps/web/ui/links/link-filters.tsx
+++ b/apps/web/ui/links/link-filters.tsx
@@ -446,7 +446,9 @@ const TagPopover = ({ tag, count }: { tag: TagProps; count: number }) => {
};
return processing ? (
- <LoadingCircle />
+ <div className="flex h-6 items-center justify-center">
+ <LoadingCircle />
+ </div>
) : (
<Popover
content={
diff --git a/apps/web/ui/modals/accept-invite-modal.tsx b/apps/web/ui/modals/accept-invite-modal.tsx
index 86992b45dd..bc992af08a 100644
--- a/apps/web/ui/modals/accept-invite-modal.tsx
+++ b/apps/web/ui/modals/accept-invite-modal.tsx
@@ -2,7 +2,7 @@ import useProject from "@/lib/swr/use-project";
import { LoadingDots, Logo, Modal } from "@dub/ui";
import va from "@vercel/analytics";
import Link from "next/link";
-import { useParams } from "next/navigation";
+import { useParams, useRouter } from "next/navigation";
import {
Dispatch,
SetStateAction,
@@ -20,6 +20,7 @@ function AcceptInviteModal({
showAcceptInviteModal: boolean;
setShowAcceptInviteModal: Dispatch<SetStateAction<boolean>>;
}) {
+ const router = useRouter();
const { slug } = useParams() as { slug: string };
const [accepting, setAccepting] = useState(false);
const { error } = useProject();
@@ -54,13 +55,12 @@ function AcceptInviteModal({
va.track("User accepted project invite", {
project: slug,
});
- await mutate(
- (key) =>
- typeof key === "string" &&
- key.startsWith(`/api/projects`),
- undefined,
- { revalidate: true },
- );
+ await Promise.all([
+ mutate(`/api/projects/${slug}`),
+ mutate(`/api/projects/${slug}/domains`),
+ router.refresh(),
+ ]);
+ setShowAcceptInviteModal(false);
toast.success("You now are a part of this project!");
});
}}
diff --git a/apps/web/ui/modals/add-edit-domain-modal.tsx b/apps/web/ui/modals/add-edit-domain-modal.tsx
index bc18da0596..8221705042 100644
--- a/apps/web/ui/modals/add-edit-domain-modal.tsx
+++ b/apps/web/ui/modals/add-edit-domain-modal.tsx
@@ -49,14 +49,12 @@ function AddEditDomainModal({
const [debouncedDomain] = useDebounce(domain, 500);
useEffect(() => {
if (debouncedDomain.length > 0 && debouncedDomain !== props?.slug) {
- fetch(`/api/projects/${slug}/domains/${debouncedDomain}/exists`).then(
- async (res) => {
- if (res.status === 200) {
- const exists = await res.json();
- setDomainError(exists === 1 ? "Domain is already in use." : null);
- }
- },
- );
+ fetch(`/api/domains/${debouncedDomain}/exists`).then(async (res) => {
+ if (res.status === 200) {
+ const exists = await res.json();
+ setDomainError(exists === 1 ? "Domain is already in use." : null);
+ }
+ });
}
}, [debouncedDomain]);
diff --git a/apps/web/ui/modals/import-bitly-modal.tsx b/apps/web/ui/modals/import-bitly-modal.tsx
index 8b92e1c975..ab15224328 100644
--- a/apps/web/ui/modals/import-bitly-modal.tsx
+++ b/apps/web/ui/modals/import-bitly-modal.tsx
@@ -125,9 +125,9 @@ function ImportBitlyModal({
router.push(`/${slug}`);
setPollLinks(true);
} else {
+ setImporting(false);
throw new Error();
}
- setImporting(false);
}),
{
loading: "Adding links to import queue...",
diff --git a/apps/web/ui/modals/import-short-modal.tsx b/apps/web/ui/modals/import-short-modal.tsx
index fe53b832ef..67668f271f 100644
--- a/apps/web/ui/modals/import-short-modal.tsx
+++ b/apps/web/ui/modals/import-short-modal.tsx
@@ -124,9 +124,9 @@ function ImportShortModal({
router.push(`/${slug}`);
setPollLinks(true);
} else {
+ setImporting(false);
throw new Error();
}
- setImporting(false);
}),
{
loading: "Adding links to import queue...",
diff --git a/apps/web/ui/modals/remove-teammate-modal.tsx b/apps/web/ui/modals/remove-teammate-modal.tsx
index 0b317d1312..380b263efd 100644
--- a/apps/web/ui/modals/remove-teammate-modal.tsx
+++ b/apps/web/ui/modals/remove-teammate-modal.tsx
@@ -85,6 +85,7 @@ function RemoveTeammateModal({
<Button
text="Confirm"
variant="danger"
+ autoFocus
loading={removing}
onClick={() => {
setRemoving(true);
diff --git a/apps/web/ui/modals/scim-modal.tsx b/apps/web/ui/modals/scim-modal.tsx
index 027aee7c8d..a649174d8a 100644
--- a/apps/web/ui/modals/scim-modal.tsx
+++ b/apps/web/ui/modals/scim-modal.tsx
@@ -101,6 +101,7 @@ function SCIMModal({
setSubmitting(false);
});
}}
+ className="flex flex-col space-y-4"
>
<div>
<div className="flex items-center space-x-1">
@@ -144,18 +145,17 @@ function SCIMModal({
</option>
))}
</select>
+ {currentProvider && (
+ <a
+ href={`${HOME_DOMAIN}/help/article/${currentProvider.saml}-scim`}
+ target="_blank"
+ className="ml-2 mt-2 block text-sm text-gray-500 underline"
+ >
+ Read the guide on {currentProvider.name} SCIM
+ </a>
+ )}
</div>
- {currentProvider && (
- <a
- href={`${HOME_DOMAIN}/help/article/${currentProvider.saml}-scim`}
- target="_blank"
- className="ml-2 mt-2 block text-sm text-gray-500 underline"
- >
- Read the guide on {currentProvider.name} SCIM
- </a>
- )}
-
{currentProvider && selectedProvider === provider && (
<div className="mt-4 flex flex-col space-y-4">
<div className="w-full border-t border-gray-200" />
@@ -258,7 +258,6 @@ function SCIMModal({
</div>
)}
<Button
- className="mt-4"
text="Save changes"
loading={submitting}
disabled={!currentProvider || currentProvider.scim === provider}
diff --git a/apps/web/ui/stats/index.tsx b/apps/web/ui/stats/index.tsx
index e0ab6ddc8b..96fbdfd7b3 100644
--- a/apps/web/ui/stats/index.tsx
+++ b/apps/web/ui/stats/index.tsx
@@ -67,7 +67,7 @@ export default function Stats({
if (slug) {
return {
basePath: `/${slug}/analytics`,
- baseApiPath: `/api/stats`,
+ baseApiPath: `/api/projects/${slug}/stats`,
domain: domainSlug,
};
// Generic Dub.sh links analytics page, e.g. app.dub.co/analytics?domain=dub.sh&key=github
@@ -89,7 +89,6 @@ export default function Stats({
const queryString = useMemo(() => {
return new URLSearchParams({
- ...(slug && { slug }),
domain: domain!,
...(key && { key }),
...(interval && { interval }),