The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Implemented initial RBAC features
Steven Tey1c06a454bc14
diff --git a/components/app/link-card.tsx b/components/app/link-card.tsxindex 4e0a1619ef..4eb1d7d393 100644--- a/components/app/link-card.tsx+++ b/components/app/link-card.tsx@@ -20,7 +20,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {const router = useRouter();const { slug } = router.query as { slug: string };- const { project } = useProject();+ const { project, isOwner } = useProject();const { domain } = project || {};const { exceededUsage } = useUsage();@@ -86,13 +86,17 @@ export default function LinkCard({ props }: { props: LinkProps }) {<p className="text-sm hidden sm:block text-gray-500">Added {timeAgo(timestamp)}</p>- {exceededUsage ? (+ {slug && exceededUsage ? (<Tooltipcontent={<TooltipContent- title="You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them."- cta="Upgrade"- ctaLink={`/settings`}+ title={+ isOwner+ ? "You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them."+ : "The owner of this project has exceeded their usage limit. We're still collecting data on all existing links, but they need to upgrade their plan to edit them."+ }+ cta={isOwner && "Upgrade"}+ ctaLink={isOwner && "/settings"}/>}>diff --git a/components/app/modals/add-edit-link-modal.tsx b/components/app/modals/add-edit-link-modal.tsxindex 6b0bcf15a3..e54d8ec97a 100644--- a/components/app/modals/add-edit-link-modal.tsx+++ b/components/app/modals/add-edit-link-modal.tsx@@ -39,6 +39,8 @@ function AddEditLinkModal({const { project: { domain } = {} } = useProject();const { plan } = useUsage();+ console.log("plan", plan);+const [keyExistsError, setKeyExistsError] = useState(false);const [generatingSlug, setGeneratingSlug] = useState(false);const [generatingTitle, setGeneratingTitle] = useState(false);@@ -492,7 +494,7 @@ function AddEditLinkButton({const router = useRouter();const { slug } = router.query as { slug?: string };- const { project } = useProject();+ const { project, isOwner } = useProject();const { exceededUsage } = useUsage();return project && !project.domainVerified ? (@@ -510,13 +512,17 @@ start adding links."Add</div></Tooltip>- ) : exceededUsage ? (+ ) : slug && exceededUsage ? ( // only show exceeded usage tooltip if user is on a project page<Tooltipcontent={<TooltipContent- title="You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links."- cta="Upgrade"- ctaLink={`/settings`}+ title={+ isOwner+ ? "You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links."+ : "The owner of this project has exceeded their usage limit. We're still collecting data on all existing links, but they need to upgrade their plan to add more links."+ }+ cta={isOwner && "Upgrade"}+ ctaLink={isOwner && "/settings"}/>}>diff --git a/components/app/settings/landing-page.tsx b/components/app/settings/landing-page.tsxindex 4ccf18207c..a75cf0278e 100644--- a/components/app/settings/landing-page.tsx+++ b/components/app/settings/landing-page.tsx@@ -4,14 +4,17 @@ import { useState } from "react";import { Chart, LoadingDots } from "@/components/shared/icons";import { fetcher, nFormatter } from "@/lib/utils";import useSWR from "swr";-import Tooltip from "@/components/shared/tooltip";+import Tooltip, { TooltipContent } from "@/components/shared/tooltip";import toast from "react-hot-toast";+import useUsage from "@/lib/swr/use-usage";export default function DefaultPage() {const router = useRouter();const { slug } = router.query as { slug: string };- const { project: { domain, domainVerified } = {} } = useProject();+ const { project: { domain, domainVerified } = {}, isOwner } = useProject();++ const { plan } = useUsage();const { data: rootDomain } = useSWR<string>(slug && domain && `/api/projects/${slug}/domains/${domain}/root`,@@ -77,7 +80,7 @@ export default function DefaultPage() {)}</div><div />- {domainVerified ? (+ {domainVerified && plan !== "Free" ? (<inputtype="url"name="root"@@ -88,7 +91,23 @@ export default function DefaultPage() {className="border border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 w-full max-w-md rounded-md focus:outline-none text-sm"/>) : (- <Tooltip content="You need to verify your domain first.">+ <Tooltip+ content={+ !domainVerified ? (+ "You need to verify your domain first."+ ) : (+ <TooltipContent+ title={`You can't configure a custom landing page on a free plan. ${+ isOwner+ ? "Upgrade to a Pro plan to proceed."+ : "Ask your project owner to upgrade to a Pro plan."+ }`}+ cta={isOwner && "Upgrade to Pro"}+ ctaLink={isOwner && "/settings"}+ />+ )+ }+ ><div className="text-left border border-gray-300 text-gray-300 text-sm px-3 py-2 w-full max-w-md cursor-not-allowed rounded-md">https://yourdomain.com</div>@@ -99,7 +118,7 @@ export default function DefaultPage() {<div className="border-b border-gray-200" /><div className="px-10 py-4 flex justify-end items-center">- {domainVerified ? (+ {domainVerified && plan !== "Free" ? (<buttondisabled={saving}className={`${@@ -111,7 +130,23 @@ export default function DefaultPage() {{saving ? <LoadingDots /> : "Save Changes"}</button>) : (- <Tooltip content="You need to verify your domain first.">+ <Tooltip+ content={+ !domainVerified ? (+ "You need to verify your domain first."+ ) : (+ <TooltipContent+ title={`You can't configure a custom landing page on a free plan. ${+ isOwner+ ? "Upgrade to a Pro plan to proceed."+ : "Ask your project owner to upgrade to a Pro plan."+ }`}+ cta={isOwner && "Upgrade to Pro"}+ ctaLink={isOwner && "/settings"}+ />+ )+ }+ ><div className="cursor-not-allowed bg-gray-100 border-gray-200 text-gray-300 h-9 w-32 flex items-center justify-center text-sm border rounded-md">Save Changes</div>diff --git a/components/app/settings/plan-usage.tsx b/components/app/settings/plan-usage.tsxindex 9aa3d74417..b1577d5ebe 100644--- a/components/app/settings/plan-usage.tsx+++ b/components/app/settings/plan-usage.tsx@@ -18,7 +18,7 @@ export default function PlanUsage() {const {data: { usage, usageLimit, billingCycleStart, projectCount } = {},loading,- } = useUsage({ settingsPage: true });+ } = useUsage();const [clicked, setClicked] = useState(false);diff --git a/components/shared/tooltip.tsx b/components/shared/tooltip.tsxindex 5c4c6d3149..e53308a2dd 100644--- a/components/shared/tooltip.tsx+++ b/components/shared/tooltip.tsx@@ -96,7 +96,7 @@ export default function Tooltip({><TooltipPrimitive.Arrow className="fill-current text-white" />{typeof content === "string" ? (- <div className="px-4 py-2.5">+ <div className="p-5"><span className="block text-sm text-center text-gray-700 max-w-xs">{content}</span>@@ -125,17 +125,19 @@ export function TooltipContent({ctaLink,}: {title: string;- cta: string;- ctaLink: string;+ cta?: string;+ ctaLink?: string;}) {return (<div className="max-w-xs flex flex-col text-center items-center space-y-3 p-5"><p className="text-sm text-gray-700">{title}</p>- <Link href={ctaLink}>- <a className="py-1.5 px-3 bg-black hover:bg-white rounded-full border border-black text-sm text-white hover:text-black transition-all mt-4">- {cta}- </a>- </Link>+ {cta && ctaLink && (+ <Link href={ctaLink}>+ <a className="py-1.5 px-3 bg-black hover:bg-white rounded-full border border-black text-sm text-white hover:text-black transition-all mt-4">+ {cta}+ </a>+ </Link>+ )}</div>);}diff --git a/lib/auth.ts b/lib/auth.tsindex 7220e1f4a3..5120ca9492 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -70,6 +70,16 @@ const withProjectAuth =slug: true,domain: true,domainVerified: true,+ ownerUsageLimit: true,+ ownerExceededUsage: true,+ users: {+ where: {+ userId: session.user.id,+ },+ select: {+ role: true,+ },+ },},})) as ProjectProps;@@ -98,7 +108,7 @@ const withProjectAuth =return res.status(403).end("Unauthorized: Usage limits exceeded.");}- const freePlan = user.usageLimit === 1000;+ const freePlan = project.ownerUsageLimit === 1000;if (needProSubscription && freePlan) {return res.status(403).end("Unauthorized: Need pro subscription");}diff --git a/lib/cron.ts b/lib/cron.tsindex be9f0e3a41..f0b8d1b244 100644--- a/lib/cron.ts+++ b/lib/cron.ts@@ -57,6 +57,7 @@ export const updateUsage = async () => {select: {project: {select: {+ id: true,domain: true,domainVerified: true,},@@ -76,28 +77,52 @@ export const updateUsage = async () => {if (projects.length === 0) return;const usageArr = await Promise.all(- projects.map(async ({ project: { domain, domainVerified } }) => {- return domainVerified- ? await getUsage(domain, billingCycleStart)- : 0;+ projects.map(async ({ project: { id, domain, domainVerified } }) => {+ return {+ id,+ usage: domainVerified+ ? await getUsage(domain, billingCycleStart)+ : 0,+ };}));- let totalUsage = usageArr.reduce((a, b) => a + b, 0);+ let totalUsage = usageArr.reduce((acc, { usage }) => acc + usage, 0);+ let ownerExceededUsage = totalUsage > usageLimit;- if (totalUsage > usageLimit) {+ if (ownerExceededUsage) {await log(`${email} is over usage limit. Usage: ${totalUsage}, Limit: ${usageLimit}`);}- return await prisma.user.update({- where: {- id,- },- data: {- usage: totalUsage,- },- });+ const [updateUser, updateProjects] = await Promise.all([+ prisma.user.update({+ where: {+ id,+ },+ data: {+ usage: totalUsage,+ },+ }),+ Promise.all(+ usageArr.map(async ({ id, usage }) => {+ return await prisma.project.update({+ where: {+ id,+ },+ data: {+ usage,+ ownerExceededUsage,+ },+ });+ })+ ),+ ]);++ return {+ updateUser,+ updateProjects,+ };}));diff --git a/lib/swr/use-project.ts b/lib/swr/use-project.tsindex e463e26a61..31569b19a0 100644--- a/lib/swr/use-project.ts+++ b/lib/swr/use-project.ts@@ -1,4 +1,5 @@import useSWR from "swr";+import { useMemo } from "react";import { fetcher } from "@/lib/utils";import { useRouter } from "next/router";import { ProjectProps } from "@/lib/types";@@ -18,8 +19,15 @@ export default function useProject() {});+ const isOwner = useMemo(() => {+ if (project && Array.isArray(project.users)) {+ return project.users[0].role === "owner";+ }+ }, [project]);+return {project,+ isOwner,loading: !error && !project,error,};diff --git a/lib/swr/use-usage.ts b/lib/swr/use-usage.tsindex 0fad0dc79b..441ffa1b28 100644--- a/lib/swr/use-usage.ts+++ b/lib/swr/use-usage.ts@@ -1,24 +1,31 @@import useSWR from "swr";import { useMemo } from "react";+import { useRouter } from "next/router";import { fetcher } from "@/lib/utils";import { UsageProps } from "@/lib/types";-import { getPlanFromUsageLimit, PRO_TIERS } from "@/lib/stripe/constants";+import { getPlanFromUsageLimit } from "@/lib/stripe/constants";-export default function useUsage({ settingsPage } = { settingsPage: false }) {+export default function useUsage() {+ const router = useRouter();+ const { slug } = router.query;const { data, error } = useSWR<UsageProps>(- `/api/usage${settingsPage ? "?settingsPage=1" : ""}`,+ slug ? `/api/projects/${slug}/usage` : `/api/usage`,fetcher);const exceededUsage = useMemo(() => {if (data) {- return data.usage > data.usageLimit;+ return slug ? data.ownerExceededUsage : data.usage > data.usageLimit;}}, [data]);+ console.log(data);+const plan = useMemo(() => {if (data) {- return getPlanFromUsageLimit(data.usageLimit);+ return getPlanFromUsageLimit(+ slug ? data.ownerUsageLimit : data.usageLimit+ );}}, [data]);diff --git a/lib/types.ts b/lib/types.tsindex 1fc65e78e1..21c4c2052b 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -17,6 +17,11 @@ export interface ProjectProps {slug: string;domain: string;domainVerified: boolean;+ ownerUsageLimit?: number;+ ownerExceededUsage?: boolean;+ users?: {+ role: string;+ }[];}export interface UsageProps {@@ -24,6 +29,8 @@ export interface UsageProps {usageLimit: number;projectCount?: number;billingCycleStart?: number;+ ownerUsageLimit?: number;+ ownerExceededUsage?: boolean;}export interface UserProps {diff --git a/pages/api/projects/[slug]/usage.ts b/pages/api/projects/[slug]/usage.tsnew file mode 100644index 0000000000..7b2efdcc81--- /dev/null+++ b/pages/api/projects/[slug]/usage.ts@@ -0,0 +1,25 @@+import { NextApiRequest, NextApiResponse } from "next";+import { withProjectAuth } from "@/lib/auth";+import { ProjectProps } from "@/lib/types";++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]/usage – get the usage stats specific project (dependent on owner's plan)+ if (req.method === "GET") {+ return res.status(200).json(project);+ // DELETE /api/projects/[slug] – delete a project+ } else {+ res.setHeader("Allow", ["GET"]);+ return res+ .status(405)+ .json({ error: `Method ${req.method} Not Allowed` });+ }+ }+);diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.tsindex a58e3ee86b..588af0b82d 100644--- a/pages/api/stripe/webhook.ts+++ b/pages/api/stripe/webhook.ts@@ -46,65 +46,126 @@ export default async function webhookHandler(}if (relevantEvents.has(event.type)) {try {- switch (event.type) {- case "checkout.session.completed":- const checkoutSession = event.data- .object as Stripe.Checkout.Session;+ if (event.type === "checkout.session.completed") {+ const checkoutSession = event.data.object as Stripe.Checkout.Session;- // when the user subscribes to a plan, set their stripe customer ID- // in the database for easy identification in future webhook events- await prisma.user.update({+ // when the user subscribes to a plan, set their stripe customer ID+ // in the database for easy identification in future webhook events++ await prisma.user.update({+ where: {+ id: checkoutSession.client_reference_id,+ },+ data: {+ stripeId: checkoutSession.customer.toString(),+ billingCycleStart: new Date().getDate(),+ },+ });+ } else if (event.type === "customer.subscription.updated") {+ const subscriptionUpdated = event.data.object as Stripe.Subscription;+ const newPriceId = subscriptionUpdated.items.data[0].price.id;+ const env =+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"+ ? "production"+ : "test";+ const tier = PRO_TIERS.find(+ (tier) =>+ tier.price.monthly.priceIds[env] === newPriceId ||+ tier.price.yearly.priceIds[env] === newPriceId+ );+ const usageLimit = tier.quota;+ const stripeId = subscriptionUpdated.customer.toString();++ // If a user upgrades/downgrades their subscription, update their usage limit in the database.+ // We also need to update the ownerUsageLimit field for all their projects.++ const { projects } = await prisma.user.findUnique({+ where: {+ stripeId,+ },+ select: {+ projects: {+ where: {+ role: "owner",+ },+ select: {+ projectId: true,+ },+ },+ },+ });++ await Promise.all([+ prisma.user.update({where: {- id: checkoutSession.client_reference_id,+ stripeId,},data: {- stripeId: checkoutSession.customer.toString(),+ usageLimit,billingCycleStart: new Date().getDate(),},- });- break;+ }),+ Promise.all(+ projects.map(async ({ projectId }) => {+ return await prisma.project.update({+ where: {+ id: projectId,+ },+ data: {+ ownerUsageLimit: usageLimit,+ },+ });+ })+ ),+ ]);+ } else if (event.type === "customer.subscription.deleted") {+ const subscriptionDeleted = event.data.object as Stripe.Subscription;- case "customer.subscription.updated":- const subscriptionUpdated = event.data- .object as Stripe.Subscription;- const newPriceId = subscriptionUpdated.items.data[0].price.id;- const env =- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"- ? "production"- : "test";- const tier = PRO_TIERS.find(- (tier) =>- tier.price.monthly.priceIds[env] === newPriceId ||- tier.price.yearly.priceIds[env] === newPriceId- );- const usageLimit = tier.quota;+ const stripeId = subscriptionDeleted.customer.toString();- // If a user upgrades/downgrades their subscription,- // update their usage limit in the database.- await prisma.user.update({- where: {- stripeId: subscriptionUpdated.customer.toString(),- },- data: {- usageLimit,+ // If a user deletes their subscription, reset their usage limit in the database to 1000.+ // We also need to reset the ownerUsageLimit field for all their projects to 1000.++ const { projects } = await prisma.user.findUnique({+ where: {+ stripeId,+ },+ select: {+ projects: {+ where: {+ role: "owner",+ },+ select: {+ projectId: true,+ },},- });- break;+ },+ });- case "customer.subscription.deleted":- const subscriptionDeleted = event.data- .object as Stripe.Subscription;- await prisma.user.update({+ await Promise.all([+ prisma.user.update({where: {- stripeId: subscriptionDeleted.customer.toString(),+ stripeId,},data: {usageLimit: 1000,},- });- break;- default:- throw new Error("Unhandled relevant event!");+ }),+ Promise.all(+ projects.map(async ({ projectId }) => {+ return await prisma.project.update({+ where: {+ id: projectId,+ },+ data: {+ ownerUsageLimit: 1000,+ },+ });+ })+ ),+ ]);+ } else {+ throw new Error("Unhandled relevant event!");}} catch (error) {console.log(error);diff --git a/pages/api/usage/index.ts b/pages/api/usage/index.tsindex 9b0bd6b368..e350fe23b8 100644--- a/pages/api/usage/index.ts+++ b/pages/api/usage/index.ts@@ -6,9 +6,6 @@ export default withUserAuth(async (req: NextApiRequest, res: NextApiResponse, userId: string) => {// GET /api/usage – get a user's usage over all the projects they're an owner ofif (req.method === "GET") {- const { settingsPage } = req.query as {- settingsPage: string;- };const response = await prisma.user.findUnique({where: {id: userId,@@ -16,22 +13,18 @@ export default withUserAuth(select: {usage: true,usageLimit: true,- ...(settingsPage === "1" && {- billingCycleStart: true,- projects: {- where: {- role: "owner",- },+ billingCycleStart: true,+ projects: {+ where: {+ role: "owner",},- }),+ },},});return res.status(200).json({...response,- ...(settingsPage === "1" && {- projects: undefined,- projectCount: response?.projects?.length || "0",- }),+ projects: undefined,+ projectCount: response?.projects?.length || "0",});} else {res.setHeader("Allow", ["GET"]);diff --git a/pages/app/[slug]/[key].tsx b/pages/app/[slug]/[key].tsxindex 5c62b614f9..1d45a18fd1 100644--- a/pages/app/[slug]/[key].tsx+++ b/pages/app/[slug]/[key].tsx@@ -9,7 +9,7 @@ import ErrorPage from "next/error";import useUsage from "@/lib/swr/use-usage";export default function StatsPage() {- const { project, error } = useProject();+ const { project, isOwner, error } = useProject();const { exceededUsage } = useUsage();// handle error page@@ -29,8 +29,9 @@ export default function StatsPage() {Stats Locked</h1><p className="text-gray-600 text-sm max-w-sm text-center z-10">- You have exceeded your usage limits. We're still collecting data- on your link, but you need to upgrade to view them.+ {isOwner+ ? "You have exceeded your usage limits. We're still collecting data on your link, but you need to upgrade to view them."+ : "The owner of this project has exceeded their usage limits. We're still collecting data on this link, but they need to upgrade to view them."}</p><BlurImagesrc="/static/illustrations/video-park.svg"@@ -39,11 +40,13 @@ export default function StatsPage() {height={400}className="-my-8"/>- <Link href="/settings">- <a className="text-white hover:text-black bg-black hover:bg-white font-medium text-sm px-10 py-2 border rounded-md border-black transition-all duration-75 z-10">- Upgrade now- </a>- </Link>+ {isOwner && (+ <Link href="/settings">+ <a className="text-white hover:text-black bg-black hover:bg-white font-medium text-sm px-10 py-2 border rounded-md border-black transition-all duration-75 z-10">+ Upgrade now+ </a>+ </Link>+ )}</div></MaxWidthWrapper>)}diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 49cd1eacf0..df6208d23d 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -64,16 +64,19 @@ model VerificationToken {}model Project {- id String @id @default(cuid())- name String- slug String @unique- logo String?- domain String @unique- domainVerified Boolean @default(false)- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt- domainLastChecked DateTime @default(now())- users ProjectUsers[]+ id String @id @default(cuid())+ name String+ slug String @unique+ logo String?+ domain String @unique+ domainVerified Boolean @default(false)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ domainLastChecked DateTime @default(now())+ usage Int @default(0)+ ownerUsageLimit Int @default(1000)+ ownerExceededUsage Boolean @default(false)+ users ProjectUsers[]}model ProjectUsers {