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 password-protected links

Steven Tey67d950508cb0
diff --git a/apps/web/app/protected/[domain]/[key]/action.ts b/apps/web/app/protected/[domain]/[key]/action.ts
index 25892911cb..18571c8b8f 100644
--- a/apps/web/app/protected/[domain]/[key]/action.ts
+++ b/apps/web/app/protected/[domain]/[key]/action.ts
@@ -1,5 +1,7 @@
"use server";
import prisma from "#/lib/prisma";
+import { linkConstructor } from "@dub/utils";
+import { redirect } from "next/navigation";
export async function verifyPassword(data: FormData) {
const domain = data.get("domain") as string;
@@ -14,12 +16,18 @@ export async function verifyPassword(data: FormData) {
if (!link) {
return { error: "Link not found" };
}
- const { url, password: realPassword } = link;
+ const { password: realPassword } = link;
const validPassword = password === realPassword;
if (validPassword) {
- return { url };
+ // if the password is valid, redirect to the link with the password in the query string
+ redirect(
+ `${linkConstructor({
+ domain,
+ key: rawKey,
+ })}?pw=${password}`,
+ );
} else {
return { error: "Invalid password" };
}
diff --git a/apps/web/app/protected/[domain]/[key]/form.tsx b/apps/web/app/protected/[domain]/[key]/form.tsx
index a809d51402..9b43325d44 100644
--- a/apps/web/app/protected/[domain]/[key]/form.tsx
+++ b/apps/web/app/protected/[domain]/[key]/form.tsx
@@ -2,7 +2,7 @@
import { AlertCircleFill } from "@/components/shared/icons";
import { Button } from "@dub/ui";
-import { useParams, useRouter } from "next/navigation";
+import { useParams } from "next/navigation";
import { useState } from "react";
import { experimental_useFormStatus as useFormStatus } from "react-dom";
import { toast } from "sonner";
@@ -13,19 +13,16 @@ export default function PasswordForm() {
domain: string;
key: string;
};
- const router = useRouter();
-
const [error, setError] = useState(false);
return (
<form
+ data-testid="password-form"
action={(data) =>
verifyPassword(data).then((res) => {
if (res.error) {
setError(true);
toast.error(res.error);
- } else {
- router.push(res.url!);
}
})
}
diff --git a/apps/web/app/protected/[domain]/[key]/loading.tsx b/apps/web/app/protected/[domain]/[key]/loading.tsx
new file mode 100644
index 0000000000..2895abfcc3
--- /dev/null
+++ b/apps/web/app/protected/[domain]/[key]/loading.tsx
@@ -0,0 +1,10 @@
+import { Background, LoadingSpinner } from "@dub/ui";
+
+export default function Loading() {
+ return (
+ <main className="flex h-screen w-screen items-center justify-center">
+ <LoadingSpinner />
+ <Background />
+ </main>
+ );
+}
diff --git a/apps/web/app/protected/[domain]/[key]/page.tsx b/apps/web/app/protected/[domain]/[key]/page.tsx
index 807d11862d..8df10d43a5 100644
--- a/apps/web/app/protected/[domain]/[key]/page.tsx
+++ b/apps/web/app/protected/[domain]/[key]/page.tsx
@@ -1,6 +1,8 @@
import { Background, Logo } from "@dub/ui";
import { constructMetadata } from "@dub/utils";
+import prisma from "#/lib/prisma";
import PasswordForm from "./form";
+import { notFound, redirect } from "next/navigation";
const title = "Password Required";
const description =
@@ -14,15 +16,81 @@ export const metadata = constructMetadata({
noIndex: true,
});
-export default function PasswordProtectedLinkPage() {
+export async function generateStaticParams() {
+ const passwordProtectedLinks = await prisma.link.findMany({
+ where: {
+ password: {
+ not: null,
+ },
+ },
+ select: {
+ domain: true,
+ key: true,
+ },
+ });
+
+ return passwordProtectedLinks.map(({ domain, key }) => ({
+ params: {
+ domain,
+ key: encodeURIComponent(key),
+ },
+ }));
+}
+
+export default async function PasswordProtectedLinkPage({
+ params,
+}: {
+ params: { domain: string; key: string };
+}) {
+ const domain = params.domain;
+ const key = decodeURIComponent(params.key);
+
+ const link = await prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain,
+ key,
+ },
+ },
+ select: {
+ password: true,
+ url: true,
+ project: {
+ select: {
+ name: true,
+ logo: true,
+ plan: true,
+ },
+ },
+ },
+ });
+
+ if (!link) {
+ notFound();
+ }
+
+ if (!link.password) {
+ redirect(link.url);
+ }
+
return (
<main className="flex h-screen w-screen items-center justify-center">
<Background />
<div className="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">
- <a href="https://dub.co" target="_blank" rel="noreferrer">
- <Logo />
- </a>
+ {domain !== "dub.sh" &&
+ link.project?.plan !== "free" &&
+ link.project?.logo ? (
+ <img
+ src={link.project.logo}
+ alt={link.project.name}
+ className="h-10 w-10 rounded-full"
+ />
+ ) : (
+ <a href="https://dub.co" target="_blank" rel="noreferrer">
+ <Logo />
+ </a>
+ )}
<h3 className="text-xl font-semibold">{title}</h3>
<p className="text-sm text-gray-500">{description}</p>
</div>
diff --git a/apps/web/app/ui/modals/add-edit-link-modal/index.tsx b/apps/web/app/ui/modals/add-edit-link-modal/index.tsx
index afbe2c0a55..724432222a 100644
--- a/apps/web/app/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/app/ui/modals/add-edit-link-modal/index.tsx
@@ -136,6 +136,7 @@ function AddEditLinkModal({
useEffect(() => {
// if there's a password, no need to generate metatags
if (password) {
+ setGeneratingMetatags(false);
setData((prev) => ({
...prev,
title: "Password Required",
diff --git a/apps/web/components/app/modals/add-edit-link-modal/index.tsx b/apps/web/components/app/modals/add-edit-link-modal/index.tsx
index 00fdf2c1ad..090a63dd9c 100644
--- a/apps/web/components/app/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/components/app/modals/add-edit-link-modal/index.tsx
@@ -145,6 +145,7 @@ function AddEditLinkModal({
useEffect(() => {
// if there's a password, no need to generate metatags
if (password) {
+ setGeneratingMetatags(false);
setData((prev) => ({
...prev,
title: "Password Required",
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index fdcd747c8f..8fe92d54d1 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -10,6 +10,7 @@ import {
userAgent,
} from "next/server";
import { isBlacklistedReferrer } from "../edge-config";
+import { getLinkViaEdge } from "../planetscale";
export default async function LinkMiddleware(
req: NextRequest,
@@ -74,16 +75,26 @@ export default async function LinkMiddleware(
);
}
- // special case for link health monitoring with planetfall.io :)
- if (!req.headers.get("dub-no-track")) {
- ev.waitUntil(recordClick(domain, req, key)); // track the click only if there is no `dub-no-track` header
+ if (password) {
+ const pw = req.nextUrl.searchParams.get("pw");
+
+ // rewrite to auth page (/protected/[domain]/[key]) if:
+ // - no `pw` param is provided
+ // - the `pw` param is incorrect
+ // this will also ensure that no clicks are tracked unless the password is correct
+ if (!pw || (await getLinkViaEdge(domain, key))?.password !== pw) {
+ return NextResponse.rewrite(
+ new URL(`/protected/${domain}/${encodeURIComponent(key)}`, req.url),
+ );
+ } else if (pw) {
+ // strip it from the URL if it's correct
+ req.nextUrl.searchParams.delete("pw");
+ }
}
- if (password) {
- // rewrite to auth page (/protected/[domain]/[key]) if the link is password protected
- return NextResponse.rewrite(
- new URL(`/protected/${domain}/${encodeURIComponent(key)}`, req.url),
- );
+ // only track the click when there is no `dub-no-track` header
+ if (!req.headers.get("dub-no-track")) {
+ ev.waitUntil(recordClick(domain, req, key));
}
const isBot = detectBot(req);
diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.ts
index 39cffc785f..6a293d4219 100644
--- a/apps/web/lib/planetscale.ts
+++ b/apps/web/lib/planetscale.ts
@@ -28,7 +28,7 @@ export const getLinkViaEdge = async (domain: string, key: string) => {
const { rows } =
(await conn.execute(
- "SELECT `key`, url, proxy, title, description, image, clicks, userId, publicStats FROM Link WHERE domain = ? AND `key` = ?",
+ "SELECT `key`, url, password, proxy, title, description, image, clicks, userId, publicStats FROM Link WHERE domain = ? AND `key` = ?",
[domain, decodeURIComponent(key)], // we need to make sure that the key is always decoded (cause that's how we store it in MySQL)
)) || {};
@@ -36,6 +36,7 @@ export const getLinkViaEdge = async (domain: string, key: string) => {
? (rows[0] as {
key: string;
url: string;
+ password: string | null;
proxy: number;
title: string;
description: string;