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.

WIP

Kiran K05653ec352e5
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/decline/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/decline/route.ts
new file mode 100644
index 0000000000..556784387d
--- /dev/null
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/decline/route.ts
@@ -0,0 +1,36 @@
+import { DubApiError } from "@/lib/api/errors";
+import { withSession } from "@/lib/auth";
+import { prisma } from "@dub/prisma";
+import { NextResponse } from "next/server";
+
+// POST /api/workspaces/[idOrSlug]/invites/decline – decline a workspace invite
+export const POST = withSession(async ({ session, params }) => {
+ const { idOrSlug: slug } = params;
+
+ const invite = await prisma.projectInvite.findFirst({
+ where: {
+ email: session.user.email,
+ project: {
+ slug,
+ },
+ },
+ });
+
+ if (!invite) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "This invite is not found.",
+ });
+ }
+
+ await prisma.projectInvite.delete({
+ where: {
+ email_projectId: {
+ email: session.user.email,
+ projectId: invite.projectId,
+ },
+ },
+ });
+
+ return NextResponse.json({ message: "Invite declined." });
+});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/auth.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/auth.tsx
index 860f631f97..2ebc86a216 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/auth.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/auth.tsx
@@ -1,18 +1,25 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
+import useWorkspaces from "@/lib/swr/use-workspaces";
import LayoutLoader from "@/ui/layout/layout-loader";
-import { notFound } from "next/navigation";
+import { notFound, redirect } from "next/navigation";
import { ReactNode } from "react";
export default function WorkspaceAuth({ children }: { children: ReactNode }) {
- const { loading, error } = useWorkspace();
+ const { loading: workspaceLoading, error } = useWorkspace();
+ const { workspaces, loading: workspacesLoading } = useWorkspaces();
- if (loading) {
+ if (workspaceLoading || workspacesLoading) {
return <LayoutLoader />;
}
if (error && error.status === 404) {
+ // If user has no workspaces, redirect to onboarding instead of showing 404
+ // if (workspaces && workspaces.length === 0) {
+ // redirect("/onboarding/welcome");
+ // }
+
notFound();
}
diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.ts
index a1eef9a571..8aa2b6e93d 100644
--- a/apps/web/lib/middleware/app.ts
+++ b/apps/web/lib/middleware/app.ts
@@ -1,3 +1,4 @@
+import { prismaEdge } from "@dub/prisma/edge";
import { NextRequest, NextResponse } from "next/server";
import {
ONBOARDING_WINDOW_SECONDS,
@@ -113,6 +114,45 @@ export async function AppMiddleware(req: NextRequest) {
new URL(`${appRedirectPath}${searchParamsString}`, req.url),
);
}
+
+ if (path.startsWith("/onboarding/welcome")) {
+ // Redirect users with pending workspace invites away from onboarding
+ // to accept their invitation instead of creating a new workspace
+ const pendingInvite = await prismaEdge.projectInvite.findFirst({
+ where: {
+ email: user.email,
+ },
+ select: {
+ project: {
+ select: {
+ slug: true,
+ },
+ },
+ },
+ });
+
+ if (pendingInvite) {
+ return NextResponse.redirect(
+ new URL(`/${pendingInvite.project.slug}?invite=1`, req.url),
+ );
+ }
+
+ // If user already has a workspace, redirect them away from onboarding
+ // to their workspaces page instead of allowing them to create a new one
+ const existingWorkspace = await prismaEdge.project.findFirst({
+ where: {
+ users: {
+ some: {
+ userId: user.id,
+ },
+ },
+ },
+ });
+
+ if (existingWorkspace) {
+ return NextResponse.redirect(new URL("/workspaces", req.url));
+ }
+ }
}
// otherwise, rewrite the path to /app
diff --git a/apps/web/ui/modals/accept-invite-modal.tsx b/apps/web/ui/modals/accept-invite-modal.tsx
index dd5cfe96f9..a9caa58f4c 100644
--- a/apps/web/ui/modals/accept-invite-modal.tsx
+++ b/apps/web/ui/modals/accept-invite-modal.tsx
@@ -20,11 +20,74 @@ function AcceptInviteModal({
showAcceptInviteModal: boolean;
setShowAcceptInviteModal: Dispatch<SetStateAction<boolean>>;
}) {
- const { slug } = useParams() as { slug: string };
- const [accepting, setAccepting] = useState(false);
+ const { slug } = useParams<{ slug: string }>();
const { error } = useWorkspace();
const { data: session } = useSession();
const router = useRouter();
+
+ const [accepting, setAccepting] = useState(false);
+ const [declining, setDeclining] = useState(false);
+
+ const acceptInvite = async () => {
+ setAccepting(true);
+
+ try {
+ const response = await fetch(`/api/workspaces/${slug}/invites/accept`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ });
+
+ if (session?.user) {
+ posthog.identify(session.user["id"], {
+ email: session.user.email,
+ name: session.user.name,
+ });
+ }
+
+ if (!response.ok) {
+ const error = await response.json();
+ toast.error(error.message || "Failed to accept invite.");
+ return;
+ }
+
+ posthog.capture("accepted_workspace_invite", {
+ workspace: slug,
+ });
+
+ router.replace(`/${slug}`);
+ setShowAcceptInviteModal(false);
+ toast.success("You now are a part of this workspace!");
+ mutatePrefix("/api/workspaces");
+ } finally {
+ setAccepting(false);
+ }
+ };
+
+ const declineInvite = async () => {
+ setDeclining(true);
+
+ try {
+ const response = await fetch(`/api/workspaces/${slug}/invites/decline`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ toast.error(error.message || "Failed to decline invite.");
+ return;
+ }
+
+ setShowAcceptInviteModal(false);
+ toast.success("You have declined the invite.");
+ mutatePrefix("/api/workspaces");
+ // Use window.location for a full page reload to clear any invite query params
+ window.location.href = "/";
+ } finally {
+ setDeclining(false);
+ }
+ };
+
return (
<Modal
showModal={showAcceptInviteModal}
@@ -44,31 +107,21 @@ function AcceptInviteModal({
workspace on {process.env.NEXT_PUBLIC_APP_NAME}
</p>
</div>
- <div className="flex flex-col space-y-6 bg-neutral-50 px-4 py-8 text-left sm:px-16">
+ <div className="flex gap-2 bg-neutral-50 px-4 py-8 text-left sm:px-16">
<Button
- onClick={() => {
- setAccepting(true);
- fetch(`/api/workspaces/${slug}/invites/accept`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- }).then(() => {
- if (session?.user) {
- posthog.identify(session.user["id"], {
- email: session.user.email,
- name: session.user.name,
- });
- }
- posthog.capture("accepted_workspace_invite", {
- workspace: slug,
- });
- router.replace(`/${slug}`);
- setShowAcceptInviteModal(false);
- toast.success("You now are a part of this workspace!");
- mutatePrefix("/api/workspaces");
- });
- }}
+ variant="secondary"
+ onClick={declineInvite}
+ loading={declining}
+ text="Decline invite"
+ disabled={accepting}
+ className="w-fit"
+ />
+
+ <Button
+ onClick={acceptInvite}
loading={accepting}
text="Accept invite"
+ disabled={declining}
/>
</div>
</>