The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
oAuthApp -> Integration model
Kiran Kfa1737db4bc6
diff --git a/apps/web/app/api/oauth/apps/[appId]/route.ts b/apps/web/app/api/oauth/apps/[appId]/route.tsindex 5aeced6a05..441b23a7b5 100644--- a/apps/web/app/api/oauth/apps/[appId]/route.ts+++ b/apps/web/app/api/oauth/apps/[appId]/route.ts@@ -12,21 +12,37 @@ import { NextResponse } from "next/server";// GET /api/oauth/apps/[appId] – get an OAuth app created by the workspaceexport const GET = withWorkspace(async ({ params, workspace }) => {- const app = await prisma.oAuthApp.findFirst({+ const oAuthApp = await prisma.oAuthApp.findFirst({where: {- id: params.appId,- projectId: workspace.id,+ integration: {+ id: params.appId,+ projectId: workspace.id,+ },+ },+ select: {+ clientId: true,+ partialClientSecret: true,+ redirectUris: true,+ pkce: true,+ integration: true,},});- if (!app) {+ if (!oAuthApp) {throw new DubApiError({code: "not_found",message: `OAuth app with id ${params.appId} not found.`,});}- return NextResponse.json(oAuthAppSchema.parse(app));+ const { integration, ...app } = oAuthApp;++ return NextResponse.json(+ oAuthAppSchema.parse({+ ...app,+ ...integration,+ }),+ );},{requiredPermissions: ["oauth_apps.read"],@@ -51,7 +67,7 @@ export const PATCH = withWorkspace(} = updateOAuthAppSchema.parse(await parseRequestBody(req));try {- const app = await prisma.oAuthApp.findUniqueOrThrow({+ const integration = await prisma.integration.findUniqueOrThrow({where: {id: params.appId,projectId: workspace.id,@@ -63,7 +79,7 @@ export const PATCH = withWorkspace(});let logoUrl: string | undefined;- const logoUpdated = logo && app.logo !== logo;+ const logoUpdated = logo && integration.logo !== logo;// Logo has been changedif (logoUpdated) {@@ -75,7 +91,7 @@ export const PATCH = withWorkspace(logoUrl = result.url;}- const updatedApp = await prisma.oAuthApp.update({+ const updatedRecord = await prisma.integration.update({where: {id: params.appId,projectId: workspace.id,@@ -87,10 +103,29 @@ export const PATCH = withWorkspace(website,description,readme,- redirectUris,- pkce,screenshots,...(logoUrl && { logo: logoUrl }),+ oAuthApp: {+ update: {+ redirectUris,+ pkce,+ },+ },+ },+ select: {+ id: true,+ createdAt: true,+ updatedAt: true,+ name: true,+ slug: true,+ description: true,+ developer: true,+ logo: true,+ website: true,+ readme: true,+ screenshots: true,+ verified: true,+ oAuthApp: true,},});@@ -98,15 +133,15 @@ export const PATCH = withWorkspace((async () => {if (logoUpdated &&- app.logo &&- app.logo.startsWith(`${R2_URL}/integrations`)+ integration.logo &&+ integration.logo.startsWith(`${R2_URL}/integrations`)) {- await storage.delete(app.logo.replace(`${R2_URL}/`, ""));+ await storage.delete(integration.logo.replace(`${R2_URL}/`, ""));}// Remove old screenshots- const oldScreenshots = app.screenshots- ? (app.screenshots as string[])+ const oldScreenshots = integration.screenshots+ ? (integration.screenshots as string[]): [];const removedScreenshots = oldScreenshots?.filter(@@ -117,7 +152,11 @@ export const PATCH = withWorkspace(})(),);- return NextResponse.json(oAuthAppSchema.parse(updatedApp));+ const { oAuthApp, ...updatedIntegration } = updatedRecord;++ return NextResponse.json(+ oAuthAppSchema.parse({ ...oAuthApp, ...updatedIntegration }),+ );} catch (error) {if (error.code === "P2002") {throw new DubApiError({@@ -141,21 +180,21 @@ export const PATCH = withWorkspace(// DELETE /api/oauth/apps/[appId] - delete an OAuth appexport const DELETE = withWorkspace(async ({ params, workspace }) => {- const app = await prisma.oAuthApp.findFirst({+ const integration = await prisma.integration.findFirst({where: {id: params.appId,projectId: workspace.id,},});- if (!app) {+ if (!integration) {throw new DubApiError({code: "not_found",message: `OAuth app with id ${params.appId} not found.`,});}- await prisma.oAuthApp.delete({+ await prisma.integration.delete({where: {id: params.appId,},@@ -163,11 +202,14 @@ export const DELETE = withWorkspace(waitUntil((async () => {- if (app.logo && app.logo.startsWith(`${R2_URL}/integrations`)) {- await storage.delete(app.logo.replace(`${R2_URL}/`, ""));+ if (+ integration.logo &&+ integration.logo.startsWith(`${R2_URL}/integrations`)+ ) {+ await storage.delete(integration.logo.replace(`${R2_URL}/`, ""));}- await deleteScreenshots(app.screenshots);+ await deleteScreenshots(integration.screenshots);})(),);diff --git a/apps/web/app/api/oauth/apps/route.ts b/apps/web/app/api/oauth/apps/route.tsindex 31f8d51363..fae314f638 100644--- a/apps/web/app/api/oauth/apps/route.ts+++ b/apps/web/app/api/oauth/apps/route.ts@@ -5,31 +5,35 @@ import { parseRequestBody } from "@/lib/api/utils";import { hashToken, withWorkspace } from "@/lib/auth";import { prisma } from "@/lib/prisma";import { storage } from "@/lib/storage";+import z from "@/lib/zod";import { createOAuthAppSchema, oAuthAppSchema } from "@/lib/zod/schemas/oauth";import { nanoid } from "@dub/utils";import { NextResponse } from "next/server";-import { z } from "zod";// GET /api/oauth/apps - get all OAuth apps created by a workspaceexport const GET = withWorkspace(async ({ workspace }) => {- const result = await prisma.oAuthApp.findMany({+ const oAuthApp = await prisma.oAuthApp.findMany({where: {- projectId: workspace.id,- },- include: {- _count: {- select: { authorizedApps: true },+ integration: {+ projectId: workspace.id,},},+ select: {+ clientId: true,+ partialClientSecret: true,+ redirectUris: true,+ pkce: true,+ integration: true,+ },});- const apps = result.map((app) => ({- ...app,- installations: app._count.authorizedApps,+ const oAuthApps = oAuthApp.map(({ integration, ...oAuthApp }) => ({+ ...oAuthApp,+ ...integration,}));- return NextResponse.json(z.array(oAuthAppSchema).parse(apps));+ return NextResponse.json(z.array(oAuthAppSchema).parse(oAuthApps));},{requiredPermissions: ["oauth_apps.read"],@@ -53,13 +57,13 @@ export const POST = withWorkspace(screenshots,} = createOAuthAppSchema.parse(await parseRequestBody(req));- const app = await prisma.oAuthApp.findUnique({+ const integration = await prisma.integration.findUnique({where: {slug,},});- if (app) {+ if (integration) {throw new DubApiError({code: "conflict",message: `The slug "${slug}" is already in use.`,@@ -80,43 +84,66 @@ export const POST = withWorkspace(try {let logoUrl: string | undefined;- const appId = nanoid(25);+ const integrationId = nanoid(25);if (logo) {const result = await storage.upload(- `integrations/${appId}_${nanoid(7)}`,+ `integrations/${integrationId}_${nanoid(7)}`,logo,);logoUrl = result.url;}- const app = await prisma.oAuthApp.create({+ const { oAuthApp, ...integration } = await prisma.integration.create({data: {- id: appId,+ id: integrationId,projectId: workspace.id,+ userId: session.user.id,name,slug,developer,website,description,readme,- redirectUris,- clientId,- hashedClientSecret: clientSecret ? await hashToken(clientSecret) : "",- partialClientSecret: clientSecret- ? `dub_app_secret_****${clientSecret.slice(-8)}`- : "",- userId: session.user.id,- pkce,screenshots,...(logoUrl && { logo: logoUrl }),+ oAuthApp: {+ create: {+ clientId,+ projectId: workspace.id,+ userId: session.user.id,+ hashedClientSecret: clientSecret+ ? await hashToken(clientSecret)+ : "",+ partialClientSecret: clientSecret+ ? `dub_app_secret_****${clientSecret.slice(-8)}`+ : "",+ redirectUris,+ pkce,+ },+ },+ },+ select: {+ id: true,+ createdAt: true,+ updatedAt: true,+ name: true,+ slug: true,+ description: true,+ developer: true,+ logo: true,+ website: true,+ readme: true,+ screenshots: true,+ verified: true,+ oAuthApp: true,},});return NextResponse.json({- ...oAuthAppSchema.parse(app),+ ...oAuthAppSchema.parse({ ...oAuthApp, ...integration }),...(clientSecret && { clientSecret }),},{ status: 201 },diff --git a/apps/web/lib/actions/generate-client-secret.ts b/apps/web/lib/actions/generate-client-secret.tsindex 09ecae7831..9e01126442 100644--- a/apps/web/lib/actions/generate-client-secret.ts+++ b/apps/web/lib/actions/generate-client-secret.ts@@ -19,7 +19,7 @@ export const generateClientSecret = authActionClientconst { workspace } = ctx;const { appId } = parsedInput;- await prisma.oAuthApp.findFirstOrThrow({+ await prisma.integration.findFirstOrThrow({where: {id: appId,projectId: workspace.id,@@ -33,7 +33,7 @@ export const generateClientSecret = authActionClientawait prisma.oAuthApp.update({where: {- id: appId,+ integrationId: appId,},data: {hashedClientSecret: await hashToken(clientSecret),diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex ef945a5315..f22fc36fbe 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -2,6 +2,7 @@ import z from "@/lib/zod";import { metaTagsSchema } from "@/lib/zod/schemas/metatags";import { DirectorySyncProviders } from "@boxyhq/saml-jackson";import { Link, Project } from "@prisma/client";+import { integrationSchema } from "./zod/schemas/integration";import { createLinkBodySchema } from "./zod/schemas/links";import { oAuthAppSchema } from "./zod/schemas/oauth";import { tokenSchema } from "./zod/schemas/token";@@ -227,3 +228,5 @@ export type InstalledIntegrationInfoProps = Pick<};} | null;};++export type IntegrationProps = z.infer<typeof integrationSchema>;diff --git a/apps/web/lib/zod/schemas/integration.ts b/apps/web/lib/zod/schemas/integration.tsnew file mode 100644index 0000000000..817f88fc0c--- /dev/null+++ b/apps/web/lib/zod/schemas/integration.ts@@ -0,0 +1,17 @@+import { z } from "zod";++export const integrationSchema = z.object({+ id: z.string(),+ name: z.string(),+ slug: z.string(),+ description: z.string().nullish(),+ readme: z.string().nullish(),+ developer: z.string(),+ website: z.string(),+ logo: z.string().nullable(),+ screenshots: z.array(z.string()).nullable(),+ verified: z.boolean(),+ createdAt: z.date(),+ updatedAt: z.date(),+ installations: z.number().default(0),+});diff --git a/apps/web/lib/zod/schemas/oauth.ts b/apps/web/lib/zod/schemas/oauth.tsindex 7a50c2321d..04edc3d2ca 100644--- a/apps/web/lib/zod/schemas/oauth.ts+++ b/apps/web/lib/zod/schemas/oauth.ts@@ -1,6 +1,7 @@import { OAUTH_SCOPES } from "@/lib/api/oauth/constants";import { R2_URL } from "@dub/utils";import { z } from "zod";+import { integrationSchema } from "./integration";export const createOAuthAppSchema = z.object({name: z.string().min(1).max(100),@@ -67,25 +68,14 @@ export const createOAuthAppSchema = z.object({export const updateOAuthAppSchema = createOAuthAppSchema.partial();-export const oAuthAppSchema = z.object({- id: z.string(),- clientId: z.string(),- partialClientSecret: z.string(),- name: z.string(),- slug: z.string(),- description: z.string().nullish(),- readme: z.string().nullish(),- developer: z.string(),- website: z.string(),- redirectUris: z.array(z.string()),- logo: z.string().nullable(),- pkce: z.boolean(),- verified: z.boolean(),- createdAt: z.date(),- updatedAt: z.date(),- installations: z.number().default(0),- screenshots: z.array(z.string()).nullable(),-});+export const oAuthAppSchema = integrationSchema.merge(+ z.object({+ clientId: z.string(),+ partialClientSecret: z.string(),+ redirectUris: z.array(z.string()),+ pkce: z.boolean(),+ }),+);// Schema for OAuth2.0 Authorization requestexport const authorizeRequestSchema = z.object({diff --git a/apps/web/prisma/schema/oauth.prisma b/apps/web/prisma/schema/oauth.prismaindex 4dda45265c..ad83590109 100644--- a/apps/web/prisma/schema/oauth.prisma+++ b/apps/web/prisma/schema/oauth.prisma@@ -1,20 +1,20 @@model OAuthApp {// To be removed- name String- slug String @unique- description String?- readme String? @db.LongText- developer String- website String- logo String?- screenshots Json?- userId String?- projectId String- verified Boolean @default(false)- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt- user User? @relation(fields: [userId], references: [id], onDelete: SetNull)- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ // name String+ // slug String @unique+ // description String?+ // readme String? @db.LongText+ // developer String+ // website String+ // logo String?+ // screenshots Json?+ userId String?+ projectId String+ // verified Boolean @default(false)+ // createdAt DateTime @default(now())+ // updatedAt DateTime @updatedAt+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)id String @id @default(cuid())integrationId String? @unique // Maybe remove the optional mark after migration @unique