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.

Added team invites feature

Steven Teyb6ffc0a86505
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index 248cf43b84..9ae2ba7963 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -62,7 +62,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const expired = expiresAt && new Date() > new Date(expiresAt);
return (
- <div className="relative rounded-lg bg-white p-3 pr-1 shadow transition-all hover:shadow-md sm:p-4">
+ <div className="relative rounded-lg border border-gray-100 bg-white p-3 pr-1 shadow transition-all hover:shadow-md sm:p-4">
<LinkQRModal />
<AddEditLinkModal />
<ArchiveLinkModal />
diff --git a/components/app/links/link-filters/user-filter.tsx b/components/app/links/link-filters/user-filter.tsx
index aee57cb59a..c325a7e4b3 100644
--- a/components/app/links/link-filters/user-filter.tsx
+++ b/components/app/links/link-filters/user-filter.tsx
@@ -2,7 +2,7 @@ import { useRouter } from "next/router";
import { useMemo, useState } from "react";
import useSWR from "swr";
import BlurImage from "@/components/shared/blur-image";
-import { ChevronDown, Search, Tick, X } from "@/components/shared/icons";
+import { ChevronDown, Search, X } from "@/components/shared/icons";
import Popover from "@/components/shared/popover";
import { UserProps } from "@/lib/types";
import { fetcher } from "@/lib/utils";
diff --git a/components/app/links/links-container.tsx b/components/app/links/links-container.tsx
index a5aa90a2b0..6f8052299e 100644
--- a/components/app/links/links-container.tsx
+++ b/components/app/links/links-container.tsx
@@ -19,7 +19,7 @@ export default function LinksContainer({
slug: string;
};
- const { project: { domain } = {} } = useProject();
+ const { project: { domain } = {}, loading } = useProject();
const { data: links } = useSWR<LinkProps[]>(
domain
@@ -36,7 +36,7 @@ export default function LinksContainer({
<MaxWidthWrapper className="pb-10">
<LinkFilters />
<ul className="grid grid-cols-1 gap-3">
- {links ? (
+ {links && !loading ? (
links.length > 0 ? (
links.map((props) => <LinkCard key={props.key} props={props} />)
) : (
diff --git a/components/app/modals/accept-invite-modal.tsx b/components/app/modals/accept-invite-modal.tsx
new file mode 100644
index 0000000000..ecb25f89ec
--- /dev/null
+++ b/components/app/modals/accept-invite-modal.tsx
@@ -0,0 +1,94 @@
+import { useRouter } from "next/router";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import { mutate } from "swr";
+import BlurImage from "@/components/shared/blur-image";
+import LoadingDots from "@/components/shared/icons/loading-dots";
+import Modal from "@/components/shared/modal";
+import useProject from "@/lib/swr/use-project";
+import { InlineSnippet } from "../settings/custom-domain/domain-configuration";
+
+function AcceptInviteModal({
+ showAcceptInviteModal,
+ setShowAcceptInviteModal,
+}: {
+ showAcceptInviteModal: boolean;
+ setShowAcceptInviteModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+ const [accepting, setAccepting] = useState(false);
+ const { error } = useProject();
+
+ return (
+ <Modal
+ showModal={showAcceptInviteModal}
+ setShowModal={setShowAcceptInviteModal}
+ >
+ <div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">
+ <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">
+ <BlurImage
+ src={`/_static/logo.png`}
+ alt={"Invite Teammate"}
+ className="h-10 w-10 rounded-full"
+ width={20}
+ height={20}
+ />
+ <h3 className="text-lg font-medium">Project Invitation</h3>
+ <p className="text-center text-sm text-gray-500">
+ You've been invited to join and collaborate on the{" "}
+ <InlineSnippet>{slug}</InlineSnippet> team on Dub
+ </p>
+ </div>
+ <div className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16">
+ <button
+ onClick={() => {
+ setAccepting(true);
+ fetch(`/api/projects/${slug}/invite/accept`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ }).then(async () => {
+ mutate(`/api/projects/${slug}`);
+ setShowAcceptInviteModal(false);
+ });
+ }}
+ disabled={accepting}
+ className={`${
+ accepting
+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
+ : "border-black bg-black text-white hover:bg-white hover:text-black"
+ } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
+ >
+ {accepting ? <LoadingDots color="#808080" /> : <p>Accept invite</p>}
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
+
+export function useAcceptInviteModal() {
+ const [showAcceptInviteModal, setShowAcceptInviteModal] = useState(false);
+
+ const AcceptInviteModalCallback = useCallback(() => {
+ return (
+ <AcceptInviteModal
+ showAcceptInviteModal={showAcceptInviteModal}
+ setShowAcceptInviteModal={setShowAcceptInviteModal}
+ />
+ );
+ }, [showAcceptInviteModal, setShowAcceptInviteModal]);
+
+ return useMemo(
+ () => ({
+ setShowAcceptInviteModal,
+ AcceptInviteModal: AcceptInviteModalCallback,
+ }),
+ [setShowAcceptInviteModal, AcceptInviteModalCallback],
+ );
+}
diff --git a/components/app/modals/invite-teammate-modal.tsx b/components/app/modals/invite-teammate-modal.tsx
new file mode 100644
index 0000000000..c5fff8f65e
--- /dev/null
+++ b/components/app/modals/invite-teammate-modal.tsx
@@ -0,0 +1,128 @@
+import { useRouter } from "next/router";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import { mutate } from "swr";
+import BlurImage from "@/components/shared/blur-image";
+import LoadingDots from "@/components/shared/icons/loading-dots";
+import Modal from "@/components/shared/modal";
+import useProject from "@/lib/swr/use-project";
+
+function InviteTeammateModal({
+ showInviteTeammateModal,
+ setShowInviteTeammateModal,
+}: {
+ showInviteTeammateModal: boolean;
+ setShowInviteTeammateModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+ const [state, setState] = useState("idle");
+ const [error, setError] = useState(null);
+ const [email, setEmail] = useState("");
+ const { project: { logo } = {} } = useProject();
+
+ return (
+ <Modal
+ showModal={showInviteTeammateModal}
+ setShowModal={setShowInviteTeammateModal}
+ >
+ <div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">
+ <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">
+ <BlurImage
+ src={logo || `/_static/logo.png`}
+ alt={"Invite Teammate"}
+ className="h-10 w-10 rounded-full"
+ width={20}
+ height={20}
+ />
+ <h3 className="text-lg font-medium">Invite Teammate</h3>
+ <p className="text-center text-sm text-gray-500">
+ Invite a teammate to join your project.
+ </p>
+ </div>
+
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setState("inviting");
+ fetch(`/api/projects/${slug}/invite`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email }),
+ }).then(async (res) => {
+ if (res.status === 200) {
+ setState("invited");
+ mutate(`/api/projects/${slug}/invite`);
+ } else {
+ setState("idle");
+ const response = await res.json();
+ setError(response.error);
+ }
+ });
+ }}
+ className="flex flex-col bg-gray-50 px-4 py-8 text-left sm:px-16"
+ >
+ <div>
+ <label htmlFor="email" className="block text-sm text-gray-700">
+ Email
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="email"
+ name="email"
+ id="email"
+ placeholder="[email protected]"
+ required
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"
+ />
+ </div>
+ </div>
+
+ <button
+ disabled={state === "inviting"}
+ className={`${
+ state === "inviting"
+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
+ : "border-black bg-black text-white hover:bg-white hover:text-black"
+ } mt-4 mb-2 flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
+ >
+ {state === "inviting" ? (
+ <LoadingDots color="#808080" />
+ ) : (
+ <p>Send invite</p>
+ )}
+ </button>
+ {error && <p className="text-center text-xs text-red-500">{error}</p>}
+ </form>
+ </div>
+ </Modal>
+ );
+}
+
+export function useInviteTeammateModal() {
+ const [showInviteTeammateModal, setShowInviteTeammateModal] = useState(false);
+
+ const InviteTeammateModalCallback = useCallback(() => {
+ return (
+ <InviteTeammateModal
+ showInviteTeammateModal={showInviteTeammateModal}
+ setShowInviteTeammateModal={setShowInviteTeammateModal}
+ />
+ );
+ }, [showInviteTeammateModal, setShowInviteTeammateModal]);
+
+ return useMemo(
+ () => ({
+ setShowInviteTeammateModal,
+ InviteTeammateModal: InviteTeammateModalCallback,
+ }),
+ [setShowInviteTeammateModal, InviteTeammateModalCallback],
+ );
+}
diff --git a/components/app/settings/custom-domain/domain-configuration.tsx b/components/app/settings/custom-domain/domain-configuration.tsx
index 657073110d..b10f7abec9 100644
--- a/components/app/settings/custom-domain/domain-configuration.tsx
+++ b/components/app/settings/custom-domain/domain-configuration.tsx
@@ -2,9 +2,9 @@ import { useState } from "react";
import { DomainVerificationStatusProps } from "@/lib/types";
import { getSubdomain } from "@/lib/utils";
-const InlineSnippet = ({ children }: { children: string }) => {
+export const InlineSnippet = ({ children }: { children: string }) => {
return (
- <span className="inline-block rounded-md bg-blue-100 p-1 font-mono text-blue-900">
+ <span className="inline-block rounded-md bg-blue-100 px-1 py-0.5 font-mono text-blue-900">
{children}
</span>
);
diff --git a/components/app/settings/delete-project.tsx b/components/app/settings/delete-project.tsx
index 015f4b47f8..7a1396ba43 100644
--- a/components/app/settings/delete-project.tsx
+++ b/components/app/settings/delete-project.tsx
@@ -19,7 +19,7 @@ export default function DeleteProject() {
<div className="flex items-center justify-end px-10 py-4">
<button
onClick={() => setShowDeleteProjectModal(true)}
- className="h-9 w-32 rounded-md border border-red-500 bg-red-500 text-sm text-white transition-all duration-150 ease-in-out hover:bg-white hover:text-red-500 focus:outline-none"
+ className="h-9 w-32 rounded-md border border-red-600 bg-red-600 text-sm text-white transition-all duration-150 ease-in-out hover:bg-white hover:text-red-600 focus:outline-none"
>
Delete Project
</button>
diff --git a/components/app/settings/landing-page.tsx b/components/app/settings/landing-page.tsx
index 043940fee4..4caf9cbdc9 100644
--- a/components/app/settings/landing-page.tsx
+++ b/components/app/settings/landing-page.tsx
@@ -8,7 +8,7 @@ import useProject from "@/lib/swr/use-project";
import useUsage from "@/lib/swr/use-usage";
import { fetcher, nFormatter } from "@/lib/utils";
-export default function DefaultPage() {
+export default function LandingPage() {
const router = useRouter();
const { slug } = router.query as { slug: string };
diff --git a/components/app/settings/layout.tsx b/components/app/settings/layout.tsx
new file mode 100644
index 0000000000..b6f4cd411a
--- /dev/null
+++ b/components/app/settings/layout.tsx
@@ -0,0 +1,71 @@
+import ErrorPage from "next/error";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import AppLayout from "components/layout/app";
+import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
+import useProject from "@/lib/swr/use-project";
+import { useAcceptInviteModal } from "@/components/app/modals/accept-invite-modal";
+import { ReactNode, useEffect } from "react";
+
+export default function SettingsLayout({ children }: { children: ReactNode }) {
+ const router = useRouter();
+ const { slug } = router.query as {
+ slug?: string;
+ };
+ const { error } = useProject();
+ const { AcceptInviteModal, setShowAcceptInviteModal } =
+ useAcceptInviteModal();
+
+ // handle errors
+ useEffect(() => {
+ if (error && (error.status === 409 || error.status === 410)) {
+ setShowAcceptInviteModal(true);
+ }
+ }, [error]);
+
+ if (error && error.status === 404) {
+ return <ErrorPage statusCode={404} />;
+ }
+
+ const tabs = [
+ {
+ name: "General",
+ href: `/${slug}/settings`,
+ },
+ {
+ name: "People",
+ href: `/${slug}/settings/people`,
+ },
+ ];
+
+ return (
+ <AppLayout bgWhite>
+ {error && (error.status === 409 || error.status === 410) && (
+ <AcceptInviteModal />
+ )}
+ <div className="flex h-36 items-center border-b border-gray-200 bg-white">
+ <MaxWidthWrapper>
+ <div className="flex items-center justify-between">
+ <h1 className="text-2xl text-gray-600">Settings</h1>
+ </div>
+ </MaxWidthWrapper>
+ </div>
+ <MaxWidthWrapper className="grid grid-cols-5 items-start gap-5 py-10">
+ <div className="col-span-1 grid gap-1">
+ {tabs.map(({ name, href }) => (
+ <Link href={href}>
+ <a
+ className={`${
+ router.asPath === href ? "font-semibold text-black" : ""
+ } rounded-md p-2.5 text-sm transition-all duration-75 hover:bg-gray-100 active:bg-gray-200`}
+ >
+ {name}
+ </a>
+ </Link>
+ ))}
+ </div>
+ <div className="col-span-4 grid gap-5">{children}</div>
+ </MaxWidthWrapper>
+ </AppLayout>
+ );
+}
diff --git a/components/layout/app/index.tsx b/components/layout/app/index.tsx
index 16cd694e29..4875d7dc97 100644
--- a/components/layout/app/index.tsx
+++ b/components/layout/app/index.tsx
@@ -16,7 +16,13 @@ const NavTabs = dynamic(() => import("./nav-tabs"), {
loading: () => <div className="-mb-0.5 h-12 w-full" />,
}); // dynamic import to avoid react hydration mismatch error
-export default function AppLayout({ children }: { children: ReactNode }) {
+export default function AppLayout({
+ children,
+ bgWhite,
+}: {
+ children: ReactNode;
+ bgWhite?: boolean;
+}) {
const router = useRouter();
const { slug, key } = router.query as {
slug?: string;
@@ -34,7 +40,9 @@ export default function AppLayout({ children }: { children: ReactNode }) {
strategy="lazyOnload"
/>
<Toaster />
- <div className="min-h-screen w-full bg-gray-50">
+ <div
+ className={`min-h-screen w-full ${bgWhite ? "bg-white" : "bg-gray-50"}`}
+ >
<div className="sticky top-0 left-0 right-0 z-20 border-b border-gray-200 bg-white">
<div className="mx-auto max-w-screen-xl px-2.5 md:px-20">
<div className="flex h-16 items-center justify-between">
diff --git a/components/layout/app/nav-tabs.tsx b/components/layout/app/nav-tabs.tsx
index dabbf5031d..b7fcc186e6 100644
--- a/components/layout/app/nav-tabs.tsx
+++ b/components/layout/app/nav-tabs.tsx
@@ -38,7 +38,9 @@ export default function NavTabs() {
<Link key={href} href={href}>
<a
className={`border-b-2 p-1 ${
- router.asPath.split("?")[0] === href
+ // hacky approach to getting the current tab – will replace with useSelectedLayoutSegments when upgrading to Next.js 13
+ router.asPath.split("?")[0].split("/").slice(0, 3).join("/") ===
+ href
? "border-black text-black"
: "border-transparent text-gray-600 hover:text-black"
}`}
diff --git a/emails/TeamInvite.tsx b/emails/TeamInvite.tsx
new file mode 100644
index 0000000000..90d0855f7f
--- /dev/null
+++ b/emails/TeamInvite.tsx
@@ -0,0 +1,58 @@
+import {
+ Mjml,
+ MjmlBody,
+ MjmlColumn,
+ MjmlSection,
+ MjmlText,
+ MjmlWrapper,
+} from "mjml-react";
+import ButtonPrimary from "./components/ButtonPrimary";
+import Divider from "./components/Divider";
+import Footer from "./components/Footer";
+import Head from "./components/Head";
+import Header from "./components/Header";
+import { purple } from "./components/theme";
+
+export default function TeamInvite({ url }: { url: string }): JSX.Element {
+ return (
+ <Mjml>
+ <Head />
+ <MjmlBody width={500}>
+ <MjmlWrapper cssClass="container">
+ <Header title="Your Dub Invite" />
+ <MjmlSection cssClass="smooth">
+ <MjmlColumn>
+ <MjmlText cssClass="paragraph">
+ You've been invited to join a team on Dub
+ </MjmlText>
+ <MjmlText cssClass="paragraph">
+ Please click the magic link below to sign in to your account.
+ </MjmlText>
+ <ButtonPrimary link={url} uiText="Sign In" />
+ <MjmlText cssClass="paragraph">
+ If you're on a mobile device, you can also copy the link below
+ and paste it into the browser of your choice.
+ </MjmlText>
+ <MjmlText cssClass="paragraph">
+ <a
+ rel="nofollow"
+ style={{
+ textDecoration: "none",
+ color: `${purple} !important`,
+ }}
+ >
+ {url.replace(/^https?:\/\//, "")}
+ </a>
+ </MjmlText>
+ <MjmlText cssClass="paragraph">
+ If you did not request this email, you can safely ignore it.
+ </MjmlText>
+ <Divider />
+ </MjmlColumn>
+ </MjmlSection>
+ <Footer footnote={false} />
+ </MjmlWrapper>
+ </MjmlBody>
+ </Mjml>
+ );
+}
diff --git a/emails/previews/Account.tsx b/emails/previews/Account.tsx
index 6030f61c4b..724045291c 100644
--- a/emails/previews/Account.tsx
+++ b/emails/previews/Account.tsx
@@ -1,4 +1,5 @@
import { default as LoginLinkEmail } from "../LoginLink";
+import { default as TeamInviteEmail } from "../TeamInvite";
import { default as WelcomeEmailChild } from "../WelcomeEmail";
export function LoginLink() {
@@ -7,6 +8,12 @@ export function LoginLink() {
);
}
+export function TeamInvite() {
+ return (
+ <TeamInviteEmail url="http://app.localhost:3000/api/auth/callback/email?callbackUrl=http%3A%2F%2Fapp.localhost%3A3000%2Flogin&token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&[email protected]" />
+ );
+}
+
export function WelcomeEmail() {
return <WelcomeEmailChild name="Steven Tey" />;
}
diff --git a/lib/auth.ts b/lib/auth.ts
index 03fd34c722..be6759576f 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -3,9 +3,9 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { unstable_getServerSession } from "next-auth/next";
import { FREE_PLAN_PROJECT_LIMIT } from "@/lib/constants";
import prisma from "@/lib/prisma";
-import { ProjectProps, UsageProps, UserProps } from "@/lib/types";
+import { ProjectProps, UserProps } from "@/lib/types";
-interface Session {
+export interface Session {
user: {
email?: string | null;
id?: string | null;
@@ -57,14 +57,9 @@ const withProjectAuth =
.json({ error: "Missing or misconfigured project slug" });
}
- const project = (await prisma.project.findFirst({
+ const project = (await prisma.project.findUnique({
where: {
slug,
- users: {
- some: {
- userId: session.user.id,
- },
- },
},
select: {
id: true,
@@ -86,7 +81,32 @@ const withProjectAuth =
},
})) as ProjectProps;
- if (!project) return res.status(404).json({ error: "Project not found" });
+ if (project) {
+ // 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 res.status(404).json({ error: "Project not found" });
+ } else if (pendingInvites.expires < new Date()) {
+ return res.status(410).json({ error: "Project invite expired" });
+ } else {
+ return res.status(409).json({ error: "Project invite pending" });
+ }
+ }
+ } else {
+ // project doesn't exist
+ return res.status(404).json({ error: "Project not found" });
+ }
// if the action doesn't need to be gated for GET requests, return handler now
if (req.method === "GET" && excludeGet) return handler(req, res, project);
@@ -116,7 +136,7 @@ interface WithUsertNextApiHandler {
(
req: NextApiRequest,
res: NextApiResponse,
- userId: string,
+ session: Session,
user?: UserProps,
): Promise<void>;
}
@@ -136,7 +156,7 @@ const withUserAuth =
const session = await getSession(req, res);
if (!session?.user.id) return res.status(401).end("Unauthorized");
- if (req.method === "GET") return handler(req, res, session.user.id);
+ if (req.method === "GET") return handler(req, res, session);
if (needUserDetails || needProSubscription) {
const user = (await prisma.user.findUnique({
@@ -173,10 +193,10 @@ const withUserAuth =
.end("Unauthorized: Can't add more projects, need pro subscription");
}
- return handler(req, res, session.user.id, user);
+ return handler(req, res, session, user);
}
- return handler(req, res, session.user.id);
+ return handler(req, res, session);
};
export { withUserAuth };
diff --git a/lib/swr/use-project.ts b/lib/swr/use-project.ts
index b3039bf711..640e3f2f5c 100644
--- a/lib/swr/use-project.ts
+++ b/lib/swr/use-project.ts
@@ -11,13 +11,13 @@ export default function useProject() {
slug: string;
};
- const { data: project, error } = useSWR<ProjectProps>(
- slug && `/api/projects/${slug}`,
- fetcher,
- {
- dedupingInterval: 30000,
- },
- );
+ const {
+ data: project,
+ isValidating,
+ error,
+ } = useSWR<ProjectProps>(slug && `/api/projects/${slug}`, fetcher, {
+ dedupingInterval: 30000,
+ });
const isOwner = useMemo(() => {
if (project && Array.isArray(project.users)) {
@@ -28,7 +28,7 @@ export default function useProject() {
return {
project,
isOwner,
- loading: !error && !project,
+ loading: isValidating,
error,
};
}
diff --git a/lib/types.ts b/lib/types.ts
index 120b3fe6a8..890693f142 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -51,6 +51,7 @@ export interface UserProps {
email: string;
stripeId: string;
usageLimit: number;
+ joinedAt?: Date;
projects?: { projectId: string }[];
}
diff --git a/pages/api/links/[key]/archive.ts b/pages/api/links/[key]/archive.ts
index 191a349c28..34e6391eeb 100644
--- a/pages/api/links/[key]/archive.ts
+++ b/pages/api/links/[key]/archive.ts
@@ -1,12 +1,12 @@
import { NextApiRequest, NextApiResponse } from "next";
import { archiveLink } from "@/lib/api/links";
-import { withUserAuth } from "@/lib/auth";
+import { Session, withUserAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
const domain = "dub.sh";
export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, userId: string) => {
+ async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
const { key } = req.query as { key: string };
const isOwner = await prisma.link
@@ -18,7 +18,7 @@ export default withUserAuth(
},
},
})
- .then((link) => link?.userId === userId);
+ .then((link) => link?.userId === session.user.id);
if (!isOwner) {
return res.status(403).json({ error: "Not authorized" });
diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.ts
index 04416fa215..c942dbca53 100644
--- a/pages/api/links/[key]/index.ts
+++ b/pages/api/links/[key]/index.ts
@@ -1,12 +1,12 @@
import { NextApiRequest, NextApiResponse } from "next";
import { deleteLink, editLink } from "@/lib/api/links";
-import { withUserAuth } from "@/lib/auth";
+import { Session, withUserAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
const domain = "dub.sh";
export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, userId: string) => {
+ async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
const { key: oldKey } = req.query as { key: string };
const isOwner = await prisma.link
@@ -18,7 +18,7 @@ export default withUserAuth(
},
},
})
- .then((link) => link?.userId === userId);
+ .then((link) => link?.userId === session.user.id);
if (!isOwner) {
return res.status(403).json({ error: "Not authorized" });
@@ -35,7 +35,7 @@ export default withUserAuth(
{
domain,
...req.body,
- userId,
+ userId: session.user.id,
},
oldKey,
"dub",
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index ee35f6030a..6ba921e1e5 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -1,11 +1,11 @@
import { NextApiRequest, NextApiResponse } from "next";
import { addLink, getLinksForProject } from "@/lib/api/links";
-import { withUserAuth } from "@/lib/auth";
+import { Session, withUserAuth } from "@/lib/auth";
// This is a special route for retrieving and creating custom dub.sh links.
export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, userId: string) => {
+ async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
// GET /api/links – get all dub.sh links created by the user
if (req.method === "GET") {
const { status, sort } = req.query as {
@@ -16,7 +16,7 @@ export default withUserAuth(
domain: "dub.sh",
status,
sort,
- userId,
+ userId: session.user.id,
});
return res.status(200).json(response);
@@ -29,7 +29,7 @@ export default withUserAuth(
const response = await addLink({
...req.body,
domain: "dub.sh",
- userId,
+ userId: session.user.id,
});
if (response === null) {
diff --git a/pages/api/projects/[slug]/invite/accept.ts b/pages/api/projects/[slug]/invite/accept.ts
new file mode 100644
index 0000000000..d2759344c6
--- /dev/null
+++ b/pages/api/projects/[slug]/invite/accept.ts
@@ -0,0 +1,51 @@
+import { Session, withUserAuth } from "@/lib/auth";
+import { NextApiRequest, NextApiResponse } from "next";
+
+export default withUserAuth(
+ async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
+ const { slug } = req.query as { slug: string };
+ if (!slug || typeof slug !== "string") {
+ return res
+ .status(400)
+ .json({ error: "Missing or misconfigured project slug" });
+ }
+ if (req.method === "POST") {
+ const invite = await prisma.projectInvite.findFirst({
+ where: {
+ email: session.user.email,
+ project: {
+ slug,
+ },
+ },
+ select: {
+ expires: true,
+ projectId: true,
+ },
+ });
+ if (!invite) {
+ return res.status(404).json({ error: "Invalid invitation" });
+ } else if (invite.expires < new Date()) {
+ return res.status(410).json({ error: "Invitation expired" });
+ } 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,
+ },
+ },
+ }),
+ ]);
+ return res.status(200).json(response);
+ }
+ }
+ },
+);
diff --git a/pages/api/projects/[slug]/invite/index.tsx b/pages/api/projects/[slug]/invite/index.tsx
new file mode 100644
index 0000000000..51fab976aa
--- /dev/null
+++ b/pages/api/projects/[slug]/invite/index.tsx
@@ -0,0 +1,108 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { withProjectAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import sendMail from "emails";
+import TeamInvite from "emails/TeamInvite";
+import { randomBytes, createHash } from "crypto";
+import { ProjectProps } from "@/lib/types";
+
+const hashToken = (token: string) => {
+ return createHash("sha256")
+ .update(`${token}${process.env.NEXTAUTH_SECRET}`)
+ .digest("hex");
+};
+
+export default withProjectAuth(
+ async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
+ const { slug } = req.query;
+ if (!slug || typeof slug !== "string") {
+ return res
+ .status(400)
+ .json({ error: "Missing or misconfigured project slug" });
+ }
+
+ // GET /api/projects/[slug]/invite - Get all pending invites for a project
+ if (req.method === "GET") {
+ const invites = await prisma.projectInvite.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ email: true,
+ createdAt: true,
+ },
+ });
+ return res.status(200).json(
+ invites.map((invite) => ({
+ email: invite.email,
+ joinedAt: invite.createdAt,
+ })),
+ );
+
+ // POST /api/projects/[slug]/invite – invite a teammate
+ } else if (req.method === "POST") {
+ const { email } = req.body;
+
+ const alreadyInTeam = await prisma.projectUsers.findFirst({
+ where: {
+ projectId: project.id,
+ user: {
+ email,
+ },
+ },
+ });
+ if (alreadyInTeam) {
+ return res
+ .status(400)
+ .json({ error: "User already exists in this project" });
+ }
+
+ // same method of generating a token as next-auth
+ const token = randomBytes(32).toString("hex");
+ const ONE_WEEK_IN_SECONDS = 604800;
+ const expires = new Date(Date.now() + ONE_WEEK_IN_SECONDS * 1000);
+
+ // create a project invite record and a verification request token that lasts for a week
+ try {
+ await prisma.projectInvite.create({
+ data: {
+ email,
+ expires,
+ projectId: project.id,
+ },
+ });
+
+ await prisma.verificationToken.create({
+ data: {
+ identifier: email,
+ token: hashToken(token),
+ expires,
+ },
+ });
+
+ const params = new URLSearchParams({
+ callbackUrl: `${process.env.NEXTAUTH_URL}/${slug}`,
+ email,
+ token,
+ });
+
+ const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
+
+ sendMail({
+ subject: "You've been invited to join a project on Dub",
+ to: email,
+ component: <TeamInvite url={url} />,
+ });
+
+ return res.status(200).json({ message: "Invite sent" });
+ } catch (error) {
+ return res.status(400).json({ error: "User already invited" });
+ }
+ } else {
+ res.setHeader("Allow", ["GET", "POST"]);
+ return res
+ .status(405)
+ .json({ error: `Method ${req.method} Not Allowed` });
+ }
+ },
+);
diff --git a/pages/api/projects/[slug]/users.ts b/pages/api/projects/[slug]/users.ts
index 3a4ec82546..deffd0c3c4 100644
--- a/pages/api/projects/[slug]/users.ts
+++ b/pages/api/projects/[slug]/users.ts
@@ -1,9 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
-import { removeDomain } from "@/lib/domains";
import prisma from "@/lib/prisma";
import { ProjectProps } from "@/lib/types";
-import { deleteProject } from "@/lib/upstash";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
@@ -17,21 +15,27 @@ export default withProjectAuth(
// GET /api/projects/[slug]/users – get users for a specific project
if (req.method === "GET") {
const { id: projectId } = project;
- const users = await prisma.user.findMany({
+ const users = await prisma.projectUsers.findMany({
where: {
- projects: {
- some: {
- projectId,
- },
- },
+ projectId,
},
select: {
- id: true,
- name: true,
- email: true,
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ createdAt: true,
},
});
- return res.status(200).json(users);
+ return res.status(200).json(
+ users.map((u) => ({
+ ...u.user,
+ joinedAt: u.createdAt,
+ })),
+ );
} else {
res.setHeader("Allow", ["GET"]);
return res
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index ccd3f49826..08f94ce28d 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -1,19 +1,19 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { getSession, withUserAuth } from "@/lib/auth";
+import { getSession, Session, withUserAuth } from "@/lib/auth";
import { DEFAULT_REDIRECTS, RESERVED_KEYS } from "@/lib/constants";
import { addDomain, removeDomain } from "@/lib/domains";
import prisma from "@/lib/prisma";
import { validDomainRegex } from "@/lib/utils";
export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, userId: string) => {
+ async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
// GET /api/projects – get all projects associated with the authenticated user
if (req.method === "GET") {
const response = await prisma.project.findMany({
where: {
users: {
some: {
- userId,
+ userId: session.user.id,
},
},
},
@@ -75,7 +75,7 @@ export default withUserAuth(
domain,
users: {
create: {
- userId,
+ userId: session.user.id,
role: "owner",
},
},
diff --git a/pages/api/stripe/upgrade.ts b/pages/api/stripe/upgrade.ts
index c9a5028b76..7a1af339b9 100644
--- a/pages/api/stripe/upgrade.ts
+++ b/pages/api/stripe/upgrade.ts
@@ -1,5 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { withUserAuth } from "@/lib/auth";
+import { Session, withUserAuth } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
import { UserProps } from "@/lib/types";
@@ -7,13 +7,13 @@ export default withUserAuth(
async (
req: NextApiRequest,
res: NextApiResponse,
- userId: string,
+ session: Session,
user: UserProps,
) => {
// POST /api/stripe/upgrade – upgrade a user's account from free to pro
if (req.method === "POST") {
const { priceId } = req.query as { priceId: string };
- const session = await stripe.checkout.sessions.create({
+ const stripeSession = await stripe.checkout.sessions.create({
customer_email: user.email,
payment_method_types: ["card"],
billing_address_collection: "required",
@@ -29,9 +29,9 @@ export default withUserAuth(
}/settings`,
line_items: [{ price: priceId, quantity: 1 }],
mode: "subscription",
- client_reference_id: userId,
+ client_reference_id: session.user.id,
});
- return res.status(200).json(session);
+ return res.status(200).json(stripeSession);
} else {
res.setHeader("Allow", ["POST"]);
return res
diff --git a/pages/api/usage/index.ts b/pages/api/usage/index.ts
index 75ed5c4c34..b424b7bff8 100644
--- a/pages/api/usage/index.ts
+++ b/pages/api/usage/index.ts
@@ -1,14 +1,14 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { withUserAuth } from "@/lib/auth";
+import { Session, withUserAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, userId: string) => {
+ async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
// GET /api/usage – get a user's usage over all the projects they're an owner of
if (req.method === "GET") {
const response = await prisma.user.findUnique({
where: {
- id: userId,
+ id: session.user.id,
},
select: {
usage: true,
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index ef13b16f58..ce562c692c 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -4,13 +4,23 @@ import { useAddEditLinkModal } from "@/components/app/modals/add-edit-link-modal
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import AppLayout from "components/layout/app";
import useProject from "@/lib/swr/use-project";
+import { useAcceptInviteModal } from "@/components/app/modals/accept-invite-modal";
+import { useEffect } from "react";
export default function ProjectLinks() {
const { project, error } = useProject();
const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal({});
+ const { AcceptInviteModal, setShowAcceptInviteModal } =
+ useAcceptInviteModal();
+
+ // handle errors
+ useEffect(() => {
+ if (error && (error.status === 409 || error.status === 410)) {
+ setShowAcceptInviteModal(true);
+ }
+ }, [error]);
- // handle error page
if (error && error.status === 404) {
return <ErrorPage statusCode={404} />;
}
@@ -18,6 +28,9 @@ export default function ProjectLinks() {
return (
<AppLayout>
{project && <AddEditLinkModal />}
+ {error && (error.status === 409 || error.status === 410) && (
+ <AcceptInviteModal />
+ )}
<div className="flex h-36 items-center border-b border-gray-200 bg-white">
<MaxWidthWrapper>
<div className="flex items-center justify-between">
@@ -26,7 +39,7 @@ export default function ProjectLinks() {
</div>
</MaxWidthWrapper>
</div>
- {project && <LinksContainer AddEditLinkButton={AddEditLinkButton} />}
+ <LinksContainer AddEditLinkButton={AddEditLinkButton} />
</AppLayout>
);
}
diff --git a/pages/app/[slug]/settings.tsx b/pages/app/[slug]/settings.tsx
deleted file mode 100644
index a125ae885f..0000000000
--- a/pages/app/[slug]/settings.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import ErrorPage from "next/error";
-import CustomDomain from "@/components/app/settings/custom-domain";
-import DeleteProject from "@/components/app/settings/delete-project";
-import DefaultPage from "@/components/app/settings/landing-page";
-import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import AppLayout from "components/layout/app";
-import useProject from "@/lib/swr/use-project";
-
-export default function ProjectLinks() {
- const { error } = useProject();
-
- // handle error page
- if (error && error.status === 404) {
- return <ErrorPage statusCode={404} />;
- }
-
- return (
- <AppLayout>
- <div className="flex h-36 items-center border-b border-gray-200 bg-white">
- <MaxWidthWrapper>
- <div className="flex items-center justify-between">
- <h1 className="text-2xl text-gray-600">Settings</h1>
- </div>
- </MaxWidthWrapper>
- </div>
- <MaxWidthWrapper>
- <div className="grid gap-5 py-10">
- <CustomDomain />
- <DefaultPage />
- <DeleteProject />
- </div>
- </MaxWidthWrapper>
- </AppLayout>
- );
-}
diff --git a/pages/app/[slug]/settings/index.tsx b/pages/app/[slug]/settings/index.tsx
new file mode 100644
index 0000000000..e08fad7d17
--- /dev/null
+++ b/pages/app/[slug]/settings/index.tsx
@@ -0,0 +1,14 @@
+import CustomDomain from "@/components/app/settings/custom-domain";
+import DeleteProject from "@/components/app/settings/delete-project";
+import LandingPage from "@/components/app/settings/landing-page";
+import SettingsLayout from "@/components/app/settings/layout";
+
+export default function ProjectSettingsGeneral() {
+ return (
+ <SettingsLayout>
+ <CustomDomain />
+ <LandingPage />
+ <DeleteProject />
+ </SettingsLayout>
+ );
+}
diff --git a/pages/app/[slug]/settings/people.tsx b/pages/app/[slug]/settings/people.tsx
new file mode 100644
index 0000000000..5bf37b518b
--- /dev/null
+++ b/pages/app/[slug]/settings/people.tsx
@@ -0,0 +1,109 @@
+import SettingsLayout from "@/components/app/settings/layout";
+import { useInviteTeammateModal } from "components/app/modals/invite-teammate-modal";
+import { useState } from "react";
+import { useRouter } from "next/router";
+import useSWR from "swr";
+import BlurImage from "@/components/shared/blur-image";
+import { UserProps } from "@/lib/types";
+import { fetcher, timeAgo } from "@/lib/utils";
+
+const tabs = ["Members", "Invitations"];
+
+export default function ProjectSettingsPeople() {
+ const { setShowInviteTeammateModal, InviteTeammateModal } =
+ useInviteTeammateModal();
+
+ const router = useRouter();
+ const { slug } = router.query as { slug?: string };
+ const [currentTab, setCurrentTab] = useState("Members");
+
+ const { data: users } = useSWR<UserProps[]>(
+ slug &&
+ (currentTab === "Members"
+ ? `/api/projects/${slug}/users`
+ : `/api/projects/${slug}/invite`),
+ fetcher,
+ );
+
+ return (
+ <SettingsLayout>
+ <InviteTeammateModal />
+ <div className="rounded-lg border border-gray-200 bg-white">
+ <div className="flex items-center justify-between p-10">
+ <div className="flex flex-col space-y-3">
+ <h2 className="text-xl font-medium">People</h2>
+ <p className="text-sm text-gray-500">
+ Teammates or friends that have access to this project.
+ </p>
+ </div>
+ <button
+ onClick={() => setShowInviteTeammateModal(true)}
+ className="h-9 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"
+ >
+ Invite
+ </button>
+ </div>
+ <div className="flex space-x-3 border-b border-gray-200 px-7">
+ {tabs.map((tab) => (
+ <div
+ className={`${
+ tab === currentTab ? "border-black" : "border-transparent"
+ } border-b py-1`}
+ >
+ <button
+ onClick={() => setCurrentTab(tab)}
+ className="rounded-md px-3 py-1.5 text-sm transition-all duration-75 hover:bg-gray-100 active:bg-gray-200"
+ >
+ {tab}
+ </button>
+ </div>
+ ))}
+ </div>
+ <div className="grid divide-y divide-gray-200">
+ {users
+ ? users.map(({ name, email, joinedAt }) => (
+ <div className="flex items-center justify-between space-x-3 px-8 py-3">
+ <div className="flex items-center space-x-3">
+ <BlurImage
+ src={`https://avatars.dicebear.com/api/micah/${email}.svg`}
+ alt={email}
+ width={40}
+ height={40}
+ className="rounded-full border border-gray-200"
+ />
+ <div className="flex flex-col">
+ <h3 className="text-sm font-medium">
+ {currentTab === "Members"
+ ? name || "Anonymous"
+ : "Invitation Sent"}
+ </h3>
+ <p className="text-xs text-gray-500">{email}</p>
+ </div>
+ </div>
+ <p className="text-xs text-gray-500">
+ {currentTab === "Members" ? "Joined " : "Invited "}
+ {timeAgo(joinedAt)}
+ </p>
+ </div>
+ ))
+ : Array.from({ length: 3 }).map((_, i) => (
+ <UserPlaceholder key={i} />
+ ))}
+ </div>
+ </div>
+ </SettingsLayout>
+ );
+}
+
+const UserPlaceholder = () => (
+ <div className="flex items-center justify-between space-x-3 px-8 py-3">
+ <div className="flex items-center space-x-3">
+ <div className="h-10 w-10 animate-pulse rounded-full bg-gray-200" />
+ <div className="flex flex-col">
+ <div className="h-4 w-24 animate-pulse rounded bg-gray-200" />
+ <div className="mt-1 h-3 w-32 animate-pulse rounded bg-gray-200" />
+ </div>
+ </div>
+ <div className="h-3 w-24 animate-pulse rounded bg-gray-200" />
+ </div>
+);
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index b7c098c68f..dea839ec7a 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -76,6 +76,7 @@ model Project {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
users ProjectUsers[]
+ invites ProjectInvite[]
domainLastChecked DateTime @default(now())
usage Int @default(0)
ownerUsageLimit Int @default(1000)
@@ -84,6 +85,16 @@ model Project {
links Link[]
}
+model ProjectInvite {
+ email String
+ expires DateTime
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ projectId String
+ createdAt DateTime @default(now())
+
+ @@unique([email, projectId])
+}
+
model ProjectUsers {
id String @id @default(cuid())
role String @default("member")