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.

remove server actions

Steven Tey6d36642b1d0a
diff --git a/apps/web/app/admin.dub.co/actions.ts b/apps/web/app/admin.dub.co/actions.ts
deleted file mode 100644
index 91c59e2ea2..0000000000
--- a/apps/web/app/admin.dub.co/actions.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-"use server";
-
-import { addDomainToVercel, removeDomainFromVercel } from "@/lib/api/domains";
-import { deleteProjectAdmin } from "@/lib/api/projects";
-import { getSession, hashToken } from "@/lib/auth";
-import { unsubscribe } from "@/lib/flodesk";
-import prisma from "@/lib/prisma";
-import { DUB_DOMAINS_ARRAY, DUB_PROJECT_ID } from "@dub/utils";
-import { get } from "@vercel/edge-config";
-import cloudinary from "cloudinary";
-import { randomBytes } from "crypto";
-
-export async function isAdmin() {
- const session = await getSession();
- if (!session?.user) return false;
- const response = await prisma.projectUsers.findUnique({
- where: {
- userId_projectId: {
- // @ts-ignore
- userId: session.user.id,
- projectId: DUB_PROJECT_ID,
- },
- },
- });
- if (!response) return false;
- return true;
-}
-
-async function getImpersonateUrl(email: string) {
- const token = randomBytes(32).toString("hex");
-
- await prisma.verificationToken.create({
- data: {
- identifier: email,
- token: hashToken(token),
- expires: new Date(Date.now() + 60000),
- },
- });
-
- const params = new URLSearchParams({
- callbackUrl: process.env.NEXTAUTH_URL as string,
- email,
- token,
- });
-
- return `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
-}
-
-export async function getUserOrProjectOwner(data: FormData) {
- const email = data.get("email") as string;
- const slug = data.get("slug") as string;
-
- if (!(await isAdmin())) {
- return {
- error: "Unauthorized",
- };
- }
-
- const response = await prisma.user.findFirst({
- where: email
- ? { email }
- : {
- projects: {
- some: {
- project: {
- slug,
- },
- role: "owner",
- },
- },
- },
- select: {
- email: true,
- links: {
- where: {
- domain: {
- in: DUB_DOMAINS_ARRAY,
- },
- },
- select: {
- domain: true,
- },
- },
- projects: {
- select: {
- project: {
- select: {
- name: true,
- slug: true,
- plan: true,
- usage: true,
- _count: {
- select: {
- domains: true,
- links: true,
- },
- },
- },
- },
- },
- },
- },
- });
-
- if (!response?.email) {
- return {
- error: "No user found",
- };
- }
-
- return {
- email: response.email,
- // object with domain slugs as keys and the count of links as values
- defaultDomainLinks: response.links.reduce(
- (acc, { domain }) => {
- if (acc[domain]) {
- acc[domain]++;
- } else {
- acc[domain] = 1;
- }
- return acc;
- },
- {} as Record<string, number>,
- ),
- projects: response.projects.map(({ project }) => ({
- ...project,
- clicks: project.usage,
- domains: project._count.domains,
- links: project._count.links,
- })),
- impersonateUrl: await getImpersonateUrl(response.email),
- };
-}
-
-export async function banUser(data: FormData) {
- const email = data.get("email") as string;
-
- if (!(await isAdmin())) {
- return {
- error: "Unauthorized",
- };
- }
-
- const user = await prisma.user.findUnique({
- where: {
- email,
- },
- select: {
- id: true,
- email: true,
- projects: {
- where: {
- role: "owner",
- },
- select: {
- project: {
- select: {
- id: true,
- slug: true,
- logo: true,
- stripeId: true,
- },
- },
- },
- },
- },
- });
-
- if (!user?.email) {
- return {
- error: "No user found",
- };
- }
-
- const blacklistedEmails = (await get("emails")) as string[];
-
- await Promise.allSettled(
- user.projects.map(({ project }) =>
- deleteProjectAdmin({
- id: project.id,
- slug: project.slug,
- stripeId: project.stripeId || null,
- logo: project.logo || null,
- }),
- ),
- );
-
- await Promise.allSettled([
- prisma.user.delete({
- where: {
- id: user.id,
- },
- }),
- cloudinary.v2.uploader.destroy(`avatars/${user.id}`, {
- invalidate: true,
- }),
- unsubscribe(user.email),
- fetch(
- `https://api.vercel.com/v1/edge-config/${process.env.EDGE_CONFIG_ID}/items?teamId=${process.env.TEAM_ID_VERCEL}`,
- {
- method: "PATCH",
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- items: [
- {
- operation: "update",
- key: "emails",
- value: [...blacklistedEmails, email],
- },
- ],
- }),
- },
- ),
- ]);
-
- return true;
-}
-
-export async function refreshDomain(data: FormData) {
- const domain = data.get("domain") as string;
-
- if (!(await isAdmin())) {
- return {
- error: "Unauthorized",
- };
- }
-
- const remove = await removeDomainFromVercel(domain);
- const add = await addDomainToVercel(domain);
-
- console.log({ remove, add });
-
- return true;
-}
diff --git a/apps/web/app/admin.dub.co/components/impersonate-project.tsx b/apps/web/app/admin.dub.co/components/impersonate-project.tsx
index 65fd2f773b..1b67ac1a3d 100644
--- a/apps/web/app/admin.dub.co/components/impersonate-project.tsx
+++ b/apps/web/app/admin.dub.co/components/impersonate-project.tsx
@@ -5,7 +5,6 @@ import { cn } from "@dub/utils";
import { useState } from "react";
import { useFormStatus } from "react-dom";
import { toast } from "sonner";
-import { getUserOrProjectOwner } from "../actions";
import UserInfo, { UserInfoProps } from "./user-info";
export default function ImpersonateProject() {
@@ -14,16 +13,22 @@ export default function ImpersonateProject() {
return (
<div className="flex flex-col space-y-5">
<form
- action={(data) =>
- getUserOrProjectOwner(data).then((res) => {
- if (res.error) {
- toast.error(res.error);
- } else {
- // @ts-ignore
- setData(res);
- }
+ action={async (formData) => {
+ await fetch("/api/admin/impersonate", {
+ method: "POST",
+ body: JSON.stringify({
+ slug: formData.get("slug"),
+ }),
})
- }
+ .then((res) => res.json())
+ .then((res) => {
+ if (res.error) {
+ toast.error(res.error);
+ } else {
+ setData(res);
+ }
+ });
+ }}
>
<Form />
</form>
diff --git a/apps/web/app/admin.dub.co/components/impersonate-user.tsx b/apps/web/app/admin.dub.co/components/impersonate-user.tsx
index 2753c1606f..3e7a98d97f 100644
--- a/apps/web/app/admin.dub.co/components/impersonate-user.tsx
+++ b/apps/web/app/admin.dub.co/components/impersonate-user.tsx
@@ -5,7 +5,6 @@ import { cn } from "@dub/utils";
import { useState } from "react";
import { useFormStatus } from "react-dom";
import { toast } from "sonner";
-import { banUser, getUserOrProjectOwner } from "../actions";
import UserInfo, { UserInfoProps } from "./user-info";
export default function ImpersonateUser() {
@@ -14,22 +13,28 @@ export default function ImpersonateUser() {
return (
<div className="flex flex-col space-y-5">
<form
- action={(data) =>
- getUserOrProjectOwner(data).then((res) => {
- if (res.error) {
- toast.error(res.error);
- } else {
- // @ts-ignore
- setData(res);
- }
+ action={async (formData) => {
+ await fetch("/api/admin/impersonate", {
+ method: "POST",
+ body: JSON.stringify({
+ email: formData.get("email"),
+ }),
})
- }
+ .then((res) => res.json())
+ .then((res) => {
+ if (res.error) {
+ toast.error(res.error);
+ } else {
+ setData(res);
+ }
+ });
+ }}
>
<Form />
</form>
{data && (
<form
- action={(formData) => {
+ action={async (formData) => {
if (
!confirm(
`This will ban the user ${data.email} and delete all their projects and links. Are you sure?`,
@@ -37,8 +42,18 @@ export default function ImpersonateUser() {
) {
return;
}
- banUser(formData).then(() => {
- toast.success("Successfully banned user");
+ await fetch("/api/admin/ban", {
+ method: "POST",
+ body: JSON.stringify({
+ email: data.email,
+ }),
+ }).then(async (res) => {
+ if (res.ok) {
+ toast.success("User has been banned");
+ } else {
+ const error = await res.text();
+ toast.error(error);
+ }
});
}}
>
diff --git a/apps/web/app/admin.dub.co/components/refresh-domain.tsx b/apps/web/app/admin.dub.co/components/refresh-domain.tsx
index 52df3b0af0..807537f13d 100644
--- a/apps/web/app/admin.dub.co/components/refresh-domain.tsx
+++ b/apps/web/app/admin.dub.co/components/refresh-domain.tsx
@@ -5,7 +5,6 @@ import { cn } from "@dub/utils";
import { useState } from "react";
import { useFormStatus } from "react-dom";
import { toast } from "sonner";
-import { refreshDomain } from "../actions";
import { UserInfoProps } from "./user-info";
export default function RefreshDomain() {
@@ -14,10 +13,21 @@ export default function RefreshDomain() {
return (
<div className="flex flex-col space-y-5">
<form
- action={(data) =>
- refreshDomain(data).then(() => {
- toast.success("Domain refreshed");
+ action={async (data) =>
+ await fetch("/api/admin/refresh-domain", {
+ method: "POST",
+ body: JSON.stringify({
+ domain: data.get("domain"),
+ }),
})
+ .then((res) => res.json())
+ .then((res) => {
+ if (res.error) {
+ toast.error(res.error);
+ } else {
+ toast.success("Domain has been refreshed");
+ }
+ })
}
>
<Form />
diff --git a/apps/web/app/api/admin/ban/route.ts b/apps/web/app/api/admin/ban/route.ts
new file mode 100644
index 0000000000..e2f773c7b9
--- /dev/null
+++ b/apps/web/app/api/admin/ban/route.ts
@@ -0,0 +1,87 @@
+import { deleteProjectAdmin } from "@/lib/api/projects";
+import { withAdmin } from "@/lib/auth";
+import { unsubscribe } from "@/lib/flodesk";
+import prisma from "@/lib/prisma";
+import { get } from "@vercel/edge-config";
+import cloudinary from "cloudinary";
+import { NextResponse } from "next/server";
+
+// POST /api/admin/ban
+export const POST = withAdmin(async ({ req }) => {
+ const { email } = await req.json();
+
+ const user = await prisma.user.findUnique({
+ where: {
+ email,
+ },
+ select: {
+ id: true,
+ email: true,
+ projects: {
+ where: {
+ role: "owner",
+ },
+ select: {
+ project: {
+ select: {
+ id: true,
+ slug: true,
+ logo: true,
+ stripeId: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!user?.email) {
+ return new Response("No user found", { status: 404 });
+ }
+
+ const blacklistedEmails = (await get("emails")) as string[];
+
+ await Promise.allSettled(
+ user.projects.map(({ project }) =>
+ deleteProjectAdmin({
+ id: project.id,
+ slug: project.slug,
+ stripeId: project.stripeId || null,
+ logo: project.logo || null,
+ }),
+ ),
+ );
+
+ await Promise.allSettled([
+ prisma.user.delete({
+ where: {
+ id: user.id,
+ },
+ }),
+ cloudinary.v2.uploader.destroy(`avatars/${user.id}`, {
+ invalidate: true,
+ }),
+ unsubscribe(user.email),
+ fetch(
+ `https://api.vercel.com/v1/edge-config/${process.env.EDGE_CONFIG_ID}/items?teamId=${process.env.TEAM_ID_VERCEL}`,
+ {
+ method: "PATCH",
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ items: [
+ {
+ operation: "update",
+ key: "emails",
+ value: [...blacklistedEmails, email],
+ },
+ ],
+ }),
+ },
+ ),
+ ]);
+
+ return NextResponse.json({ success: true });
+});
diff --git a/apps/web/app/api/admin/impersonate/route.ts b/apps/web/app/api/admin/impersonate/route.ts
new file mode 100644
index 0000000000..9198098d97
--- /dev/null
+++ b/apps/web/app/api/admin/impersonate/route.ts
@@ -0,0 +1,105 @@
+import { hashToken, withAdmin } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { DUB_DOMAINS_ARRAY } from "@dub/utils";
+import { randomBytes } from "crypto";
+import { NextResponse } from "next/server";
+
+// POST /api/admin/impersonate
+export const POST = withAdmin(async ({ req }) => {
+ const { email, slug } = await req.json();
+
+ const response = await prisma.user.findFirst({
+ where: email
+ ? { email }
+ : {
+ projects: {
+ some: {
+ project: {
+ slug,
+ },
+ role: "owner",
+ },
+ },
+ },
+ select: {
+ email: true,
+ links: {
+ where: {
+ domain: {
+ in: DUB_DOMAINS_ARRAY,
+ },
+ },
+ select: {
+ domain: true,
+ },
+ },
+ projects: {
+ select: {
+ project: {
+ select: {
+ name: true,
+ slug: true,
+ plan: true,
+ usage: true,
+ _count: {
+ select: {
+ domains: true,
+ links: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!response?.email) {
+ return new Response("User not found", { status: 404 });
+ }
+
+ const data = {
+ email: response.email,
+ // object with domain slugs as keys and the count of links as values
+ defaultDomainLinks: response.links.reduce(
+ (acc, { domain }) => {
+ if (acc[domain]) {
+ acc[domain]++;
+ } else {
+ acc[domain] = 1;
+ }
+ return acc;
+ },
+ {} as Record<string, number>,
+ ),
+ projects: response.projects.map(({ project }) => ({
+ ...project,
+ clicks: project.usage,
+ domains: project._count.domains,
+ links: project._count.links,
+ })),
+ impersonateUrl: await getImpersonateUrl(response.email),
+ };
+
+ return NextResponse.json(data);
+});
+
+async function getImpersonateUrl(email: string) {
+ const token = randomBytes(32).toString("hex");
+
+ await prisma.verificationToken.create({
+ data: {
+ identifier: email,
+ token: hashToken(token),
+ expires: new Date(Date.now() + 60000),
+ },
+ });
+
+ const params = new URLSearchParams({
+ callbackUrl: process.env.NEXTAUTH_URL as string,
+ email,
+ token,
+ });
+
+ return `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
+}
diff --git a/apps/web/app/api/admin/refresh-domain/route.ts b/apps/web/app/api/admin/refresh-domain/route.ts
new file mode 100644
index 0000000000..f22d1c186e
--- /dev/null
+++ b/apps/web/app/api/admin/refresh-domain/route.ts
@@ -0,0 +1,15 @@
+import { addDomainToVercel, removeDomainFromVercel } from "@/lib/api/domains";
+import { withAdmin } from "@/lib/auth";
+import { NextResponse } from "next/server";
+
+// POST /api/admin/refresh-domain
+export const POST = withAdmin(async ({ req }) => {
+ const { domain } = await req.json();
+
+ const remove = await removeDomainFromVercel(domain);
+ const add = await addDomainToVercel(domain);
+
+ console.log({ remove, add });
+
+ return NextResponse.json({ success: true });
+});
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index 7f17ee38c4..f0e3824af8 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -1,8 +1,12 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import prisma from "@/lib/prisma";
-import { API_DOMAIN, getSearchParams, isDubDomain } from "@dub/utils";
+import {
+ API_DOMAIN,
+ DUB_PROJECT_ID,
+ getSearchParams,
+ isDubDomain,
+} from "@dub/utils";
import { Link as LinkProps } from "@prisma/client";
-import { isAdmin } from "app/admin.dub.co/actions";
import { createHash } from "crypto";
import { getServerSession } from "next-auth/next";
import { exceededLimitError } from "../api/errors";
@@ -549,7 +553,20 @@ interface WithAdminHandler {
export const withAdmin =
(handler: WithAdminHandler) =>
async (req: Request, { params }: { params: Record<string, string> }) => {
- if (!(await isAdmin())) {
+ const session = await getSession();
+ if (!session?.user) {
+ return new Response("Unauthorized: Login required.", { status: 401 });
+ }
+
+ const response = await prisma.projectUsers.findUnique({
+ where: {
+ userId_projectId: {
+ userId: session.user.id,
+ projectId: DUB_PROJECT_ID,
+ },
+ },
+ });
+ if (!response) {
return new Response("Unauthorized: Not an admin.", { status: 401 });
}