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 password + noindex support to analytics dashboards

Steven Teyf3dc7aba565a
diff --git a/apps/web/app/api/dashboards/[id]/route.ts b/apps/web/app/api/dashboards/[id]/route.ts
index 5ffe53e9a2..9fa4c8e427 100644
--- a/apps/web/app/api/dashboards/[id]/route.ts
+++ b/apps/web/app/api/dashboards/[id]/route.ts
@@ -1,12 +1,62 @@
+import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
+import {
+ dashboardSchema,
+ updateDashboardBodySchema,
+} from "@/lib/zod/schemas/dashboard";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
+const getDashboardOrThrow = async ({
+ id,
+ workspaceId,
+}: {
+ id: string;
+ workspaceId: string;
+}) => {
+ const dashboard = await prisma.dashboard.findUnique({
+ where: { id, projectId: workspaceId },
+ });
+
+ if (!dashboard) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Dashboard not found",
+ });
+ }
+
+ return dashboard;
+};
+
+// PATCH /api/dashboards/[id] – update a dashboard
+export const PATCH = withWorkspace(
+ async ({ params, workspace, req }) => {
+ const { id } = params;
+ await getDashboardOrThrow({ id, workspaceId: workspace.id });
+
+ const body = await req.json();
+ const data = updateDashboardBodySchema.parse(body);
+
+ const dashboard = await prisma.dashboard.update({
+ where: {
+ id,
+ },
+ data,
+ });
+
+ return NextResponse.json(dashboardSchema.parse(dashboard));
+ },
+ {
+ requiredPermissions: ["links.write"],
+ },
+);
+
// DELETE /api/dashboards/[id] – delete a dashboard
export const DELETE = withWorkspace(
async ({ params, workspace }) => {
const { id } = params;
+ await getDashboardOrThrow({ id, workspaceId: workspace.id });
const dashboard = await prisma.dashboard.delete({
where: {
diff --git a/apps/web/app/app.dub.co/(share)/layout.tsx b/apps/web/app/app.dub.co/(share)/layout.tsx
deleted file mode 100644
index 83bd18b58a..0000000000
--- a/apps/web/app/app.dub.co/(share)/layout.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import { Footer, Nav, NavMobile } from "@dub/ui";
-import { ReactNode } from "react";
-
-export default function dashboardLayout({ children }: { children: ReactNode }) {
- return (
- <div className="flex min-h-screen flex-col justify-between bg-gray-50/80">
- <NavMobile staticDomain="app.dub.co" />
- <Nav staticDomain="app.dub.co" />
- {children}
- <Footer staticDomain="app.dub.co" />
- </div>
- );
-}
diff --git a/apps/web/app/app.dub.co/(share)/share/[dashboardId]/action.ts b/apps/web/app/app.dub.co/(share)/share/[dashboardId]/action.ts
new file mode 100644
index 0000000000..cdb2dd934e
--- /dev/null
+++ b/apps/web/app/app.dub.co/(share)/share/[dashboardId]/action.ts
@@ -0,0 +1,29 @@
+"use server";
+
+import { prismaEdge } from "@/lib/prisma/edge";
+import { cookies } from "next/headers";
+
+export async function verifyPassword(_prevState: any, data: FormData) {
+ const dashboardId = data.get("dashboardId") as string;
+ const password = data.get("password") as string;
+
+ const dashboard = await prismaEdge.dashboard.findUnique({
+ where: { id: dashboardId },
+ });
+
+ if (!dashboard) {
+ return { error: "Dashboard not found" };
+ }
+
+ if (dashboard.password !== password) {
+ return { error: "Invalid password" };
+ }
+
+ cookies().set(`dub_dash_${dashboardId}`, password, {
+ path: "/",
+ httpOnly: true,
+ secure: true,
+ });
+
+ return { redirect: `/share/${dashboardId}` };
+}
diff --git a/apps/web/app/app.dub.co/(share)/share/[dashboardId]/page.tsx b/apps/web/app/app.dub.co/(share)/share/[dashboardId]/page.tsx
index 13ac92a5f1..f02833a1ff 100644
--- a/apps/web/app/app.dub.co/(share)/share/[dashboardId]/page.tsx
+++ b/apps/web/app/app.dub.co/(share)/share/[dashboardId]/page.tsx
@@ -1,9 +1,13 @@
import { getDashboard } from "@/lib/fetchers/get-dashboard";
import { PlanProps } from "@/lib/types";
import Analytics from "@/ui/analytics";
+import { NewBackground } from "@/ui/shared/new-background";
+import { Footer, Logo, Nav, NavMobile } from "@dub/ui";
import { APP_DOMAIN, constructMetadata } from "@dub/utils";
+import { cookies } from "next/headers";
import { notFound } from "next/navigation";
import { Suspense } from "react";
+import DashboardPasswordForm from "./password-form";
export const runtime = "edge";
@@ -22,7 +26,7 @@ export async function generateMetadata({
return constructMetadata({
title: `Analytics for ${data.link.domain}/${data.link.key} – ${process.env.NEXT_PUBLIC_APP_NAME}`,
image: `${APP_DOMAIN}/api/og/analytics?domain=${data.link.domain}&key=${data.link.key}`,
- noIndex: true,
+ noIndex: !data.doIndex,
});
}
@@ -38,17 +42,44 @@ export default async function dashboardPage({
notFound();
}
+ if (
+ data.password &&
+ cookies().get(`dub_dash_${params.dashboardId}`)?.value !== data.password
+ ) {
+ return (
+ <main className="flex h-screen w-screen items-center justify-center">
+ <NewBackground />
+ <div className="z-10 w-full max-w-md overflow-hidden rounded-2xl border border-gray-100 shadow-xl">
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16">
+ <Logo />
+ <h3 className="text-xl font-semibold">Enter Password</h3>
+ <p className="text-sm text-gray-500">
+ This dashboard is password protected. Enter the password to view
+ the dashboard.
+ </p>
+ </div>
+ <DashboardPasswordForm />
+ </div>
+ </main>
+ );
+ }
+
return (
- <Suspense fallback={<div className="h-screen w-full bg-gray-50" />}>
- <Analytics
- dashboardProps={{
- domain: data.link.domain,
- key: data.link.key,
- url: data.link.url,
- showConversions: data.showConversions,
- workspacePlan: data.project?.plan as PlanProps,
- }}
- />
- </Suspense>
+ <div className="flex min-h-screen flex-col justify-between bg-gray-50/80">
+ <NavMobile staticDomain="app.dub.co" />
+ <Nav staticDomain="app.dub.co" />
+ <Suspense fallback={<div className="h-screen w-full bg-gray-50" />}>
+ <Analytics
+ dashboardProps={{
+ domain: data.link.domain,
+ key: data.link.key,
+ url: data.link.url,
+ showConversions: data.showConversions,
+ workspacePlan: data.project?.plan as PlanProps,
+ }}
+ />
+ </Suspense>
+ <Footer staticDomain="app.dub.co" />
+ </div>
);
}
diff --git a/apps/web/app/app.dub.co/(share)/share/[dashboardId]/password-form.tsx b/apps/web/app/app.dub.co/(share)/share/[dashboardId]/password-form.tsx
new file mode 100644
index 0000000000..24af4fe547
--- /dev/null
+++ b/apps/web/app/app.dub.co/(share)/share/[dashboardId]/password-form.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { AlertCircleFill } from "@/ui/shared/icons";
+import { Button, useMediaQuery } from "@dub/ui";
+import { useParams } from "next/navigation";
+import { useFormState, useFormStatus } from "react-dom";
+import { verifyPassword } from "./action";
+
+const initialState = {
+ redirect: null,
+ error: null,
+};
+
+export default function DashboardPasswordForm() {
+ const { dashboardId } = useParams() as { dashboardId: string };
+
+ const [state, formAction] = useFormState(verifyPassword, initialState);
+ const { isMobile } = useMediaQuery();
+
+ return (
+ <form
+ action={formAction}
+ className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 sm:px-16"
+ >
+ <div>
+ <label htmlFor="password" className="block text-xs text-gray-600">
+ PASSWORD
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input type="hidden" name="dashboardId" value={dashboardId} />
+ <input
+ type="password"
+ name="password"
+ id="password"
+ autoFocus={!isMobile}
+ required
+ className={`${
+ state.error
+ ? "border-red-300 pr-10 text-red-500 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
+ : "border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:ring-gray-500"
+ } block w-full rounded-md focus:outline-none sm:text-sm`}
+ />
+ {state.error && (
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
+ <AlertCircleFill
+ className="h-5 w-5 text-red-500"
+ aria-hidden="true"
+ />
+ </div>
+ )}
+ </div>
+ {state.error && (
+ <p className="mt-2 text-sm text-red-600" id="slug-error">
+ Incorrect password
+ </p>
+ )}
+ </div>
+
+ <FormButton />
+ </form>
+ );
+}
+
+const FormButton = () => {
+ const { pending } = useFormStatus();
+ return <Button text="Submit" loading={pending} />;
+};
diff --git a/apps/web/app/password/[domain]/[key]/page.tsx b/apps/web/app/password/[domain]/[key]/page.tsx
index acc116f975..17f5cb820a 100644
--- a/apps/web/app/password/[domain]/[key]/page.tsx
+++ b/apps/web/app/password/[domain]/[key]/page.tsx
@@ -1,5 +1,6 @@
import { prisma } from "@/lib/prisma";
-import { Background, BlurImage, Logo } from "@dub/ui";
+import { NewBackground } from "@/ui/shared/new-background";
+import { BlurImage, Logo } from "@dub/ui";
import { constructMetadata, isDubDomain } from "@dub/utils";
import { notFound, redirect } from "next/navigation";
import PasswordForm from "./form";
@@ -113,7 +114,7 @@ export default async function PasswordProtectedLinkPage({
return (
<main className="flex h-screen w-screen items-center justify-center">
- <Background />
+ <NewBackground />
<div className="z-10 w-full max-w-md overflow-hidden rounded-2xl border border-gray-100 shadow-xl">
<div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16">
{!isDubDomain(domain) &&
diff --git a/apps/web/lib/fetchers/get-dashboard.ts b/apps/web/lib/fetchers/get-dashboard.ts
index 7995b8017c..6bd5be2797 100644
--- a/apps/web/lib/fetchers/get-dashboard.ts
+++ b/apps/web/lib/fetchers/get-dashboard.ts
@@ -8,6 +8,8 @@ export const getDashboard = cache(async ({ id }: { id: string }) => {
},
select: {
id: true,
+ doIndex: true,
+ password: true,
showConversions: true,
link: {
select: {
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index f4009b7332..7a7a25d4e8 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -15,6 +15,7 @@ import {
CustomerSchema,
trackCustomerResponseSchema,
} from "./zod/schemas/customers";
+import { dashboardSchema } from "./zod/schemas/dashboard";
import { integrationSchema } from "./zod/schemas/integration";
import { trackLeadResponseSchema } from "./zod/schemas/leads";
import { createLinkBodySchema } from "./zod/schemas/links";
@@ -230,6 +231,8 @@ export const tagColors = [
"brown",
] as const;
+export type DashboardProps = z.infer<typeof dashboardSchema>;
+
export type MetaTag = z.infer<typeof metaTagsSchema>;
export type TokenProps = z.infer<typeof tokenSchema>;
diff --git a/apps/web/lib/zod/schemas/dashboard.ts b/apps/web/lib/zod/schemas/dashboard.ts
index 90971fc9f0..cc9bc333b0 100644
--- a/apps/web/lib/zod/schemas/dashboard.ts
+++ b/apps/web/lib/zod/schemas/dashboard.ts
@@ -11,3 +11,8 @@ export const dashboardSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
});
+
+export const updateDashboardBodySchema = dashboardSchema.pick({
+ doIndex: true,
+ password: true,
+});
diff --git a/apps/web/ui/analytics/analytics-provider.tsx b/apps/web/ui/analytics/analytics-provider.tsx
index 46fe95c24d..1ecb44fe2d 100644
--- a/apps/web/ui/analytics/analytics-provider.tsx
+++ b/apps/web/ui/analytics/analytics-provider.tsx
@@ -29,7 +29,7 @@ import useSWR from "swr";
import { defaultConfig } from "swr/_internal";
import { UpgradeRequiredToast } from "../shared/upgrade-required-toast";
-export interface dashboardProps {
+export interface AnalyticsDashboardProps {
domain: string;
key: string;
url: string;
@@ -59,7 +59,7 @@ export const AnalyticsContext = createContext<{
partnerPage?: boolean;
showConversions?: boolean;
requiresUpgrade?: boolean;
- dashboardProps?: dashboardProps;
+ dashboardProps?: AnalyticsDashboardProps;
}>({
basePath: "",
baseApiPath: "",
@@ -86,7 +86,7 @@ export default function AnalyticsProvider({
}: PropsWithChildren<{
adminPage?: boolean;
demoPage?: boolean;
- dashboardProps?: dashboardProps;
+ dashboardProps?: AnalyticsDashboardProps;
}>) {
const searchParams = useSearchParams();
const pathname = usePathname();
diff --git a/apps/web/ui/analytics/index.tsx b/apps/web/ui/analytics/index.tsx
index e1e8355fe7..d8a17fb76c 100644
--- a/apps/web/ui/analytics/index.tsx
+++ b/apps/web/ui/analytics/index.tsx
@@ -8,7 +8,7 @@ import { cn } from "@dub/utils";
import AnalyticsProvider, {
AnalyticsContext,
- dashboardProps,
+ AnalyticsDashboardProps,
} from "./analytics-provider";
import Devices from "./devices";
import Locations from "./locations";
@@ -24,7 +24,7 @@ export default function Analytics({
}: {
adminPage?: boolean;
demoPage?: boolean;
- dashboardProps?: dashboardProps;
+ dashboardProps?: AnalyticsDashboardProps;
}) {
return (
<AnalyticsProvider {...{ adminPage, demoPage, dashboardProps }}>
diff --git a/apps/web/ui/modals/link-builder/password-modal.tsx b/apps/web/ui/modals/link-builder/password-modal.tsx
index b6c204ada4..f464229ccd 100644
--- a/apps/web/ui/modals/link-builder/password-modal.tsx
+++ b/apps/web/ui/modals/link-builder/password-modal.tsx
@@ -156,6 +156,7 @@ function PasswordModalInner({
<input
type={showPassword ? "text" : "password"}
placeholder="Create password"
+ data-1p-ignore
className={`${
errors.password
? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
diff --git a/apps/web/ui/modals/share-dashboard-modal.tsx b/apps/web/ui/modals/share-dashboard-modal.tsx
index 03986eb877..1340fb4cf9 100644
--- a/apps/web/ui/modals/share-dashboard-modal.tsx
+++ b/apps/web/ui/modals/share-dashboard-modal.tsx
@@ -1,8 +1,12 @@
import useWorkspace from "@/lib/swr/use-workspace";
-import { LinkProps } from "@/lib/types";
+import { DashboardProps, LinkProps } from "@/lib/types";
+import z from "@/lib/zod";
+import { updateDashboardBodySchema } from "@/lib/zod/schemas/dashboard";
import {
AnimatedSizeContainer,
+ Button,
Copy,
+ Input,
LinkLogo,
Modal,
Switch,
@@ -18,6 +22,7 @@ import {
linkConstructor,
} from "@dub/utils";
import { useCallback, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
import { toast } from "sonner";
import useSWR from "swr";
@@ -48,17 +53,37 @@ function ShareDashboardModalInner({
? `/api/links/info?${new URLSearchParams({ workspaceId, domain, key }).toString()}`
: undefined,
fetcher,
+ {
+ dedupingInterval: 60000,
+ },
);
- const { data, mutate } = useSWR<{ id: string }>(
+ const { data: dashboard, mutate } = useSWR<DashboardProps>(
link?.id
? `/api/links/${link.id}/dashboard?workspaceId=${workspaceId}`
: undefined,
fetcher,
{
- onSuccess: (data) => setChecked(Boolean(data)),
+ dedupingInterval: 60000,
+ onSuccess: (data) => {
+ setChecked(Boolean(data));
+ },
},
);
+ const [checked, setChecked] = useState(Boolean(dashboard));
+
+ const {
+ register,
+ handleSubmit,
+ watch,
+ setValue,
+ formState: { isDirty, isSubmitting },
+ } = useForm<z.infer<typeof updateDashboardBodySchema>>({
+ defaultValues: {
+ doIndex: dashboard?.doIndex ?? false,
+ password: dashboard?.password ?? null,
+ },
+ });
const [isCreating, setIsCreating] = useState(false);
const [copied, copyToClipboard] = useCopyToClipboard();
@@ -97,8 +122,34 @@ function ShareDashboardModalInner({
setIsCreating(false);
};
+ const handleUpdate = async (
+ formData: z.infer<typeof updateDashboardBodySchema>,
+ ) => {
+ if (!dashboard) {
+ return;
+ }
+
+ const res = await fetch(
+ `/api/dashboards/${dashboard.id}?workspaceId=${workspaceId}`,
+ {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(formData),
+ },
+ );
+
+ if (res.ok) {
+ await mutate();
+ toast.success("Saved changes.");
+ } else {
+ toast.error("Failed to save changes.");
+ }
+ };
+
const handleRemove = async () => {
- if (!data) {
+ if (!dashboard) {
return;
}
@@ -114,7 +165,7 @@ function ShareDashboardModalInner({
setIsRemoving(true);
const res = await fetch(
- `/api/dashboards/${data.id}?workspaceId=${workspaceId}`,
+ `/api/dashboards/${dashboard.id}?workspaceId=${workspaceId}`,
{
method: "DELETE",
},
@@ -131,8 +182,6 @@ function ShareDashboardModalInner({
setIsRemoving(false);
};
- const [checked, setChecked] = useState(Boolean(data));
-
return (
<>
<h3 className="border-b border-gray-200 px-4 py-4 text-lg font-medium sm:px-6">
@@ -144,7 +193,7 @@ function ShareDashboardModalInner({
height
transition={{ duration: 0.2, ease: "easeInOut" }}
>
- {data !== undefined ? (
+ {dashboard !== undefined ? (
<>
<label className="flex cursor-pointer items-center justify-between gap-2 pt-6">
<span className="flex items-center gap-2 text-sm text-gray-600">
@@ -158,18 +207,18 @@ function ShareDashboardModalInner({
/>
</label>
{checked &&
- (data ? (
+ (dashboard ? (
<div className="pt-4 text-sm">
<div className="divide-x-200 flex items-center justify-between divide-x overflow-hidden rounded-md border border-gray-200 bg-gray-100">
<div className="scrollbar-hide overflow-scroll pl-3">
<p className="whitespace-nowrap text-gray-400">
- {getPrettyUrl(`${APP_DOMAIN}/share/${data.id}`)}
+ {getPrettyUrl(`${APP_DOMAIN}/share/${dashboard.id}`)}
</p>
</div>
<button
className="flex h-8 items-center gap-2 whitespace-nowrap border-l bg-white px-3 hover:bg-gray-50 active:bg-gray-100"
onClick={() => {
- const url = `${APP_DOMAIN}/share/${data.id}`;
+ const url = `${APP_DOMAIN}/share/${dashboard.id}`;
toast.promise(copyToClipboard(url), {
success: "Copied to clipboard",
});
@@ -183,6 +232,53 @@ function ShareDashboardModalInner({
Copy link
</button>
</div>
+ <form
+ className="grid w-full gap-3 px-px pt-4"
+ onSubmit={handleSubmit(handleUpdate)}
+ >
+ <p className="text-base font-medium">Settings</p>
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-sm text-gray-600">
+ Search engine indexing
+ </p>
+ <Switch
+ checked={watch("doIndex")}
+ fn={(checked) => {
+ setValue("doIndex", checked, {
+ shouldDirty: true,
+ });
+ }}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-sm text-gray-600">
+ Require password
+ </p>
+ <Switch
+ checked={watch("password") !== null}
+ fn={(checked) => {
+ setValue("password", checked ? "" : null, {
+ shouldDirty: true,
+ });
+ }}
+ />
+ </div>
+ {watch("password") !== null && (
+ <Input
+ data-1p-ignore
+ type="password"
+ {...register("password")}
+ required
+ />
+ )}
+ <Button
+ type="submit"
+ loading={isSubmitting}
+ disabled={!isDirty}
+ text="Save changes"
+ className="h-9"
+ />
+ </form>
</div>
) : (
<div className="mt-4 h-7 w-full animate-pulse rounded-md bg-gray-200" />
diff --git a/packages/ui/src/input.tsx b/packages/ui/src/input.tsx
index 87bbfb4a81..c556476c73 100644
--- a/packages/ui/src/input.tsx
+++ b/packages/ui/src/input.tsx
@@ -1,6 +1,7 @@
import { cn } from "@dub/utils";
-import { AlertCircle, EyeIcon, EyeOffIcon } from "lucide-react";
+import { AlertCircle } from "lucide-react";
import React, { useCallback, useState } from "react";
+import { Eye, EyeSlash } from "./icons";
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {
@@ -58,12 +59,12 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
}
>
{isPasswordVisible ? (
- <EyeIcon
+ <Eye
className="size-4 flex-none text-gray-500 transition hover:text-gray-700"
aria-hidden
/>
) : (
- <EyeOffIcon
+ <EyeSlash
className="size-4 flex-none text-gray-500 transition hover:text-gray-700"
aria-hidden
/>