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 invite link feature

Steven Tey9983094698b1
diff --git a/apps/web/app/api/projects/[slug]/invites/accept/route.ts b/apps/web/app/api/projects/[slug]/invites/accept/route.ts
index b7b5f95bfe..09ec131113 100644
--- a/apps/web/app/api/projects/[slug]/invites/accept/route.ts
+++ b/apps/web/app/api/projects/[slug]/invites/accept/route.ts
@@ -1,5 +1,7 @@
+import { exceededLimitError } from "@/lib/api/errors";
import { withSession } from "@/lib/auth";
import prisma from "@/lib/prisma";
+import { PlanProps } from "@/lib/types";
import { NextResponse } from "next/server";
// POST /api/projects/[slug]/invites/accept – accept a project invite
@@ -13,31 +15,59 @@ export const POST = withSession(async ({ session, params }) => {
},
select: {
expires: true,
- projectId: true,
+ project: {
+ select: {
+ id: true,
+ plan: true,
+ usersLimit: true,
+ _count: {
+ select: {
+ users: true,
+ },
+ },
+ },
+ },
},
});
if (!invite) {
return new Response("Invalid invite", { status: 404 });
- } else if (invite.expires < new Date()) {
+ }
+
+ if (invite.expires < new Date()) {
return new Response("Invite expired", { status: 410 });
- } else {
- const response = await Promise.all([
- prisma.projectUsers.create({
- data: {
- userId: session.user.id,
- role: "member",
- projectId: invite.projectId,
- },
- }),
- prisma.projectInvite.delete({
- where: {
- email_projectId: {
- email: session.user.email,
- projectId: invite.projectId,
- },
- },
+ }
+
+ const project = invite.project;
+
+ if (project._count.users >= project.usersLimit) {
+ return new Response(
+ exceededLimitError({
+ plan: project.plan as PlanProps,
+ limit: project.usersLimit,
+ type: "users",
}),
- ]);
- return NextResponse.json(response);
+ {
+ status: 403,
+ },
+ );
}
+
+ const response = await Promise.all([
+ prisma.projectUsers.create({
+ data: {
+ userId: session.user.id,
+ role: "member",
+ projectId: project.id,
+ },
+ }),
+ prisma.projectInvite.delete({
+ where: {
+ email_projectId: {
+ email: session.user.email,
+ projectId: project.id,
+ },
+ },
+ }),
+ ]);
+ return NextResponse.json(response);
});
diff --git a/apps/web/app/api/projects/[slug]/invites/reset/route.ts b/apps/web/app/api/projects/[slug]/invites/reset/route.ts
new file mode 100644
index 0000000000..ae2170a865
--- /dev/null
+++ b/apps/web/app/api/projects/[slug]/invites/reset/route.ts
@@ -0,0 +1,22 @@
+import { withAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { nanoid } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+export const POST = withAuth(
+ async ({ project }) => {
+ const response = await prisma.project.update({
+ where: {
+ id: project.id,
+ },
+ data: {
+ inviteCode: nanoid(24),
+ },
+ });
+
+ return NextResponse.json(response);
+ },
+ {
+ requiredRole: ["owner"],
+ },
+);
diff --git a/apps/web/app/api/projects/[slug]/invites/route.tsx b/apps/web/app/api/projects/[slug]/invites/route.tsx
index faff461fe2..8598f529aa 100644
--- a/apps/web/app/api/projects/[slug]/invites/route.tsx
+++ b/apps/web/app/api/projects/[slug]/invites/route.tsx
@@ -1,5 +1,5 @@
import { exceededLimitError } from "@/lib/api/errors";
-import { inviteUser } from "@/lib/api/users";
+import { inviteChecks, inviteUser } from "@/lib/api/users";
import { withAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
@@ -22,31 +22,18 @@ export const GET = withAuth(async ({ project }) => {
export const POST = withAuth(
async ({ req, project, session }) => {
const { email } = await req.json();
- const alreadyInTeam = await prisma.projectUsers.findFirst({
- where: {
- projectId: project.id,
- user: {
- email,
- },
- },
+ const [alreadyInTeam, projectUserCount] = await inviteChecks({
+ projectId: project.id,
+ email,
});
+
if (alreadyInTeam) {
return new Response("User already exists in this project.", {
status: 400,
});
}
- const users = await prisma.projectUsers.count({
- where: {
- projectId: project.id,
- },
- });
- const invites = await prisma.projectInvite.count({
- where: {
- projectId: project.id,
- },
- });
- if (users + invites >= project.usersLimit) {
+ if (projectUserCount >= project.usersLimit) {
return new Response(
exceededLimitError({
plan: project.plan,
diff --git a/apps/web/app/api/projects/route.ts b/apps/web/app/api/projects/route.ts
index ce9e9f070e..89f6dda699 100644
--- a/apps/web/app/api/projects/route.ts
+++ b/apps/web/app/api/projects/route.ts
@@ -10,6 +10,7 @@ import prisma from "@/lib/prisma";
import {
DEFAULT_REDIRECTS,
FREE_PROJECTS_LIMIT,
+ nanoid,
validSlugRegex,
} from "@dub/utils";
import { NextResponse } from "next/server";
@@ -132,6 +133,7 @@ export const POST = withSession(async ({ req, session }) => {
},
}),
billingCycleStart: new Date().getDate(),
+ inviteCode: nanoid(24),
},
include: {
domains: true,
diff --git a/apps/web/app/app.dub.co/(auth)/invites/[code]/page.tsx b/apps/web/app/app.dub.co/(auth)/invites/[code]/page.tsx
new file mode 100644
index 0000000000..49fa154e67
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/invites/[code]/page.tsx
@@ -0,0 +1,93 @@
+import { inviteChecks } from "@/lib/api/users";
+import { getSession } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { LoadingSpinner, Logo } from "@dub/ui";
+import { APP_NAME, TWO_WEEKS_IN_SECONDS } from "@dub/utils";
+import { redirect } from "next/navigation";
+import { Suspense } from "react";
+
+export const runtime = "nodejs";
+
+export default function InvitesPage({
+ params,
+}: {
+ params: {
+ code: string;
+ };
+}) {
+ return (
+ <div className="flex h-screen flex-col items-center justify-center space-y-6 text-center">
+ <Logo className="h-12 w-12" />
+ <Suspense
+ fallback={
+ <>
+ <h1 className="font-display text-4xl font-bold">
+ Verifying Invite
+ </h1>
+ <p className="text-lg text-gray-600">
+ {APP_NAME} is verifying your invite link.
+ <br /> Please wait...
+ </p>
+ <LoadingSpinner className="h-7 w-7" />
+ </>
+ }
+ >
+ <VerifyInvite code={params.code} />
+ </Suspense>
+ </div>
+ );
+}
+
+async function VerifyInvite({ code }: { code: string }) {
+ const session = await getSession();
+
+ if (!session) {
+ redirect("/login");
+ }
+
+ // fake promise 3s
+ const project = await prisma.project.findUnique({
+ select: {
+ id: true,
+ slug: true,
+ usersLimit: true,
+ },
+ where: {
+ inviteCode: code,
+ },
+ });
+
+ if (!project) {
+ redirect("/");
+ }
+
+ const [alreadyInTeam, projectUserCount] = await inviteChecks({
+ projectId: project.id,
+ email: session.user.email,
+ });
+
+ if (alreadyInTeam) {
+ redirect(`/${project.slug}`);
+ }
+
+ if (projectUserCount >= project.usersLimit) {
+ return (
+ <>
+ <h1 className="font-display text-4xl font-bold">User Limit Reached</h1>
+ <p className="text-lg text-gray-600">
+ This project has reached its user limit.
+ </p>
+ </>
+ );
+ }
+
+ await prisma.projectInvite.create({
+ data: {
+ email: session.user.email,
+ expires: new Date(Date.now() + TWO_WEEKS_IN_SECONDS * 1000),
+ projectId: project.id,
+ },
+ });
+
+ redirect(`/${project.slug}`);
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/people/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/people/page-client.tsx
index 42e4884cce..fcfedd392f 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/people/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/people/page-client.tsx
@@ -4,10 +4,11 @@ import useProject from "@/lib/swr/use-project";
import useUsers from "@/lib/swr/use-users";
import { UserProps } from "@/lib/types";
import { useEditRoleModal } from "@/ui/modals/edit-role-modal";
+import { useInviteCodeModal } from "@/ui/modals/invite-code-modal";
import { useInviteTeammateModal } from "@/ui/modals/invite-teammate-modal";
import { useRemoveTeammateModal } from "@/ui/modals/remove-teammate-modal";
-import { ThreeDots } from "@/ui/shared/icons";
-import { Avatar, Badge, IconMenu, Popover } from "@dub/ui";
+import { Link as LinkIcon, ThreeDots } from "@/ui/shared/icons";
+import { Avatar, Badge, Button, IconMenu, Popover } from "@dub/ui";
import { cn, timeAgo } from "@dub/utils";
import { UserMinus } from "lucide-react";
import { useSession } from "next-auth/react";
@@ -19,6 +20,8 @@ export default function ProjectPeopleClient() {
const { setShowInviteTeammateModal, InviteTeammateModal } =
useInviteTeammateModal();
+ const { setShowInviteCodeModal, InviteCodeModal } = useInviteCodeModal();
+
const [currentTab, setCurrentTab] = useState<"Members" | "Invitations">(
"Members",
);
@@ -28,6 +31,7 @@ export default function ProjectPeopleClient() {
return (
<>
<InviteTeammateModal />
+ <InviteCodeModal />
<div className="rounded-lg border border-gray-200 bg-white">
<div className="flex flex-col items-center justify-between space-y-3 p-5 sm:flex-row sm:space-y-0 sm:p-10">
<div className="flex flex-col space-y-3">
@@ -36,12 +40,19 @@ export default function ProjectPeopleClient() {
Teammates that have access to this project.
</p>
</div>
- <button
- onClick={() => setShowInviteTeammateModal(true)}
- className="h-9 w-full rounded-md border border-black bg-black px-6 text-sm text-white transition-all duration-150 ease-in-out hover:bg-white hover:text-black focus:outline-none sm:w-auto"
- >
- Invite
- </button>
+ <div className="flex space-x-2">
+ <Button
+ text="Invite"
+ onClick={() => setShowInviteTeammateModal(true)}
+ className="h-9"
+ />
+ <Button
+ icon={<LinkIcon className="h-4 w-4 text-gray-800" />}
+ variant="secondary"
+ onClick={() => setShowInviteCodeModal(true)}
+ className="h-9"
+ />
+ </div>
</div>
<div className="flex space-x-3 border-b border-gray-200 px-3 sm:px-7">
{tabs.map((tab) => (
@@ -186,8 +197,8 @@ const UserCard = ({
session?.user?.email === email
? "Leave project"
: currentTab === "Members"
- ? "Remove teammate"
- : "Revoke invite"
+ ? "Remove teammate"
+ : "Revoke invite"
}
icon={<UserMinus className="h-4 w-4" />}
/>
diff --git a/apps/web/lib/api/users.ts b/apps/web/lib/api/users.ts
index 228fa42545..ca340e9105 100644
--- a/apps/web/lib/api/users.ts
+++ b/apps/web/lib/api/users.ts
@@ -1,10 +1,35 @@
import { Session, hashToken } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { ProjectProps } from "@/lib/types";
+import { TWO_WEEKS_IN_SECONDS } from "@dub/utils";
import { randomBytes } from "crypto";
import { sendEmail } from "emails";
import ProjectInvite from "emails/project-invite";
+export async function inviteChecks({
+ projectId,
+ email,
+}: {
+ projectId: string;
+ email: string;
+}) {
+ return await Promise.all([
+ prisma.projectUsers.findFirst({
+ where: {
+ projectId,
+ user: {
+ email,
+ },
+ },
+ }),
+ prisma.projectUsers.count({
+ where: {
+ projectId,
+ },
+ }),
+ ]);
+}
+
export async function inviteUser({
email,
project,
@@ -16,7 +41,6 @@ export async function inviteUser({
}) {
// same method of generating a token as next-auth
const token = randomBytes(32).toString("hex");
- const TWO_WEEKS_IN_SECONDS = 60 * 60 * 24 * 14;
const expires = new Date(Date.now() + TWO_WEEKS_IN_SECONDS * 1000);
// create a project invite record and a verification request token that lasts for a week
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index aea552bcfe..63a720cdf1 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -233,6 +233,7 @@ export const withAuth =
primary: true,
},
},
+ inviteCode: true,
metadata: true,
},
}),
diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.ts
index 3ac8dd6558..1e46ecaf6d 100644
--- a/apps/web/lib/middleware/app.ts
+++ b/apps/web/lib/middleware/app.ts
@@ -1,7 +1,6 @@
import { parse } from "@/lib/middleware/utils";
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
-import { conn } from "../planetscale";
import { UserProps } from "../types";
export default async function AppMiddleware(req: NextRequest) {
@@ -36,41 +35,7 @@ export default async function AppMiddleware(req: NextRequest) {
new Date(session?.user?.createdAt).getTime() > Date.now() - 10000 &&
path === "/"
) {
- // check if the user has an existing project invite, if yes, we skip the onboarding flow
- const [existingInvite, existingProject] = [
- await conn
- ?.execute("SELECT projectId FROM ProjectInvite WHERE email = ?", [
- session.email,
- ])
- .then((res) => res.rows[0] as { projectId: string } | undefined),
- await conn
- ?.execute("SELECT projectId FROM ProjectUsers WHERE userId = ?", [
- session.user.id,
- ])
- .then((res) => res.rows[0] as { projectId: string } | undefined),
- ];
-
- // if there's an existing invite or there's an existing project
- if (existingInvite || existingProject) {
- // get the project slug
- const project = await conn
- ?.execute("SELECT slug from Project WHERE id = ?", [
- existingInvite
- ? existingInvite.projectId
- : existingProject?.projectId,
- ])
- .then((res) => res.rows[0] as { slug: string } | undefined);
-
- // redirect them to the project slug
- if (project?.slug) {
- return NextResponse.redirect(new URL(project.slug, req.url));
- } else {
- return NextResponse.redirect(new URL("/", req.url));
- }
- } else {
- // if there's no existing invite, redirect to /welcome flow
- return NextResponse.redirect(new URL("/welcome", req.url));
- }
+ return NextResponse.redirect(new URL("/welcome", req.url));
// if the path is /login or /register, redirect to "/"
} else if (path === "/login" || path === "/register") {
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 1de9cfd803..a2d3efaee5 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -86,6 +86,7 @@ export interface ProjectProps {
metadata?: {
defaultDomains?: string[];
};
+ inviteCode: string;
}
export interface ProjectWithDomainProps extends ProjectProps {
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index c7727864ad..e3cb051f7f 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -109,7 +109,9 @@ model Project {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
- metadata Json? @default("{\"defaultDomains\":[\"dub.sh\",\"chatg.pt\",\"spti.fi\",\"amzn.id\"]}")
+
+ inviteCode String? @unique
+ metadata Json? @default("{\"defaultDomains\":[\"dub.sh\",\"chatg.pt\",\"spti.fi\",\"amzn.id\"]}")
}
model ProjectInvite {
@@ -228,6 +230,9 @@ model Link {
tag Tag? @relation(fields: [tagId], references: [id])
tagId String?
+ // (Upcoming) multiple link tags
+ tags LinkTag[]
+
// Comments on the particular shortlink
comments String? @db.LongText
@@ -256,11 +261,26 @@ model Tag {
project Project @relation(fields: [projectId], references: [id], onUpdate: Cascade, onDelete: Cascade)
projectId String
links Link[]
+ linksNew LinkTag[]
@@unique([name, projectId])
@@index(projectId)
}
+model LinkTag {
+ id String @id @default(cuid())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ link Link @relation(fields: [linkId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ linkId String
+ tag Tag @relation(fields: [tagId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ tagId String
+
+ @@unique([linkId, tagId])
+ @@index(linkId)
+ @@index(tagId)
+}
+
model jackson_index {
id Int @id @default(autoincrement())
key String @db.VarChar(250)
diff --git a/apps/web/scripts/seed-invite-codes.ts b/apps/web/scripts/seed-invite-codes.ts
new file mode 100644
index 0000000000..fcf8b878e0
--- /dev/null
+++ b/apps/web/scripts/seed-invite-codes.ts
@@ -0,0 +1,32 @@
+import prisma from "@/lib/prisma";
+import "dotenv-flow/config";
+import { nanoid } from "./utils";
+
+async function main() {
+ const projects = await prisma.project.findMany({
+ select: {
+ id: true,
+ },
+ where: {
+ inviteCode: null,
+ },
+ take: 1000,
+ });
+
+ const res = await Promise.all(
+ projects.map(async ({ id }) => {
+ return prisma.project.update({
+ where: {
+ id,
+ },
+ data: {
+ inviteCode: nanoid(24),
+ },
+ });
+ }),
+ );
+
+ console.log(res.length);
+}
+
+main();
diff --git a/apps/web/ui/modals/invite-code-modal.tsx b/apps/web/ui/modals/invite-code-modal.tsx
new file mode 100644
index 0000000000..3dd9e39630
--- /dev/null
+++ b/apps/web/ui/modals/invite-code-modal.tsx
@@ -0,0 +1,85 @@
+import useProject from "@/lib/swr/use-project";
+import { Button, CopyButton, Logo, Modal } from "@dub/ui";
+import { APP_DOMAIN } from "@dub/utils";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+
+function InviteCodeModal({
+ showInviteCodeModal,
+ setShowInviteCodeModal,
+}: {
+ showInviteCodeModal: boolean;
+ setShowInviteCodeModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const { slug, inviteCode, mutate } = useProject();
+
+ const inviteLink = useMemo(() => {
+ return `${APP_DOMAIN}/invites/${inviteCode}`;
+ }, [inviteCode]);
+
+ const [resetting, setResetting] = useState(false);
+
+ return (
+ <Modal
+ showModal={showInviteCodeModal}
+ setShowModal={setShowInviteCodeModal}
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
+ <Logo />
+ <h3 className="text-lg font-medium">Invite Link</h3>
+ <p className="text-center text-sm text-gray-500">
+ Allow other people to join your project through the link below.
+ </p>
+ </div>
+
+ <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 text-left sm:px-16">
+ <div className="flex items-center justify-between rounded-md border border-gray-300 bg-white px-3 py-2">
+ <p className="scrollbar-hide w-5/6 overflow-scroll font-mono text-sm text-gray-500">
+ {inviteLink}
+ </p>
+ <CopyButton value={inviteLink} className="rounded-md" />
+ </div>
+ <Button
+ text="Reset invite link"
+ variant="secondary"
+ loading={resetting}
+ onClick={() => {
+ setResetting(true);
+ fetch(`/api/projects/${slug}/invites/reset`, {
+ method: "POST",
+ }).then(async () => {
+ await mutate();
+ setResetting(false);
+ });
+ }}
+ />
+ </div>
+ </Modal>
+ );
+}
+
+export function useInviteCodeModal() {
+ const [showInviteCodeModal, setShowInviteCodeModal] = useState(false);
+
+ const InviteCodeModalCallback = useCallback(() => {
+ return (
+ <InviteCodeModal
+ showInviteCodeModal={showInviteCodeModal}
+ setShowInviteCodeModal={setShowInviteCodeModal}
+ />
+ );
+ }, [showInviteCodeModal, setShowInviteCodeModal]);
+
+ return useMemo(
+ () => ({
+ setShowInviteCodeModal,
+ InviteCodeModal: InviteCodeModalCallback,
+ }),
+ [setShowInviteCodeModal, InviteCodeModalCallback],
+ );
+}
diff --git a/packages/ui/src/button.tsx b/packages/ui/src/button.tsx
index aa649a5a4c..803636e168 100644
--- a/packages/ui/src/button.tsx
+++ b/packages/ui/src/button.tsx
@@ -86,7 +86,7 @@ export function Button({
{...props}
>
{loading ? <LoadingSpinner /> : icon ? icon : null}
- <p className={cn(shortcut && "flex-1 text-left")}>{text}</p>
+ {text && <p className={cn(shortcut && "flex-1 text-left")}>{text}</p>}
{shortcut && (
<kbd
className={cn(
diff --git a/packages/utils/src/constants/misc.ts b/packages/utils/src/constants/misc.ts
index 060a51bdc1..f2fc9a2e0f 100644
--- a/packages/utils/src/constants/misc.ts
+++ b/packages/utils/src/constants/misc.ts
@@ -23,3 +23,5 @@ export const GOOGLE_FAVICON_URL =
"https://www.google.com/s2/favicons?sz=64&domain_url=";
export const PAGINATION_LIMIT = 100;
+
+export const TWO_WEEKS_IN_SECONDS = 60 * 60 * 24 * 14;