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.

add platform verification in admin

Steven Tey677e4eed63d8
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/page.tsx
index 5960d883d5..3efee6f616 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/page.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/page.tsx
@@ -1,11 +1,22 @@
"use client";
+import { PARTNER_PLATFORM_FIELDS } from "@/lib/partners/partner-platforms";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
import { PartnerAvatar } from "@/ui/partners/partner-avatar";
-import { Button, CopyText, TimestampTooltip } from "@dub/ui";
-import { Xmark } from "@dub/ui/icons";
+import { PlatformType } from "@dub/prisma/client";
+import { Button, CopyText, Sheet, TimestampTooltip, Tooltip } from "@dub/ui";
+import {
+ BadgeCheck2Fill,
+ Instagram,
+ LinkedIn,
+ TikTok,
+ Twitter,
+ Xmark,
+ YouTube,
+} from "@dub/ui/icons";
import { cn, fetcher, formatDateSmart } from "@dub/utils";
-import { FormEvent, useCallback, useMemo, useState } from "react";
+import Link from "next/link";
+import { FormEvent, useCallback, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import useSWR from "swr";
@@ -15,8 +26,57 @@ type TrustedPartner = {
email: string | null;
image: string | null;
trustedAt: Date;
+ description?: string | null;
+ platforms: Array<{
+ type: PlatformType;
+ identifier: string;
+ verifiedAt: Date | string | null;
+ subscribers: number;
+ posts: number;
+ views: number;
+ }>;
};
+const PLATFORM_ORDER: PlatformType[] = [
+ "youtube",
+ "twitter",
+ "linkedin",
+ "instagram",
+ "tiktok",
+ "website",
+];
+
+const PLATFORM_LABELS: Record<PlatformType, string> = {
+ website: "Website",
+ youtube: "YouTube",
+ twitter: "X / Twitter",
+ linkedin: "LinkedIn",
+ instagram: "Instagram",
+ tiktok: "TikTok",
+};
+
+const PLATFORM_PLACEHOLDERS: Record<PlatformType, string> = {
+ website: "https://example.com",
+ youtube: "@creator or channel URL",
+ twitter: "@handle or profile URL",
+ linkedin: "profile slug or URL",
+ instagram: "@handle or profile URL",
+ tiktok: "@handle or profile URL",
+};
+
+const formatInt = (value: number) =>
+ new Intl.NumberFormat("en-US").format(value);
+
+function PlatformIcon({ platform }: { platform: PlatformType }) {
+ const className = "size-4";
+ if (platform === "youtube") return <YouTube className={className} />;
+ if (platform === "twitter") return <Twitter className={className} />;
+ if (platform === "linkedin") return <LinkedIn className={className} />;
+ if (platform === "instagram") return <Instagram className={className} />;
+ if (platform === "tiktok") return <TikTok className={className} />;
+ return <span className="text-xs text-neutral-500">WEB</span>;
+}
+
function TrustedAtLabel({
trustedAt,
className,
@@ -48,6 +108,19 @@ export default function PartnersPage() {
const [partnerToRemove, setPartnerToRemove] = useState<TrustedPartner | null>(
null,
);
+ const [activePartner, setActivePartner] = useState<TrustedPartner | null>(
+ null,
+ );
+ const [sheetOpen, setSheetOpen] = useState(false);
+ const [draftHandles, setDraftHandles] = useState<
+ Partial<Record<PlatformType, string>>
+ >({});
+ const [linkedInPostUrls, setLinkedInPostUrls] = useState<
+ Partial<Record<PlatformType, string>>
+ >({});
+ const [verifyingPlatforms, setVerifyingPlatforms] = useState<
+ Partial<Record<PlatformType, boolean>>
+ >({});
const { data, isLoading, mutate } = useSWR<{ partners: TrustedPartner[] }>(
"/api/admin/partners",
@@ -56,6 +129,26 @@ export default function PartnersPage() {
);
const trustedPartners = data?.partners ?? [];
+ const platformByType = useMemo(
+ () =>
+ Object.fromEntries(
+ (activePartner?.platforms ?? []).map((platform) => [
+ platform.type,
+ platform,
+ ]),
+ ) as Partial<Record<PlatformType, TrustedPartner["platforms"][number]>>,
+ [activePartner?.platforms],
+ );
+
+ useEffect(() => {
+ if (!activePartner) return;
+ const nextDraftHandles: Partial<Record<PlatformType, string>> = {};
+ for (const platform of PLATFORM_ORDER) {
+ nextDraftHandles[platform] = platformByType[platform]?.identifier ?? "";
+ }
+ setDraftHandles(nextDraftHandles);
+ setLinkedInPostUrls({});
+ }, [activePartner, platformByType]);
const { setShowConfirmModal, confirmModal } = useConfirmModal({
title: "Remove trusted partner",
@@ -135,6 +228,58 @@ export default function PartnersPage() {
});
};
+ const verifyPlatform = async (platform: PlatformType) => {
+ if (!activePartner) return;
+ const identifier = draftHandles[platform]?.trim();
+ if (!identifier) {
+ toast.error(`Please enter a ${PLATFORM_LABELS[platform]} identifier.`);
+ return;
+ }
+
+ setVerifyingPlatforms((prev) => ({ ...prev, [platform]: true }));
+
+ const payload: {
+ partnerId: string;
+ platform: PlatformType;
+ identifier: string;
+ postUrl?: string;
+ } = {
+ partnerId: activePartner.id,
+ platform,
+ identifier,
+ };
+
+ const linkedInPostUrl = linkedInPostUrls.linkedin?.trim();
+ if (platform === "linkedin" && linkedInPostUrl) {
+ payload.postUrl = linkedInPostUrl;
+ }
+
+ await fetch("/api/admin/partners/platforms", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ })
+ .then(async (res) => {
+ if (!res.ok) {
+ throw new Error(await res.text());
+ }
+ const refreshed = await mutate();
+ const updatedActivePartner = refreshed?.partners?.find(
+ (p) => p.id === activePartner.id,
+ );
+ if (updatedActivePartner) {
+ setActivePartner(updatedActivePartner);
+ }
+ toast.success(`${PLATFORM_LABELS[platform]} verified manually.`);
+ })
+ .catch((error) => {
+ toast.error(error.message || "Failed to verify platform.");
+ })
+ .finally(() => {
+ setVerifyingPlatforms((prev) => ({ ...prev, [platform]: false }));
+ });
+ };
+
return (
<div className="mx-auto flex w-full max-w-screen-xl flex-col gap-6 p-6">
{confirmModal}
@@ -190,9 +335,28 @@ export default function PartnersPage() {
<ul className="divide-y divide-neutral-100">
{trustedPartners.map((partner) => (
<li key={partner.id}>
- <div className="flex items-start gap-3 px-4 py-3.5 sm:px-5 md:items-center">
+ <div
+ role="button"
+ tabIndex={0}
+ className="flex cursor-pointer items-start gap-3 px-4 py-3.5 transition-colors hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-300 sm:px-5 md:items-center"
+ onClick={() => {
+ setActivePartner(partner);
+ setSheetOpen(true);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ setActivePartner(partner);
+ setSheetOpen(true);
+ }
+ }}
+ >
<PartnerAvatar
- partner={partner}
+ partner={{
+ id: partner.id,
+ name: partner.name,
+ image: partner.image,
+ }}
className="size-10 shrink-0 border border-neutral-100 shadow-sm"
/>
<div className="min-w-0 flex-1">
@@ -208,14 +372,74 @@ export default function PartnersPage() {
{partner.id}
</CopyText>
</div>
- {partner.email ? (
- <CopyText
- value={partner.email}
- className="truncate text-sm text-neutral-500"
- >
- {partner.email}
- </CopyText>
- ) : null}
+ <div className="mt-1 flex flex-col gap-1 lg:flex-row lg:items-center lg:gap-3">
+ {partner.email ? (
+ <CopyText
+ value={partner.email}
+ className="w-fit truncate text-sm text-neutral-500"
+ >
+ {partner.email}
+ </CopyText>
+ ) : (
+ <span />
+ )}
+ <div className="flex flex-wrap items-center gap-1.5 lg:justify-end">
+ {(() => {
+ const platforms = partner.platforms.map((p) => ({
+ ...p,
+ platformId: null,
+ avatarUrl: null,
+ subscribers: BigInt(p.subscribers),
+ posts: BigInt(p.posts),
+ views: BigInt(p.views),
+ verifiedAt: p.verifiedAt
+ ? new Date(p.verifiedAt)
+ : null,
+ }));
+ return PARTNER_PLATFORM_FIELDS.map(
+ ({ label, icon: Icon, data: getPlatformData }) => {
+ const { value, href, verified } =
+ getPlatformData(platforms);
+ if (!value) return null;
+ return (
+ <Tooltip
+ key={label}
+ content={
+ <Link
+ href={href ?? "#"}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex items-center gap-1 px-2 py-1 text-xs font-medium text-neutral-700 hover:text-neutral-900"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Icon className="size-3 shrink-0" />
+ <span>{value}</span>
+ {verified && (
+ <BadgeCheck2Fill className="size-3 text-green-600" />
+ )}
+ </Link>
+ }
+ >
+ <Link
+ href={href ?? "#"}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="border-border-subtle hover:bg-bg-muted relative flex size-6 shrink-0 items-center justify-center rounded-full border"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Icon className="size-3" />
+ <span className="sr-only">{label}</span>
+ {verified && (
+ <BadgeCheck2Fill className="absolute -right-1 -top-1 size-3 text-green-600" />
+ )}
+ </Link>
+ </Tooltip>
+ );
+ },
+ );
+ })()}
+ </div>
+ </div>
<TrustedAtLabel
trustedAt={partner.trustedAt}
className="mt-0.5 md:hidden"
@@ -234,7 +458,10 @@ export default function PartnersPage() {
"hover:bg-neutral-100 hover:text-neutral-700",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 focus-visible:ring-offset-2",
)}
- onClick={() => openRemoveModal(partner)}
+ onClick={(e) => {
+ e.stopPropagation();
+ openRemoveModal(partner);
+ }}
>
<Xmark className="size-4" />
</button>
@@ -245,6 +472,140 @@ export default function PartnersPage() {
</ul>
)}
</div>
+ <Sheet
+ open={sheetOpen}
+ onOpenChange={(open) => {
+ setSheetOpen(open);
+ if (!open) setActivePartner(null);
+ }}
+ >
+ <div className="flex h-full flex-col">
+ <div className="flex h-16 items-center justify-between border-b border-neutral-200 px-6 py-4">
+ <Sheet.Title className="text-lg font-semibold">
+ Partner profile and platforms
+ </Sheet.Title>
+ <Sheet.Close asChild>
+ <Button
+ type="button"
+ variant="outline"
+ icon={<Xmark className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+
+ <div className="grid min-h-0 flex-1 gap-4 overflow-y-auto p-6">
+ {!activePartner ? null : (
+ <>
+ <div className="rounded-xl border border-neutral-200 bg-white p-4">
+ <div className="flex items-start gap-3">
+ <img
+ src={activePartner.image || ""}
+ alt={activePartner.name}
+ className="size-12 shrink-0 rounded-full border border-neutral-100 bg-neutral-100 object-cover"
+ />
+ <div className="min-w-0">
+ <p className="truncate text-sm font-semibold text-neutral-900">
+ {activePartner.name}
+ </p>
+ <p className="truncate text-sm text-neutral-600">
+ {activePartner.email ?? "No email"}
+ </p>
+ {activePartner.description ? (
+ <p className="mt-1 line-clamp-3 text-sm text-neutral-500">
+ {activePartner.description}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ </div>
+
+ <div className="space-y-3">
+ {PLATFORM_ORDER.map((platform) => {
+ const existing = platformByType[platform];
+ const isVerifying = Boolean(verifyingPlatforms[platform]);
+ return (
+ <div
+ key={platform}
+ className="rounded-xl border border-neutral-200 bg-white p-4"
+ >
+ <div className="mb-3 flex items-center justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <PlatformIcon platform={platform} />
+ <p className="text-sm font-medium text-neutral-900">
+ {PLATFORM_LABELS[platform]}
+ </p>
+ </div>
+ <div
+ className={cn(
+ "rounded-full px-2 py-0.5 text-xs font-medium",
+ existing?.verifiedAt
+ ? "bg-emerald-100 text-emerald-700"
+ : "bg-neutral-100 text-neutral-600",
+ )}
+ >
+ {existing?.verifiedAt ? "Verified" : "Not verified"}
+ </div>
+ </div>
+
+ <div className="grid gap-2 sm:grid-cols-[1fr_auto]">
+ <input
+ type="text"
+ value={draftHandles[platform] ?? ""}
+ onChange={(e) =>
+ setDraftHandles((prev) => ({
+ ...prev,
+ [platform]: e.target.value,
+ }))
+ }
+ placeholder={PLATFORM_PLACEHOLDERS[platform]}
+ className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500"
+ />
+ <Button
+ type="button"
+ text="Verify"
+ className="w-fit"
+ loading={isVerifying}
+ onClick={() => verifyPlatform(platform)}
+ />
+ </div>
+
+ {platform === "linkedin" ? (
+ <input
+ type="text"
+ value={linkedInPostUrls.linkedin ?? ""}
+ onChange={(e) =>
+ setLinkedInPostUrls((prev) => ({
+ ...prev,
+ linkedin: e.target.value,
+ }))
+ }
+ placeholder="Optional: LinkedIn post URL (for follower metadata)"
+ className="mt-2 w-full rounded-md border border-neutral-300 px-3 py-2 text-sm text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500"
+ />
+ ) : null}
+
+ <div className="mt-3 flex flex-wrap gap-3 text-xs text-neutral-500">
+ <span>
+ Subscribers: {formatInt(existing?.subscribers ?? 0)}
+ </span>
+ <span>Posts: {formatInt(existing?.posts ?? 0)}</span>
+ <span>Views: {formatInt(existing?.views ?? 0)}</span>
+ {existing?.verifiedAt ? (
+ <span>
+ Verified {formatDateSmart(existing.verifiedAt)}
+ </span>
+ ) : null}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </Sheet>
</div>
);
}
diff --git a/apps/web/app/(ee)/api/admin/partners/platforms/route.ts b/apps/web/app/(ee)/api/admin/partners/platforms/route.ts
new file mode 100644
index 0000000000..ce72f66a5e
--- /dev/null
+++ b/apps/web/app/(ee)/api/admin/partners/platforms/route.ts
@@ -0,0 +1,142 @@
+import { getLinkedInPost } from "@/lib/api/scrape-creators/get-linkedin-post";
+import { getSocialProfile } from "@/lib/api/scrape-creators/get-social-profile";
+import { withAdmin } from "@/lib/auth";
+import { sanitizeSocialHandle, sanitizeWebsite } from "@/lib/social-utils";
+import { prisma } from "@dub/prisma";
+import { PlatformType } from "@dub/prisma/client";
+import { revalidatePath } from "next/cache";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const postSchema = z.object({
+ partnerId: z.string().trim().min(1),
+ platform: z.enum(PlatformType),
+ identifier: z.string().trim().min(1),
+ postUrl: z.string().trim().url().optional(),
+});
+
+// POST /api/admin/partners/platforms
+export const POST = withAdmin(
+ async ({ req }) => {
+ const { partnerId, platform, identifier: rawIdentifier, postUrl } = postSchema
+ .parse(await req.json());
+
+ const partner = await prisma.partner.findUnique({
+ where: { id: partnerId },
+ select: { id: true },
+ });
+
+ if (!partner) {
+ return new Response("Partner not found.", { status: 404 });
+ }
+
+ const identifier =
+ platform === "website"
+ ? sanitizeWebsite(rawIdentifier)
+ : sanitizeSocialHandle(rawIdentifier, platform);
+
+ if (!identifier) {
+ return new Response("Invalid platform identifier.", { status: 400 });
+ }
+
+ let verifiedData: {
+ platformId: string | null;
+ subscribers: bigint;
+ posts: bigint;
+ views: bigint;
+ avatarUrl: string | null;
+ metadata?: Record<string, string | number>;
+ } = {
+ platformId: null,
+ subscribers: BigInt(0),
+ posts: BigInt(0),
+ views: BigInt(0),
+ avatarUrl: null,
+ metadata: {},
+ };
+
+ if (["youtube", "instagram", "twitter", "tiktok"].includes(platform)) {
+ const socialProfile = await getSocialProfile({
+ platform,
+ handle: identifier,
+ });
+
+ verifiedData = {
+ platformId: socialProfile.platformId,
+ subscribers: socialProfile.subscribers,
+ posts: socialProfile.posts,
+ views: socialProfile.views,
+ avatarUrl: socialProfile.avatarUrl,
+ };
+ } else if (platform === "linkedin" && postUrl) {
+ const linkedInPost = await getLinkedInPost(postUrl);
+ verifiedData = {
+ platformId: null,
+ subscribers: BigInt(linkedInPost.author.followers || 0),
+ posts: BigInt(0),
+ views: BigInt(0),
+ avatarUrl: null,
+ metadata: {
+ linkedInPostUrl: postUrl,
+ linkedInAuthorUrl: linkedInPost.author.url ?? "",
+ },
+ };
+ }
+
+ const updated = await prisma.partnerPlatform.upsert({
+ where: {
+ partnerId_type: {
+ partnerId,
+ type: platform,
+ },
+ },
+ create: {
+ partnerId,
+ type: platform,
+ identifier,
+ verifiedAt: new Date(),
+ platformId: verifiedData.platformId,
+ subscribers: verifiedData.subscribers,
+ posts: verifiedData.posts,
+ views: verifiedData.views,
+ avatarUrl: verifiedData.avatarUrl,
+ metadata: {
+ ...(verifiedData.metadata ?? {}),
+ manuallyVerifiedByAdmin: true,
+ manuallyVerifiedAt: new Date().toISOString(),
+ },
+ lastCheckedAt: new Date(),
+ },
+ update: {
+ identifier,
+ verifiedAt: new Date(),
+ platformId: verifiedData.platformId,
+ subscribers: verifiedData.subscribers,
+ posts: verifiedData.posts,
+ views: verifiedData.views,
+ avatarUrl: verifiedData.avatarUrl,
+ metadata: {
+ ...(verifiedData.metadata ?? {}),
+ manuallyVerifiedByAdmin: true,
+ manuallyVerifiedAt: new Date().toISOString(),
+ },
+ lastCheckedAt: new Date(),
+ },
+ });
+
+ revalidatePath("/api/admin/partners");
+ revalidatePath("/api/admin/partners/platforms");
+
+ return NextResponse.json({
+ platform: {
+ ...updated,
+ subscribers: Number(updated.subscribers),
+ posts: Number(updated.posts),
+ views: Number(updated.views),
+ },
+ });
+ },
+ {
+ requiredRoles: ["owner"],
+ },
+);
diff --git a/apps/web/app/(ee)/api/admin/partners/route.ts b/apps/web/app/(ee)/api/admin/partners/route.ts
index 0e488a1d24..bbd63a2e76 100644
--- a/apps/web/app/(ee)/api/admin/partners/route.ts
+++ b/apps/web/app/(ee)/api/admin/partners/route.ts
@@ -19,11 +19,32 @@ export const GET = withAdmin(async () => {
name: true,
email: true,
image: true,
+ description: true,
trustedAt: true,
+ platforms: {
+ select: {
+ type: true,
+ identifier: true,
+ verifiedAt: true,
+ subscribers: true,
+ posts: true,
+ views: true,
+ },
+ },
},
});
- return NextResponse.json({ partners });
+ return NextResponse.json({
+ partners: partners.map((partner) => ({
+ ...partner,
+ platforms: partner.platforms.map((platform) => ({
+ ...platform,
+ subscribers: Number(platform.subscribers),
+ posts: Number(platform.posts),
+ views: Number(platform.views),
+ })),
+ })),
+ });
});
// POST /api/admin/partners
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
index 043a2564d3..6dd32a932d 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
@@ -1,5 +1,5 @@
import { DubApiError } from "@/lib/api/errors";
-import { isDubAdmin, withWorkspace } from "@/lib/auth";
+import { getDubAdminRole, withWorkspace } from "@/lib/auth";
import { getDubCustomer } from "@/lib/dub";
import { stripe } from "@/lib/stripe";
import { booleanQuerySchema } from "@/lib/zod/schemas/misc";
@@ -47,8 +47,8 @@ export const POST = withWorkspace(
: null;
if (process.env.VERCEL === "1" && process.env.VERCEL_ENV === "preview") {
- const isAdminUser = await isDubAdmin(session.user.id);
- if (!isAdminUser) {
+ const adminRole = await getDubAdminRole(session.user.id);
+ if (!adminRole) {
throw new DubApiError({
code: "unauthorized",
message: "Unauthorized: Not an admin.",
diff --git a/apps/web/lib/auth/admin.ts b/apps/web/lib/auth/admin.ts
index ff9fe0c263..84104e66fb 100644
--- a/apps/web/lib/auth/admin.ts
+++ b/apps/web/lib/auth/admin.ts
@@ -16,7 +16,7 @@ interface WithAdminHandler {
}): Promise<Response>;
}
-const getDubAdminRole = async (userId: string) => {
+export const getDubAdminRole = async (userId: string) => {
const response = await prisma.projectUsers.findUnique({
where: {
userId_projectId: {