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.

improve admin

Steven Tey478a5e1c4854
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx
index bfcd7c1768..44a74b3f19 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx
@@ -18,7 +18,7 @@ export function ImpersonateUser() {
await fetch("/api/admin/impersonate", {
method: "POST",
body: JSON.stringify({
- email: formData.get("email"),
+ query: formData.get("query"),
}),
}).then(async (res) => {
if (res.ok) {
@@ -89,9 +89,9 @@ const Form = () => {
return (
<div className="relative flex w-full rounded-md shadow-sm">
<input
- name="email"
- id="email"
- type="email"
+ name="query"
+ id="query"
+ type="text"
required
disabled={pending}
autoComplete="off"
@@ -100,16 +100,14 @@ const Form = () => {
pending && "bg-neutral-100",
)}
onPaste={(e: React.ClipboardEvent<HTMLInputElement>) => {
- // remove mailto: on paste
e.preventDefault();
- const text = e.clipboardData.getData("text/plain");
- if (text.startsWith("mailto:")) {
- e.currentTarget.value = text.replace("mailto:", "");
- } else {
- e.currentTarget.value = text;
+ let text = e.clipboardData.getData("text/plain").trim();
+ if (text.toLowerCase().startsWith("mailto:")) {
+ text = text.slice(7);
}
+ e.currentTarget.value = text;
}}
- placeholder="[email protected]"
+ placeholder="[email protected], acme, or acme.com"
aria-invalid="true"
/>
{pending && (
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-workspace.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-workspace.tsx
deleted file mode 100644
index 4eaeec08c9..0000000000
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-workspace.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-"use client";
-
-import { LoadingSpinner } from "@dub/ui";
-import { cn } from "@dub/utils";
-import { useState } from "react";
-import { useFormStatus } from "react-dom";
-import { toast } from "sonner";
-import UserInfo, { UserInfoProps } from "./user-info";
-
-export function ImpersonateWorkspace() {
- const [data, setData] = useState<UserInfoProps | null>(null);
-
- return (
- <div className="flex flex-col space-y-5">
- <form
- action={async (formData) => {
- await fetch("/api/admin/impersonate", {
- method: "POST",
- body: JSON.stringify({
- slug: formData.get("slug"),
- }),
- }).then(async (res) => {
- if (res.ok) {
- setData(await res.json());
- } else {
- const error = await res.text();
- toast.error(error);
- }
- });
- }}
- >
- <Form />
- </form>
- {data && <UserInfo data={data} />}
- </div>
- );
-}
-
-const Form = () => {
- const { pending } = useFormStatus();
-
- return (
- <div className="relative flex w-full rounded-md shadow-sm">
- <span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-5 text-neutral-500 sm:text-sm">
- app.dub.co
- </span>
- <input
- name="slug"
- id="slug"
- type="text"
- required
- disabled={pending}
- autoComplete="off"
- className={cn(
- "block w-full rounded-r-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
- pending && "bg-neutral-100",
- )}
- placeholder="owd"
- aria-invalid="true"
- />
- {pending && (
- <LoadingSpinner className="absolute inset-y-0 right-2 my-auto h-full w-5 text-neutral-400" />
- )}
- </div>
- );
-};
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx
index a407e8d4af..60593dac26 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx
@@ -2,7 +2,6 @@ import { BanLink } from "./components/ban-link";
import { DeletePartnerAccount } from "./components/delete-partner-account";
import { DisableRestoreWorkspace } from "./components/disable-restore-workspace";
import { ImpersonateUser } from "./components/impersonate-user";
-import { ImpersonateWorkspace } from "./components/impersonate-workspace";
import { ResetLoginAttempts } from "./components/reset-login-attempts";
import { SlackSupportInvite } from "./components/slack-support-invite";
@@ -10,19 +9,13 @@ export default function AdminPage() {
return (
<div className="mx-auto flex w-full max-w-screen-sm flex-col divide-y divide-neutral-200 overflow-auto bg-white">
<div className="flex flex-col space-y-4 px-5 py-10">
- <h2 className="text-xl font-semibold">Impersonate User/Partner</h2>
+ <h2 className="text-xl font-semibold">Impersonate User</h2>
<p className="text-sm text-neutral-500">
- Get a login link for a user email (or partner email)
+ Get a login link by user/partner email, workspace slug, or domain.
+ Workspace and domain lookups impersonate the main owner.
</p>
<ImpersonateUser />
</div>
- <div className="flex flex-col space-y-4 px-5 py-10">
- <h2 className="text-xl font-semibold">Impersonate Workspace</h2>
- <p className="text-sm text-neutral-500">
- Get a login link for the owner of a workspace
- </p>
- <ImpersonateWorkspace />
- </div>
<div className="flex flex-col space-y-4 px-5 py-10">
<h2 className="text-xl font-semibold">Ban Link</h2>
<p className="text-sm text-neutral-500">Ban a dub.sh link</p>
diff --git a/apps/web/app/(ee)/api/admin/impersonate/route.ts b/apps/web/app/(ee)/api/admin/impersonate/route.ts
index 8341d7c3ec..b61065cbcb 100644
--- a/apps/web/app/(ee)/api/admin/impersonate/route.ts
+++ b/apps/web/app/(ee)/api/admin/impersonate/route.ts
@@ -1,111 +1,172 @@
+import { normalizeDomainInput } from "@/lib/api/domains/normalize-domain-input";
import { hashToken, withAdmin } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { APP_DOMAIN, PARTNERS_DOMAIN } from "@dub/utils";
+import { emailSchema } from "@/lib/zod/schemas/auth";
+import {
+ APP_DOMAIN,
+ isAppHostname,
+ PARTNERS_DOMAIN,
+ validDomainRegex,
+ validSlugRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
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();
-
- let userEmails: string[] = [];
- if (email) {
- userEmails.push(email);
- const partner = await prisma.partner.findUnique({
- where: {
- email,
- },
- select: {
- users: {
- select: {
- user: {
- select: {
- email: true,
- },
- },
- },
- take: 1,
- },
- },
- });
- if (partner?.users && partner.users.length > 0) {
- userEmails.push(...partner.users.map((user) => user.user.email || ""));
- }
- }
-
- const response = await prisma.user.findFirst({
- where:
- userEmails.length > 0
- ? {
- email: {
- in: userEmails,
- },
- }
- : {
- projects: {
- some: {
- project: {
- slug,
- },
- role: "owner",
- },
- },
- },
+const userSelect = {
+ email: true,
+ projects: {
select: {
- email: true,
- projects: {
+ project: {
select: {
- project: {
- select: {
- id: true,
- name: true,
- slug: true,
- plan: true,
- usage: true,
- linksUsage: true,
- totalClicks: true,
- totalLinks: true,
- },
- },
- },
- orderBy: {
- project: {
- totalClicks: "desc",
- },
+ id: true,
+ name: true,
+ slug: true,
+ plan: true,
+ usage: true,
+ linksUsage: true,
+ totalClicks: true,
+ totalLinks: true,
},
},
- partners: {
+ },
+ orderBy: {
+ project: {
+ totalClicks: "desc",
+ },
+ },
+ },
+ partners: {
+ select: {
+ partner: {
select: {
- partner: {
+ programs: {
select: {
- programs: {
+ program: {
select: {
- program: {
- select: {
- id: true,
- name: true,
- slug: true,
- },
- },
- status: true,
- totalClicks: true,
- totalLeads: true,
- totalConversions: true,
- totalSaleAmount: true,
- totalCommissions: true,
- },
- orderBy: {
- totalCommissions: "desc",
+ id: true,
+ name: true,
+ slug: true,
},
},
+ status: true,
+ totalClicks: true,
+ totalLeads: true,
+ totalConversions: true,
+ totalSaleAmount: true,
+ totalCommissions: true,
+ },
+ orderBy: {
+ totalCommissions: "desc",
},
},
},
},
},
- });
+ },
+} satisfies Prisma.UserSelect;
+
+const ownerSelect = {
+ users: {
+ where: {
+ role: "owner",
+ user: {
+ email: {
+ not: null,
+ },
+ },
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ take: 1,
+ select: {
+ user: {
+ select: userSelect,
+ },
+ },
+ },
+} satisfies Prisma.ProjectSelect;
+
+type ImpersonateIdentifier =
+ | { type: "email"; email: string }
+ | { type: "slug"; slug: string }
+ | { type: "domain"; domain: string };
+
+function parseImpersonateQuery(
+ raw: unknown,
+): ImpersonateIdentifier | { error: string } {
+ if (typeof raw !== "string" || !raw.trim()) {
+ return { error: "Enter a user email, workspace slug, or domain" };
+ }
+
+ let query = raw.trim();
+ if (query.toLowerCase().startsWith("mailto:")) {
+ query = query.slice(7).trim();
+ }
+
+ if (query.includes("@")) {
+ const parsed = emailSchema.safeParse(query);
+ if (!parsed.success) {
+ return { error: "Invalid email" };
+ }
+ return { type: "email", email: parsed.data };
+ }
+
+ let hostname: string | undefined;
+ let pathname: string | undefined;
+ try {
+ const url = query.includes("://")
+ ? new URL(query)
+ : query.includes("/")
+ ? new URL(`https://${query}`)
+ : undefined;
+ if (url) {
+ hostname = url.hostname.toLowerCase();
+ pathname = url.pathname;
+ }
+ } catch {
+ // keep the raw query
+ }
+
+ if (hostname && isAppHostname(hostname)) {
+ const slug = pathname?.split("/").filter(Boolean)[0];
+ if (slug && validSlugRegex.test(slug)) {
+ return { type: "slug", slug: slug.toLowerCase() };
+ }
+ }
+
+ const domain = normalizeDomainInput(hostname ?? query);
+ if (validDomainRegex.test(domain)) {
+ return { type: "domain", domain };
+ }
+
+ const slug = query.toLowerCase();
+ if (validSlugRegex.test(slug)) {
+ return { type: "slug", slug };
+ }
+
+ return { error: "Enter a user email, workspace slug, or domain" };
+}
- if (!response?.email) {
+// POST /api/admin/impersonate
+export const POST = withAdmin(async ({ req }) => {
+ const { query, email, slug, domain } = await req.json();
+ const parsed = parseImpersonateQuery(query ?? email ?? slug ?? domain);
+
+ if ("error" in parsed) {
+ return new Response(parsed.error, { status: 400 });
+ }
+
+ const result = await findUser(parsed);
+
+ if ("error" in result) {
+ return new Response(result.error, { status: 404 });
+ }
+
+ const { user: response } = result;
+
+ if (!response.email) {
return new Response("User not found", { status: 404 });
}
@@ -131,6 +192,93 @@ export const POST = withAdmin(async ({ req }) => {
return NextResponse.json(data);
});
+async function findUser(identifier: ImpersonateIdentifier) {
+ if (identifier.type === "email") {
+ const userEmails = [identifier.email];
+ const partner = await prisma.partner.findUnique({
+ where: {
+ email: identifier.email,
+ },
+ select: {
+ users: {
+ select: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ take: 1,
+ },
+ },
+ });
+ if (partner?.users && partner.users.length > 0) {
+ userEmails.push(...partner.users.map((user) => user.user.email || ""));
+ }
+
+ const user = await prisma.user.findFirst({
+ where: {
+ email: {
+ in: userEmails,
+ },
+ },
+ select: userSelect,
+ });
+
+ if (!user?.email) {
+ return { error: "User not found" };
+ }
+
+ return { user };
+ }
+
+ if (identifier.type === "domain") {
+ const domainRecord = await prisma.domain.findUnique({
+ where: {
+ slug: identifier.domain,
+ },
+ select: {
+ project: {
+ select: ownerSelect,
+ },
+ },
+ });
+
+ if (!domainRecord) {
+ return { error: "Domain not found" };
+ }
+
+ if (!domainRecord.project) {
+ return { error: "Domain is not attached to a workspace" };
+ }
+
+ const user = domainRecord.project.users[0]?.user;
+ if (!user?.email) {
+ return { error: "Workspace owner not found" };
+ }
+
+ return { user };
+ }
+
+ const project = await prisma.project.findUnique({
+ where: {
+ slug: identifier.slug,
+ },
+ select: ownerSelect,
+ });
+
+ if (!project) {
+ return { error: "Workspace not found" };
+ }
+
+ const user = project.users[0]?.user;
+ if (!user?.email) {
+ return { error: "Workspace owner not found" };
+ }
+
+ return { user };
+}
+
async function getImpersonateUrl(email: string) {
const token = randomBytes(32).toString("hex");