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.

fixed stats

Steven Tey02f7b751d2d5
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/auth.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/auth.tsx
index e4abe8e36d..81016a22a0 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/auth.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/auth.tsx
@@ -1,15 +1,24 @@
"use client";
+import useDomains from "@/lib/swr/use-domains";
import useProject from "@/lib/swr/use-project";
import ProjectExceededUsage from "@/ui/projects/project-exceeded-usage";
-import { ReactNode } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import { ReactNode, useEffect } from "react";
export default function AnalyticsAuth({ children }: { children: ReactNode }) {
- const { exceededUsage } = useProject();
-
+ const { slug, exceededUsage } = useProject();
if (exceededUsage) {
return <ProjectExceededUsage />;
}
+ const router = useRouter();
+ const { primaryDomain } = useDomains();
+ const searchParams = useSearchParams();
+ useEffect(() => {
+ if (!searchParams?.get("domain")) {
+ router.replace(`/${slug}/analytics?domain=${primaryDomain}`);
+ }
+ }, [primaryDomain, router, searchParams]);
return children;
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/page.tsx
index 08ed29e1bd..6dc6f605a5 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/page.tsx
@@ -5,10 +5,10 @@ import LayoutLoader from "@/ui/layout/layout-loader";
export default function ProjectAnalytics() {
return (
- <AnalyticsAuth>
- <Suspense fallback={<LayoutLoader />}>
+ <Suspense fallback={<LayoutLoader />}>
+ <AnalyticsAuth>
<Stats />
- </Suspense>
- </AnalyticsAuth>
+ </AnalyticsAuth>
+ </Suspense>
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/analytics/auth.tsx b/apps/web/app/app.dub.co/(dashboard)/analytics/auth.tsx
new file mode 100644
index 0000000000..19c9a70d40
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/analytics/auth.tsx
@@ -0,0 +1,28 @@
+import { getSession } from "@/lib/auth-app";
+import { getLink } from "@/lib/fetchers";
+import LinkNotFound from "@/ui/links/link-not-found";
+
+export default async function AnalyticsAuth({
+ searchParams,
+ children,
+}: {
+ searchParams: { [key: string]: string | undefined };
+ children: React.ReactNode;
+}) {
+ if (!searchParams?.key) {
+ return <LinkNotFound />;
+ }
+ const [session, link] = await Promise.all([
+ getSession(),
+ getLink({
+ domain: searchParams.domain || "dub.sh",
+ key: searchParams.key || "github",
+ }),
+ ]);
+
+ if (session?.user?.id !== link?.userId) {
+ return <LinkNotFound />;
+ }
+
+ return children as JSX.Element;
+}
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 030da40b56..54498d28d7 100644
--- a/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx
@@ -1,16 +1,13 @@
-import { getSession } from "@/lib/auth-app";
-import { getLink } from "@/lib/fetchers";
import LayoutLoader from "@/ui/layout/layout-loader";
-import LinkNotFound from "@/ui/links/link-not-found";
import Stats from "@/ui/stats";
import { Suspense } from "react";
+import AnalyticsAuth from "./auth";
export default function LinkAnalytics({
searchParams,
}: {
searchParams: { [key: string]: string | undefined };
}) {
- console.log({ searchParams });
return (
<Suspense fallback={<LayoutLoader />}>
<AnalyticsAuth searchParams={searchParams}>
@@ -19,25 +16,3 @@ export default function LinkAnalytics({
</Suspense>
);
}
-
-async function AnalyticsAuth({
- searchParams,
- children,
-}: {
- searchParams: { [key: string]: string | undefined };
- children: React.ReactNode;
-}) {
- const [session, link] = await Promise.all([
- getSession(),
- getLink({
- domain: searchParams.domain || "dub.sh",
- key: searchParams.key || "github",
- }),
- ]);
-
- if (session?.user?.id !== link?.userId) {
- return <LinkNotFound />;
- }
-
- return children as JSX.Element;
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/loading.tsx b/apps/web/app/app.dub.co/(dashboard)/loading.tsx
new file mode 100644
index 0000000000..7ccd211a71
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/ui/layout/layout-loader";
diff --git a/apps/web/lib/auth-app.ts b/apps/web/lib/auth-app.ts
index 8d215a529d..7531f26b00 100644
--- a/apps/web/lib/auth-app.ts
+++ b/apps/web/lib/auth-app.ts
@@ -1,6 +1,6 @@
-import { NextRequest } from "next/server";
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";
@@ -35,24 +35,24 @@ interface WithAuthHandler {
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,
{
- 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;
@@ -65,74 +65,95 @@ const withAuth =
}
const searchParams = getSearchParams(req.url);
- const { slug } = searchParams;
+ const { slug, domain, key } = searchParams;
- // it's a project
- if (slug) {
- 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: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
- },
+ const [project, link] = (await Promise.all([
+ slug &&
+ (await prisma.project.findUnique({
+ where: {
+ slug,
},
- },
- })) as ProjectProps;
-
- if (project && project.users) {
- // 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: {
+ 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,
},
},
- select: {
- expires: true,
+ },
+ })),
+ domain &&
+ key &&
+ prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain,
+ key,
},
- });
- 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,
- });
- }
- }
- } else {
+ },
+ }),
+ ])) 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 the action doesn't need to be gated for GET requests, return handler now
- if (req.method === "GET" && excludeGet) {
- return handler({ req, params, searchParams, session, project });
+ 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 (
@@ -161,11 +182,16 @@ const withAuth =
status: 403,
});
}
+ }
- return handler({ req, params, searchParams, session, project });
+ // check for Dub.sh links
+ if (domain === "dub.sh" && link && link.userId !== session.user.id) {
+ return new Response("Unauthorized: Invalid link.", {
+ status: 401,
+ });
}
- return handler({ req, params, searchParams, session });
+ return handler({ req, params, searchParams, session, project, link });
};
export { withAuth };
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index bc71e987ad..9123d990b5 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -32,7 +32,6 @@ export interface ProjectProps {
stripeId?: string;
billingCycleStart?: number;
createdAt?: Date;
-
domains?: {
slug: string;
}[];
diff --git a/apps/web/ui/domains/domain-card.tsx b/apps/web/ui/domains/domain-card.tsx
index 135e977197..49b111711c 100644
--- a/apps/web/ui/domains/domain-card.tsx
+++ b/apps/web/ui/domains/domain-card.tsx
@@ -60,7 +60,7 @@ export default function DomainCard({ props }: { props: DomainProps }) {
</a>
<NumberTooltip value={clicks}>
<Link
- href={`/${slug}/analytics?domain=${domain}&key=_root`}
+ href={`/${slug}/analytics?domain=${domain}`}
className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100"
>
<Chart className="h-4 w-4" />
diff --git a/apps/web/ui/layout/nav-tabs.tsx b/apps/web/ui/layout/nav-tabs.tsx
index 0363db2b03..6d9b099b0d 100644
--- a/apps/web/ui/layout/nav-tabs.tsx
+++ b/apps/web/ui/layout/nav-tabs.tsx
@@ -18,7 +18,8 @@ export default function NavTabs() {
const { loading, error } = useProject();
const tabs = useMemo(() => {
- const isDomainAnalytics = searchParams?.get("key") === "_root";
+ const isDomainAnalytics =
+ searchParams?.get("domain") && !searchParams?.get("key");
if (slug) {
if (pathname?.endsWith("/analytics")) {
diff --git a/apps/web/ui/stats/bar-chart.tsx b/apps/web/ui/stats/bar-chart.tsx
index 6af973341e..5d06d71167 100644
--- a/apps/web/ui/stats/bar-chart.tsx
+++ b/apps/web/ui/stats/bar-chart.tsx
@@ -1,4 +1,4 @@
-import { LoadingCircle, useMediaQuery } from "@dub/ui";
+import { LoadingSpinner, useMediaQuery } from "@dub/ui";
import { fetcher, nFormatter } from "@dub/utils";
import { AxisBottom, AxisLeft } from "@visx/axis";
import { localPoint } from "@visx/event";
@@ -251,7 +251,7 @@ export default function BarChart() {
)}
</>
) : (
- <LoadingCircle />
+ <LoadingSpinner />
)}
</figure>
);
diff --git a/apps/web/ui/stats/devices.tsx b/apps/web/ui/stats/devices.tsx
index 3b461c3b7e..8fab1bf7f1 100644
--- a/apps/web/ui/stats/devices.tsx
+++ b/apps/web/ui/stats/devices.tsx
@@ -1,5 +1,5 @@
import { DeviceTabs, uaToBot } from "@/lib/stats";
-import { LoadingCircle, Modal, TabSelect } from "@dub/ui";
+import { LoadingSpinner, Modal, TabSelect } from "@dub/ui";
import { fetcher } from "@dub/utils";
import { Maximize } from "lucide-react";
import { useContext, useState } from "react";
@@ -76,7 +76,7 @@ export default function Devices() {
)
) : (
<div className="flex h-[300px] items-center justify-center">
- <LoadingCircle />
+ <LoadingSpinner />
</div>
)}
{!modal && data && data.length > 9 && (
diff --git a/apps/web/ui/stats/index.tsx b/apps/web/ui/stats/index.tsx
index eae58addf2..9191fec54f 100644
--- a/apps/web/ui/stats/index.tsx
+++ b/apps/web/ui/stats/index.tsx
@@ -86,14 +86,16 @@ export default function Stats({
baseApiPath: `/api/edge/stats`,
domain: staticDomain,
};
- }, [slug, key, pathname]);
+ }, [slug, pathname, staticDomain, domainSlug, key]);
- const queryString = new URLSearchParams({
- ...(slug && { slug }),
- domain: domain!,
- ...(key && { key }),
- ...(interval && { interval }),
- }).toString();
+ const queryString = useMemo(() => {
+ return new URLSearchParams({
+ ...(slug && { slug }),
+ domain: domain!,
+ ...(key && { key }),
+ ...(interval && { interval }),
+ }).toString();
+ }, [slug, domain, key, interval]);
const { data: totalClicks } = useSWR<number>(
`${baseApiPath}/clicks?${queryString}`,
diff --git a/apps/web/ui/stats/locations.tsx b/apps/web/ui/stats/locations.tsx
index ab0ba68cbb..a282356b8b 100644
--- a/apps/web/ui/stats/locations.tsx
+++ b/apps/web/ui/stats/locations.tsx
@@ -1,5 +1,5 @@
import { LocationTabs } from "@/lib/stats";
-import { LoadingCircle, Modal, TabSelect } from "@dub/ui";
+import { LoadingSpinner, Modal, TabSelect } from "@dub/ui";
import { COUNTRIES, fetcher } from "@dub/utils";
import { Maximize } from "lucide-react";
import { useContext, useState } from "react";
@@ -74,7 +74,7 @@ export default function Locations() {
)
) : (
<div className="flex h-[300px] items-center justify-center">
- <LoadingCircle />
+ <LoadingSpinner />
</div>
)}
{!modal && data && data.length > 9 && (
diff --git a/apps/web/ui/stats/referer.tsx b/apps/web/ui/stats/referer.tsx
index da4c2fbd7a..0a50770ab7 100644
--- a/apps/web/ui/stats/referer.tsx
+++ b/apps/web/ui/stats/referer.tsx
@@ -1,5 +1,5 @@
import { BlurImage } from "@/ui/shared/blur-image";
-import { LoadingCircle, Modal } from "@dub/ui";
+import { LoadingSpinner, Modal } from "@dub/ui";
import { GOOGLE_FAVICON_URL, fetcher } from "@dub/utils";
import { Link2, Maximize } from "lucide-react";
import { useContext, useState } from "react";
@@ -71,7 +71,7 @@ export default function Referer() {
)
) : (
<div className="flex h-[300px] items-center justify-center">
- <LoadingCircle />
+ <LoadingSpinner />
</div>
)}
{!modal && data && data.length > 9 && (
diff --git a/apps/web/ui/stats/toggle.tsx b/apps/web/ui/stats/toggle.tsx
index 898eb0d6d4..868ed504d1 100644
--- a/apps/web/ui/stats/toggle.tsx
+++ b/apps/web/ui/stats/toggle.tsx
@@ -49,19 +49,23 @@ export default function Toggle() {
})}
>
<div className="mx-auto flex h-20 max-w-4xl flex-col items-center justify-between space-y-3 px-2.5 md:h-10 md:flex-row md:space-y-0 lg:px-0">
- <a
- className="group flex text-lg font-semibold text-gray-800 md:text-xl"
- href={linkConstructor({ key, domain })}
- target="_blank"
- rel="noreferrer"
- >
- {linkConstructor({
- key,
- domain: domain ? punycode.toUnicode(domain) : undefined,
- pretty: true,
- })}
- <ExpandingArrow className="h-5 w-5" />
- </a>
+ {domain ? (
+ <a
+ className="group flex text-lg font-semibold text-gray-800 md:text-xl"
+ href={linkConstructor({ key, domain })}
+ target="_blank"
+ rel="noreferrer"
+ >
+ {linkConstructor({
+ key,
+ domain: punycode.toUnicode(domain),
+ pretty: true,
+ })}
+ <ExpandingArrow className="h-5 w-5" />
+ </a>
+ ) : (
+ <div />
+ )}
<div className="flex items-center">
{!isPublicStatsPage && key && key !== "_root" && <SharePopover />}
<Popover
@@ -110,7 +114,7 @@ export default function Toggle() {
? `interval=${value}`
: `${new URLSearchParams({
domain: domain!,
- ...(key && { key }),
+ ...(key && key !== "_root" && { key }),
interval: value,
}).toString()}`
}`}