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.

Use RSC for integrations

Steven Teyddfdfc01daee
diff --git a/apps/web/app/api/integrations/[slug]/uninstall/route.ts b/apps/web/app/api/integrations/[slug]/uninstall/route.ts
new file mode 100644
index 0000000000..ff308c6a75
--- /dev/null
+++ b/apps/web/app/api/integrations/[slug]/uninstall/route.ts
@@ -0,0 +1,54 @@
+// GET /api/integrations/[slug]/installation - get an installation by slug
+
+import { DubApiError } from "@/lib/api/errors";
+import { withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { NextResponse } from "next/server";
+
+// DELETE /api/integrations/[slug]/installation - delete an installation by slug
+export const DELETE = withWorkspace(
+ async ({ params, workspace }) => {
+ const integration = await prisma.oAuthAuthorizedApp.findFirst({
+ where: {
+ projectId: workspace.id,
+ oAuthApp: {
+ slug: params.slug,
+ },
+ },
+ select: {
+ id: true,
+ clientId: true,
+ userId: true,
+ },
+ });
+
+ if (!integration) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Integration not found",
+ });
+ }
+
+ await prisma.$transaction([
+ prisma.oAuthAuthorizedApp.delete({
+ where: {
+ id: integration.id,
+ },
+ }),
+ prisma.restrictedToken.delete({
+ where: {
+ userId_projectId_clientId: {
+ userId: integration.userId,
+ projectId: workspace.id,
+ clientId: integration.clientId,
+ },
+ },
+ }),
+ ]);
+
+ return NextResponse.json({ id: params.clientId });
+ },
+ {
+ requiredPermissions: ["integrations.write"],
+ },
+);
diff --git a/apps/web/app/api/integrations/installations/[installationId]/route.ts b/apps/web/app/api/integrations/installations/[installationId]/route.ts
deleted file mode 100644
index e1d610f5d0..0000000000
--- a/apps/web/app/api/integrations/installations/[installationId]/route.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { withWorkspace } from "@/lib/auth";
-import { prisma } from "@/lib/prisma";
-import { NextResponse } from "next/server";
-
-// DELETE /api/integrations/installations/[installationId] - Uninstall an integration from the workspace
-export const DELETE = withWorkspace(
- async ({ params, workspace, session }) => {
- const uninstalledIntegration = await prisma.oAuthAuthorizedApp.delete({
- where: {
- id: params.installationId,
- },
- select: {
- oAuthApp: {
- select: {
- clientId: true,
- },
- },
- },
- });
-
- // TODO: refactor to just delete by installationId
- await prisma.restrictedToken.delete({
- where: {
- userId_projectId_clientId: {
- userId: session.user.id,
- projectId: workspace.id,
- clientId: uninstalledIntegration.oAuthApp.clientId,
- },
- },
- });
-
- return NextResponse.json({ id: params.clientId });
- },
- {
- requiredPermissions: ["integrations.disconnect"],
- },
-);
diff --git a/apps/web/app/api/integrations/installations/route.ts b/apps/web/app/api/integrations/installations/route.ts
deleted file mode 100644
index 9fdd13713d..0000000000
--- a/apps/web/app/api/integrations/installations/route.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { withWorkspace } from "@/lib/auth";
-import { prisma } from "@/lib/prisma";
-import { NextResponse } from "next/server";
-
-// GET /api/integrations/installations - get all installed integrations for a specific workspace
-export const GET = withWorkspace(
- async ({ workspace }) => {
- const result = await prisma.oAuthAuthorizedApp.findMany({
- where: {
- projectId: workspace.id,
- },
- select: {
- id: true,
- createdAt: true,
- oAuthApp: {
- select: {
- clientId: true,
- slug: true,
- name: true,
- developer: true,
- website: true,
- logo: true,
- },
- },
- user: {
- select: {
- id: true,
- name: true,
- },
- },
- },
- });
-
- const installedIntegrations = result.map((integration) => ({
- id: integration.id,
- createdAt: integration.createdAt,
- clientId: integration.oAuthApp.clientId,
- name: integration.oAuthApp.name,
- slug: integration.oAuthApp.slug,
- developer: integration.oAuthApp.developer,
- website: integration.oAuthApp.website,
- logo: integration.oAuthApp.logo,
- user: {
- id: integration.user.id,
- name: integration.user.name,
- },
- }));
-
- return NextResponse.json(installedIntegrations);
- },
- {
- requiredPermissions: ["integrations.read"],
- },
-);
diff --git a/apps/web/app/api/integrations/list/route.ts b/apps/web/app/api/integrations/list/route.ts
deleted file mode 100644
index 3d4b6072a8..0000000000
--- a/apps/web/app/api/integrations/list/route.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { prisma } from "@/lib/prisma";
-import z from "@/lib/zod";
-import { oAuthAppSchema } from "@/lib/zod/schemas/oauth";
-import { getSearchParams } from "@dub/utils";
-import { NextRequest, NextResponse } from "next/server";
-
-// GET /api/integrations/list - get a list of all verified integrations on Dub
-export const GET = async (req: NextRequest) => {
- const { page } = getSearchParams(req.url);
-
- const integrations = await prisma.oAuthApp.findMany({
- where: {
- verified: true,
- },
- include: {
- _count: {
- select: {
- authorizedApps: true,
- },
- },
- },
- take: 50,
- skip: (page ? parseInt(page) : 1 - 1) * 50,
- });
-
- return NextResponse.json(
- z
- .array(
- oAuthAppSchema
- .omit({
- clientSecret: true,
- redirectUri: true,
- pkce: true,
- })
- .merge(
- z.object({
- installations: z.number(),
- }),
- ),
- )
- .parse(
- integrations.map((integration) => ({
- ...integration,
- installations: integration._count.authorizedApps,
- })),
- ),
- );
-};
diff --git a/apps/web/app/api/integrations/route.ts b/apps/web/app/api/integrations/route.ts
index 4c4be6226f..1331b671ba 100644
--- a/apps/web/app/api/integrations/route.ts
+++ b/apps/web/app/api/integrations/route.ts
@@ -1,71 +1,48 @@
-import { OAUTH_CONFIG } from "@/lib/api/oauth/constants";
-import { createToken } from "@/lib/api/oauth/utils";
-import { parseRequestBody } from "@/lib/api/utils";
-import { hashToken, withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { createOAuthAppSchema, oAuthAppSchema } from "@/lib/zod/schemas/oauth";
-import { NextResponse } from "next/server";
-import { z } from "zod";
+import z from "@/lib/zod";
+import { oAuthAppSchema } from "@/lib/zod/schemas/oauth";
+import { getSearchParams } from "@dub/utils";
+import { NextRequest, NextResponse } from "next/server";
-// GET /api/integrations - get all integrations created by a workspace
-export const GET = withWorkspace(
- async ({ workspace }) => {
- const apps = await prisma.oAuthApp.findMany({
- where: {
- projectId: workspace.id,
- },
- });
-
- return NextResponse.json(z.array(oAuthAppSchema).parse(apps));
- },
- {
- requiredPermissions: ["oauth_apps.read"],
- featureFlag: "integrations",
- },
-);
-
-// POST /api/integrations - create a new integration
-export const POST = withWorkspace(
- async ({ req, workspace, session }) => {
- const { name, slug, developer, website, redirectUri, logo, pkce } =
- createOAuthAppSchema.parse(await parseRequestBody(req));
+// GET /api/integrations - get all integrations on Dub
+export const GET = async (req: NextRequest) => {
+ const { page } = getSearchParams(req.url);
- const clientId = createToken({
- length: OAUTH_CONFIG.CLIENT_ID_LENGTH,
- prefix: OAUTH_CONFIG.CLIENT_ID_PREFIX,
- });
-
- const clientSecret = createToken({
- length: OAUTH_CONFIG.CLIENT_SECRET_LENGTH,
- prefix: OAUTH_CONFIG.CLIENT_SECRET_PREFIX,
- });
-
- const client = await prisma.oAuthApp.create({
- data: {
- projectId: workspace.id,
- name,
- slug,
- developer,
- website,
- redirectUri,
- logo,
- clientId,
- hashedClientSecret: await hashToken(clientSecret),
- userId: session.user.id,
- pkce,
+ const integrations = await prisma.oAuthApp.findMany({
+ where: {
+ verified: true,
+ },
+ include: {
+ _count: {
+ select: {
+ authorizedApps: true,
+ },
},
- });
+ },
+ take: 50,
+ skip: (page ? parseInt(page) : 1 - 1) * 50,
+ });
- return NextResponse.json(
- {
- ...oAuthAppSchema.parse(client),
- clientSecret,
- },
- { status: 201 },
- );
- },
- {
- requiredPermissions: ["oauth_apps.write"],
- featureFlag: "integrations",
- },
-);
+ return NextResponse.json(
+ z
+ .array(
+ oAuthAppSchema
+ .omit({
+ clientSecret: true,
+ redirectUri: true,
+ pkce: true,
+ })
+ .merge(
+ z.object({
+ installations: z.number(),
+ }),
+ ),
+ )
+ .parse(
+ integrations.map((integration) => ({
+ ...integration,
+ installations: integration._count.authorizedApps,
+ })),
+ ),
+ );
+};
diff --git a/apps/web/app/api/integrations/[clientId]/route.ts b/apps/web/app/api/oauth/apps/[clientId]/route.ts
similarity index 90%
rename from apps/web/app/api/integrations/[clientId]/route.ts
rename to apps/web/app/api/oauth/apps/[clientId]/route.ts
index 54d720249f..35d1e99706 100644
--- a/apps/web/app/api/integrations/[clientId]/route.ts
+++ b/apps/web/app/api/oauth/apps/[clientId]/route.ts
@@ -5,7 +5,7 @@ import { prisma } from "@/lib/prisma";
import { oAuthAppSchema, updateOAuthAppSchema } from "@/lib/zod/schemas/oauth";
import { NextResponse } from "next/server";
-// GET /api/integrations/[clientId] – get an integration created by the workspace
+// GET /api/oauth/apps/[clientId] – get an OAuth app created by the workspace
export const GET = withWorkspace(
async ({ params, workspace }) => {
const app = await prisma.oAuthApp.findFirst({
@@ -30,7 +30,7 @@ export const GET = withWorkspace(
},
);
-// PATCH /api/integrations/[clientId] – update an integration
+// PATCH /api/oauth/apps/[clientId] – update an OAuth app
export const PATCH = withWorkspace(
async ({ req, params, workspace }) => {
const { name, slug, developer, website, redirectUri, logo, pkce } =
@@ -60,7 +60,7 @@ export const PATCH = withWorkspace(
},
);
-// DELETE /api/integrations/[clientId] - delete an integration
+// DELETE /api/oauth/apps/[clientId] - delete an OAuth app
export const DELETE = withWorkspace(
async ({ params, workspace }) => {
const app = await prisma.oAuthApp.findFirst({
diff --git a/apps/web/app/api/oauth/apps/route.ts b/apps/web/app/api/oauth/apps/route.ts
new file mode 100644
index 0000000000..56feb8901c
--- /dev/null
+++ b/apps/web/app/api/oauth/apps/route.ts
@@ -0,0 +1,71 @@
+import { OAUTH_CONFIG } from "@/lib/api/oauth/constants";
+import { createToken } from "@/lib/api/oauth/utils";
+import { parseRequestBody } from "@/lib/api/utils";
+import { hashToken, withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { createOAuthAppSchema, oAuthAppSchema } from "@/lib/zod/schemas/oauth";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+// GET /api/oauth/apps - get all OAuth apps created by a workspace
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const apps = await prisma.oAuthApp.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ });
+
+ return NextResponse.json(z.array(oAuthAppSchema).parse(apps));
+ },
+ {
+ requiredPermissions: ["oauth_apps.read"],
+ featureFlag: "integrations",
+ },
+);
+
+// POST /api/oauth/apps - create a new OAuth app
+export const POST = withWorkspace(
+ async ({ req, workspace, session }) => {
+ const { name, slug, developer, website, redirectUri, logo, pkce } =
+ createOAuthAppSchema.parse(await parseRequestBody(req));
+
+ const clientId = createToken({
+ length: OAUTH_CONFIG.CLIENT_ID_LENGTH,
+ prefix: OAUTH_CONFIG.CLIENT_ID_PREFIX,
+ });
+
+ const clientSecret = createToken({
+ length: OAUTH_CONFIG.CLIENT_SECRET_LENGTH,
+ prefix: OAUTH_CONFIG.CLIENT_SECRET_PREFIX,
+ });
+
+ const client = await prisma.oAuthApp.create({
+ data: {
+ projectId: workspace.id,
+ name,
+ slug,
+ developer,
+ website,
+ redirectUri,
+ logo,
+ clientId,
+ hashedClientSecret: await hashToken(clientSecret),
+ userId: session.user.id,
+ pkce,
+ },
+ });
+
+ return NextResponse.json(
+ {
+ ...oAuthAppSchema.parse(client),
+ clientSecret,
+ },
+ { status: 201 },
+ );
+ },
+ {
+ requiredPermissions: ["oauth_apps.write"],
+ featureFlag: "integrations",
+ },
+);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/[integrationSlug]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/[integrationSlug]/page-client.tsx
index 4b78cf66d7..4b6cb79cad 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/[integrationSlug]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/[integrationSlug]/page-client.tsx
@@ -1,26 +1,141 @@
"use client";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { OAuthAppProps } from "@/lib/types";
import { useDeleteAppModal } from "@/ui/modals/delete-oauth-app-modal";
-import { Button, MaxWidthWrapper } from "@dub/ui";
+import { ThreeDots } from "@/ui/shared/icons";
+import {
+ Avatar,
+ BlurImage,
+ Button,
+ MaxWidthWrapper,
+ Popover,
+ TokenAvatar,
+} from "@dub/ui";
+import { Globe, ReferredVia } from "@dub/ui/src/icons";
+import { cn, formatDate, getPrettyUrl } from "@dub/utils";
+import { ChevronLeft, Trash } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+
+export default function IntegrationPageClient({
+ integration,
+}: {
+ integration: OAuthAppProps & {
+ installations: number;
+ installed: {
+ by: {
+ id: string;
+ name: string | null;
+ image: string | null;
+ };
+ createdAt: Date;
+ } | null;
+ };
+}) {
+ const { slug } = useWorkspace();
+
+ const [openPopover, setOpenPopover] = useState(false);
-export default function IntegrationPageClient() {
const { DeleteAppModal, setShowDeleteAppModal } = useDeleteAppModal({
- app: {
- clientId: "123",
- name: "test",
- },
+ app: integration,
appType: "authorized",
});
return (
- <MaxWidthWrapper className="my-20">
+ <MaxWidthWrapper className="my-10 grid max-w-screen-lg gap-8">
<DeleteAppModal />
- <div className="w-fit">
- <Button
- text="Uninstall"
- variant="secondary"
- onClick={() => setShowDeleteAppModal(true)}
- />
+ <Link
+ href={`/${slug}/integrations`}
+ className="flex items-center gap-x-1"
+ >
+ <ChevronLeft className="size-4" />
+ <p className="text-sm font-medium text-gray-500">Integrations</p>
+ </Link>
+ <div className="flex justify-between">
+ <div className="flex items-center gap-x-3">
+ <div className="rounded-md border border-gray-200 bg-gradient-to-t from-gray-100 p-2">
+ {integration.logo ? (
+ <BlurImage
+ src={integration.logo}
+ alt={`Logo for ${integration.name}`}
+ className="size-8 rounded-full border border-gray-200"
+ width={20}
+ height={20}
+ />
+ ) : (
+ <TokenAvatar id={integration.clientId} className="size-8" />
+ )}
+ </div>
+ <div>
+ <p className="font-semibold text-gray-700">{integration.name}</p>
+ <p className="text-sm text-gray-500">{integration.description}</p>
+ </div>
+ </div>
+ <Popover
+ align="end"
+ content={
+ <div className="grid w-screen gap-px p-2 sm:w-48">
+ <Button
+ text="Uninstall Integration"
+ variant="danger-outline"
+ icon={<Trash className="h-4 w-4" />}
+ className="h-9 justify-start px-2"
+ onClick={() => {
+ setShowDeleteAppModal(true);
+ }}
+ />
+ </div>
+ }
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <button
+ onClick={() => setOpenPopover(!openPopover)}
+ className={cn(
+ "flex h-10 items-center rounded-md border px-1.5 outline-none transition-all",
+ "border-gray-200 bg-white text-gray-900 placeholder-gray-400",
+ "focus-visible:border-gray-500 data-[state=open]:border-gray-500 data-[state=open]:ring-4 data-[state=open]:ring-gray-200",
+ )}
+ >
+ <ThreeDots className="h-5 w-5 text-gray-500" />
+ </button>
+ </Popover>
+ </div>
+ <div className="flex gap-12 rounded-lg border border-gray-200 p-4">
+ {integration.installed && (
+ <div className="flex items-center gap-2">
+ <Avatar user={integration.installed.by} className="size-8" />
+ <div>
+ <p className="text-xs text-gray-500">INSTALLED BY</p>
+ <p className="text-sm font-medium text-gray-700">
+ {integration.installed.by.name}
+ <span className="ml-1 font-normal text-gray-500">
+ {formatDate(integration.installed.createdAt, {
+ year: undefined,
+ })}
+ </span>
+ </p>
+ </div>
+ </div>
+ )}
+ <div>
+ <p className="text-xs text-gray-500">DEVELOPER</p>
+ <div className="flex items-center gap-x-1 text-sm font-medium text-gray-700">
+ <ReferredVia className="size-4" />
+ {integration.developer}
+ </div>
+ </div>
+ <div>
+ <p className="text-gray-5000 text-xs">WEBSITE</p>
+ <a
+ href={integration.website}
+ className="flex items-center gap-x-1 text-sm font-medium text-gray-700"
+ >
+ <Globe className="size-4" />
+ {getPrettyUrl(integration.website)}
+ </a>
+ </div>
</div>
</MaxWidthWrapper>
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/[integrationSlug]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/[integrationSlug]/page.tsx
index 330fe8ffc1..c3884c7ce3 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/[integrationSlug]/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/[integrationSlug]/page.tsx
@@ -1,5 +1,62 @@
+import { prisma } from "@/lib/prisma";
+import { notFound } from "next/navigation";
import IntegrationPageClient from "./page-client";
-export default function IntegrationPage() {
- return <IntegrationPageClient />;
+export default async function IntegrationPage({
+ params,
+}: {
+ params: { slug: string; integrationSlug: string };
+}) {
+ const integration = await prisma.oAuthApp.findUnique({
+ where: {
+ slug: params.integrationSlug,
+ },
+ include: {
+ _count: {
+ select: {
+ authorizedApps: true,
+ },
+ },
+ authorizedApps: {
+ where: {
+ project: {
+ slug: params.slug,
+ },
+ },
+ include: {
+ user: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!integration) {
+ notFound();
+ }
+
+ return (
+ <IntegrationPageClient
+ integration={{
+ ...integration,
+ installations: integration._count.authorizedApps,
+ installed:
+ integration.authorizedApps.length > 0
+ ? {
+ by: {
+ id: integration.authorizedApps[0].userId,
+ name: integration.authorizedApps[0].user.name,
+ image: integration.authorizedApps[0].user.image,
+ },
+ createdAt: integration.authorizedApps[0].createdAt,
+ }
+ : null,
+ }}
+ />
+ );
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/integration-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/integration-card.tsx
index 008639d46c..8007db7e5e 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/integration-card.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/integration-card.tsx
@@ -1,47 +1,46 @@
-import useInstalledIntegrations from "@/lib/swr/use-installed-integrations";
import useWorkspace from "@/lib/swr/use-workspace";
import { OAuthAppProps } from "@/lib/types";
import { BlurImage, TokenAvatar } from "@dub/ui";
import Link from "next/link";
-export default function IntegrationCard(app: OAuthAppProps) {
+export default function IntegrationCard(
+ integration: OAuthAppProps & { installations: number; installed: boolean },
+) {
const { slug } = useWorkspace();
- const { integrations: installedIntegrations } = useInstalledIntegrations();
- const installed =
- installedIntegrations?.find((i) => i.clientId === app.clientId) || false;
-
return (
<Link
- href={`/${slug}/integrations/${app.slug}`}
+ href={`/${slug}/integrations/${integration.slug}`}
className="relative rounded-xl border border-gray-200 bg-white px-5 py-4 transition-[filter] hover:[filter:drop-shadow(0_8px_12px_#222A350d)_drop-shadow(0_32px_80px_#2f30370f)]"
>
- {installed && (
+ {integration.installed && (
<p className="absolute right-4 top-4 text-xs text-gray-500">
INSTALLED
</p>
)}
<div className="flex items-center gap-x-3">
<div className="rounded-md border border-gray-200 bg-gradient-to-t from-gray-100 p-2">
- {app.logo ? (
+ {integration.logo ? (
<BlurImage
- src={app.logo}
- alt={`Logo for ${app.name}`}
+ src={integration.logo}
+ alt={`Logo for ${integration.name}`}
className="size-6 rounded-full border border-gray-200"
width={20}
height={20}
/>
) : (
- <TokenAvatar id={app.clientId} className="size-6" />
+ <TokenAvatar id={integration.clientId} className="size-6" />
)}
</div>
- <p className="font-semibold text-gray-700">{app.name}</p>
+ <p className="font-semibold text-gray-700">{integration.name}</p>
</div>
<div className="mt-4 grid gap-2">
- <p className="text-sm text-gray-500">{app.description}</p>
+ <p className="text-sm text-gray-500">{integration.description}</p>
<p className="text-sm text-gray-500">
Built by{" "}
- <span className="font-medium text-gray-700">{app.developer}</span>
+ <span className="font-medium text-gray-700">
+ {integration.developer}
+ </span>
</p>
</div>
</Link>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/page-client.tsx
index e9149d191a..695c24acf0 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/page-client.tsx
@@ -4,29 +4,23 @@ import useWorkspace from "@/lib/swr/use-workspace";
import { OAuthAppProps } from "@/lib/types";
import { useAddEditAppModal } from "@/ui/modals/add-edit-oauth-app-modal";
import { useAppCreatedModal } from "@/ui/modals/oauth-app-created-modal";
-import EmptyState from "@/ui/shared/empty-state";
-import {
- Button,
- LoadingSpinner,
- MaxWidthWrapper,
- buttonVariants,
-} from "@dub/ui";
-import { Key } from "@dub/ui/src/icons";
-import { cn, fetcher } from "@dub/utils";
+import { Button, MaxWidthWrapper, buttonVariants } from "@dub/ui";
+import { cn } from "@dub/utils";
import Link from "next/link";
import { redirect } from "next/navigation";
import { useState } from "react";
-import useSWR from "swr";
import IntegrationCard from "./integration-card";
-export default function IntegrationsPageClient() {
+export default function IntegrationsPageClient({
+ integrations,
+}: {
+ integrations: (OAuthAppProps & {
+ installations: number;
+ installed: boolean;
+ })[];
+}) {
const { slug, flags } = useWorkspace();
- const { data: allIntegrations, isLoading } = useSWR<OAuthAppProps[]>(
- "/api/integrations/list",
- fetcher,
- );
-
if (!flags?.integrations) {
redirect(`/${slug}`);
}
@@ -77,25 +71,11 @@ export default function IntegrationsPageClient() {
</div>
<MaxWidthWrapper className="flex flex-col gap-3 py-4">
- {isLoading || !allIntegrations ? (
- <div className="flex flex-col items-center justify-center space-y-4 py-20">
- <LoadingSpinner className="h-6 w-6 text-gray-500" />
- <p className="text-sm text-gray-500">Fetching integrations...</p>
- </div>
- ) : allIntegrations.length > 0 ? (
- <div className="grid gap-4 sm:grid-cols-3">
- {allIntegrations.map((app) => (
- <IntegrationCard key={app.clientId} {...app} />
- ))}
- </div>
- ) : (
- <div className="flex flex-col items-center justify-center gap-y-4 rounded-xl border border-gray-200 bg-white py-36">
- <EmptyState
- icon={Key}
- title="You haven't authorized any applications to access Dub workspace on your behalf."
- />
- </div>
- )}
+ <div className="grid gap-4 sm:grid-cols-3">
+ {integrations.map((integration) => (
+ <IntegrationCard key={integration.clientId} {...integration} />
+ ))}
+ </div>
</MaxWidthWrapper>
</>
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/page.tsx
index f5c0a4c3df..9ce35a3ba8 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/page.tsx
@@ -1,5 +1,38 @@
+import { prisma } from "@/lib/prisma";
import IntegrationsPageClient from "./page-client";
-export default function IntegrationsPage() {
- return <IntegrationsPageClient />;
+export default async function IntegrationsPage({
+ params,
+}: {
+ params: { slug: string };
+}) {
+ const integrations = await prisma.oAuthApp.findMany({
+ where: {
+ verified: true,
+ },
+ include: {
+ _count: {
+ select: {
+ authorizedApps: true,
+ },
+ },
+ authorizedApps: {
+ where: {
+ project: {
+ slug: params.slug,
+ },
+ },
+ },
+ },
+ });
+
+ return (
+ <IntegrationsPageClient
+ integrations={integrations.map((integration) => ({
+ ...integration,
+ installations: integration._count.authorizedApps,
+ installed: integration.authorizedApps.length > 0,
+ }))}
+ />
+ );
}
diff --git a/apps/web/lib/api/rbac/permissions.ts b/apps/web/lib/api/rbac/permissions.ts
index 3a271a380d..2e4c34fdbc 100644
--- a/apps/web/lib/api/rbac/permissions.ts
+++ b/apps/web/lib/api/rbac/permissions.ts
@@ -16,7 +16,7 @@ export const PERMISSION_ACTIONS = [
"oauth_apps.read",
"oauth_apps.write",
"integrations.read",
- "integrations.disconnect",
+ "integrations.write",
] as const;
export type PermissionAction = (typeof PERMISSION_ACTIONS)[number];
@@ -102,7 +102,7 @@ export const ROLE_PERMISSIONS: {
roles: ["owner", "member"],
},
{
- action: "integrations.disconnect",
+ action: "integrations.write",
description: "Disconnect authorized OAuth apps",
roles: ["owner", "member"],
},
diff --git a/apps/web/lib/swr/use-installed-integrations.ts b/apps/web/lib/swr/use-installed-integrations.ts
deleted file mode 100644
index 50ac54f496..0000000000
--- a/apps/web/lib/swr/use-installed-integrations.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { InstalledIntegrationProps } from "@/lib/types";
-import { fetcher } from "@dub/utils";
-import useSWR from "swr";
-import useWorkspace from "./use-workspace";
-
-export default function useInstalledIntegrations() {
- const { id } = useWorkspace();
-
- const { data: integrations, isValidating } = useSWR<
- InstalledIntegrationProps[]
- >(id && `/api/integrations/installations?workspaceId=${id}`, fetcher, {
- dedupingInterval: 30000,
- });
-
- return {
- integrations,
- loading: integrations ? false : true,
- isValidating,
- };
-}
diff --git a/apps/web/ui/modals/delete-oauth-app-modal.tsx b/apps/web/ui/modals/delete-oauth-app-modal.tsx
index 236be08b92..cc3010f893 100644
--- a/apps/web/ui/modals/delete-oauth-app-modal.tsx
+++ b/apps/web/ui/modals/delete-oauth-app-modal.tsx
@@ -1,6 +1,7 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { OAuthAppProps } from "@/lib/types";
import { Button, Logo, Modal, useMediaQuery } from "@dub/ui";
+import { useRouter } from "next/navigation";
import {
Dispatch,
SetStateAction,
@@ -14,13 +15,14 @@ import { mutate } from "swr";
interface DeleteAppModalProps {
showDeleteAppModal: boolean;
setShowDeleteAppModal: Dispatch<SetStateAction<boolean>>;
- app: Pick<OAuthAppProps, "name" | "clientId">;
+ app: Pick<OAuthAppProps, "name" | "slug" | "clientId">;
appType: "published" | "authorized";
}
function DeleteAppModal(props: DeleteAppModalProps) {
const { showDeleteAppModal, setShowDeleteAppModal, app, appType } = props;
+ const router = useRouter();
const { isMobile } = useMediaQuery();
const { id: workspaceId } = useWorkspace();
const [deleting, setDeleting] = useState(false);
@@ -28,16 +30,15 @@ function DeleteAppModal(props: DeleteAppModalProps) {
const action = useMemo(() => {
if (appType === "authorized") {
return {
- url: `/api/integrations/${app.clientId}/uninstall?workspaceId=${workspaceId}`,
- mutate: `/api/integrations/installations?workspaceId=${workspaceId}`,
+ url: `/api/integrations/${app.slug}/uninstall?workspaceId=${workspaceId}`,
message: "Successfully uninstalled the application!",
title: `Uninstall ${app.name}`,
description: `This will uninstall the application from your workspace. Are you sure you want to continue?`,
};
} else {
return {
- url: `/api/integrations/${app.clientId}?workspaceId=${workspaceId}`,
- mutate: `/api/integrations?workspaceId=${workspaceId}`,
+ url: `/api/oauth/apps/${app.clientId}?workspaceId=${workspaceId}`,
+ mutate: `/api/oauth/apps?workspaceId=${workspaceId}`,
message: "Successfully deleted the application!",
title: `Delete ${app.name}`,
description: `This will permanently delete the application and revoke all the access tokens associated with it. Are you sure you want to continue?`,
@@ -54,7 +55,11 @@ function DeleteAppModal(props: DeleteAppModalProps) {
const result = await response.json();
if (response.ok) {
- mutate(action.mutate);
+ if (action.mutate) {
+ mutate(action.mutate);
+ } else {
+ router.refresh();
+ }
toast.success(action.message);
setShowDeleteAppModal(false);
} else {
@@ -105,7 +110,7 @@ export function useDeleteAppModal({
app,
appType,
}: {
- app: Pick<OAuthAppProps, "name" | "clientId">;
+ app: Pick<OAuthAppProps, "name" | "slug" | "clientId">;
appType: "published" | "authorized";
}) {
const [showDeleteAppModal, setShowDeleteAppModal] = useState(false);
diff --git a/packages/utils/src/functions/datetime.ts b/packages/utils/src/functions/datetime.ts
index 1eb8174b97..461831625d 100644
--- a/packages/utils/src/functions/datetime.ts
+++ b/packages/utils/src/functions/datetime.ts
@@ -16,13 +16,17 @@ export const parseDateTime = (str: Date | string) => {
return chrono.parseDate(str);
};
-export const formatDate = (datetime: Date | string) => {
+export const formatDate = (
+ datetime: Date | string,
+ options?: Intl.DateTimeFormatOptions,
+) => {
if (datetime.toString() === "Invalid Date") return "";
return new Date(datetime).toLocaleDateString("en-US", {
day: "numeric",
month: "long",
year: "numeric",
timeZone: "UTC",
+ ...options,
});
};