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.

Refactor HubSpot OAuth integration by introducing a new OAuthProvider class

Kiran Kfa4ba5efb80e
diff --git a/apps/web/app/(ee)/api/hubspot/callback/route.ts b/apps/web/app/(ee)/api/hubspot/callback/route.ts
index 0994081ee7..006ad10372 100644
--- a/apps/web/app/(ee)/api/hubspot/callback/route.ts
+++ b/apps/web/app/(ee)/api/hubspot/callback/route.ts
@@ -1,31 +1,16 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { getSession } from "@/lib/auth";
import { HubSpotApi } from "@/lib/integrations/hubspot/api";
-import {
- HUBSPOT_API_HOST,
- HUBSPOT_CLIENT_ID,
- HUBSPOT_CLIENT_SECRET,
- HUBSPOT_DUB_CONTACT_PROPERTIES,
- HUBSPOT_REDIRECT_URI,
- HUBSPOT_STATE_CACHE_PREFIX,
-} from "@/lib/integrations/hubspot/constants";
-import { hubSpotAuthTokenSchema } from "@/lib/integrations/hubspot/schema";
+import { HUBSPOT_DUB_CONTACT_PROPERTIES } from "@/lib/integrations/hubspot/constants";
+import { hubSpotOAuthProvider } from "@/lib/integrations/hubspot/oauth";
import { installIntegration } from "@/lib/integrations/install";
import { WorkspaceProps } from "@/lib/types";
-import { redis } from "@/lib/upstash";
-import z from "@/lib/zod";
import { prisma } from "@dub/prisma";
-import { getSearchParams } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { redirect } from "next/navigation";
export const dynamic = "force-dynamic";
-const oAuthCallbackSchema = z.object({
- code: z.string(),
- state: z.string(),
-});
-
// GET /api/hubspot/callback - OAuth callback from HubSpot
export const GET = async (req: Request) => {
const { searchParams } = new URL(req.url);
@@ -42,13 +27,6 @@ export const GET = async (req: Request) => {
}
try {
- if (!HUBSPOT_CLIENT_ID || !HUBSPOT_CLIENT_SECRET) {
- throw new DubApiError({
- code: "internal_server_error",
- message: "Missing HubSpot OAuth credentials (client id/secret).",
- });
- }
-
const session = await getSession();
if (!session?.user.id) {
@@ -58,19 +36,8 @@ export const GET = async (req: Request) => {
});
}
- const { code, state } = oAuthCallbackSchema.parse(getSearchParams(req.url));
-
- const stateKey = `${HUBSPOT_STATE_CACHE_PREFIX}:${state}`;
-
- // Find workspace that initiated the install
- const workspaceId = await redis.getdel<string>(stateKey);
-
- if (!workspaceId) {
- throw new DubApiError({
- code: "bad_request",
- message: "Unknown state. Please try again.",
- });
- }
+ const { token, contextId: workspaceId } =
+ await hubSpotOAuthProvider.exchangeCodeForToken(req);
workspace = await prisma.project.findUniqueOrThrow({
where: {
@@ -107,48 +74,17 @@ export const GET = async (req: Request) => {
});
}
- const body = new URLSearchParams({
- code,
- grant_type: "authorization_code",
- redirect_uri: HUBSPOT_REDIRECT_URI,
- client_id: HUBSPOT_CLIENT_ID,
- client_secret: HUBSPOT_CLIENT_SECRET,
- });
-
- // Exchange authorization code for access token
- const response = await fetch(`${HUBSPOT_API_HOST}/oauth/v1/token`, {
- method: "POST",
- headers: {
- "Content-Type": "application/x-www-form-urlencoded",
- },
- body,
- });
-
- const result = await response.json();
-
- if (!response.ok) {
- console.error(result);
-
- throw new DubApiError({
- code: "bad_request",
- message:
- "[HubSpot] Failed to exchange authorization code for access token",
- });
- }
-
- // Find the integration
const integration = await prisma.integration.findUniqueOrThrow({
where: {
slug: "hubspot",
},
});
- const credentials = hubSpotAuthTokenSchema.parse({
- ...result,
+ const credentials = {
+ ...token,
created_at: Date.now(),
- });
+ };
- // Install the integration
const installedIntegration = await installIntegration({
integrationId: integration.id,
userId: session.user.id,
@@ -156,20 +92,18 @@ export const GET = async (req: Request) => {
credentials,
});
- waitUntil(
- (async () => {
- if (installedIntegration) {
- const hubSpotApi = new HubSpotApi({
- token: credentials.access_token,
- });
+ if (installedIntegration) {
+ const hubSpotApi = new HubSpotApi({
+ token: credentials.access_token,
+ });
- await hubSpotApi.createPropertiesBatch({
- objectType: "0-1",
- properties: HUBSPOT_DUB_CONTACT_PROPERTIES,
- });
- }
- })(),
- );
+ waitUntil(
+ hubSpotApi.createPropertiesBatch({
+ objectType: "0-1",
+ properties: HUBSPOT_DUB_CONTACT_PROPERTIES,
+ }),
+ );
+ }
} catch (e: any) {
return handleAndReturnErrorResponse(e);
}
diff --git a/apps/web/lib/actions/get-integration-install-url.ts b/apps/web/lib/actions/get-integration-install-url.ts
index c4b9f3f3ea..539c8003f6 100644
--- a/apps/web/lib/actions/get-integration-install-url.ts
+++ b/apps/web/lib/actions/get-integration-install-url.ts
@@ -1,6 +1,6 @@
"use server";
-import { getHubSpotInstallationUrl } from "../integrations/hubspot/install";
+import { hubSpotOAuthProvider } from "../integrations/hubspot/oauth";
import { getSlackInstallationUrl } from "../integrations/slack/install";
import z from "../zod";
import { authActionClient } from "./safe-action";
@@ -22,7 +22,7 @@ export const getIntegrationInstallUrl = authActionClient
if (integrationSlug === "slack") {
url = await getSlackInstallationUrl(workspace.id);
} else if (integrationSlug === "hubspot") {
- url = await getHubSpotInstallationUrl(workspace.id);
+ url = await hubSpotOAuthProvider.generateAuthUrl(workspace.id);
} else {
throw new Error("Invalid integration slug");
}
diff --git a/apps/web/lib/integrations/hubspot/constants.ts b/apps/web/lib/integrations/hubspot/constants.ts
index b9f5c8090d..6ef05f4d34 100644
--- a/apps/web/lib/integrations/hubspot/constants.ts
+++ b/apps/web/lib/integrations/hubspot/constants.ts
@@ -4,6 +4,10 @@ export const HUBSPOT_CLIENT_ID = process.env.HUBSPOT_CLIENT_ID || "";
export const HUBSPOT_CLIENT_SECRET = process.env.HUBSPOT_CLIENT_SECRET || "";
+export const HUBSPOT_AUTH_URL = "https://app.hubspot.com/oauth/authorize";
+
+export const HUBSPOT_TOKEN_URL = "https://api.hubapi.com/oauth/v1/token";
+
export const HUBSPOT_REDIRECT_URI =
process.env.HUBSPOT_REDIRECT_URI ||
`${APP_DOMAIN_WITH_NGROK}/api/hubspot/callback`;
@@ -51,3 +55,6 @@ export const HUBSPOT_DUB_CONTACT_PROPERTIES = [
groupName: "contactinformation",
},
];
+
+// TODO:
+// Check if we need all these constants to be exported
\ No newline at end of file
diff --git a/apps/web/lib/integrations/hubspot/install.ts b/apps/web/lib/integrations/hubspot/install.ts
deleted file mode 100644
index 5be0418f2e..0000000000
--- a/apps/web/lib/integrations/hubspot/install.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { redis } from "@/lib/upstash";
-import { nanoid } from "@dub/utils";
-import {
- HUBSPOT_APP_SCOPES,
- HUBSPOT_CLIENT_ID,
- HUBSPOT_REDIRECT_URI,
- HUBSPOT_STATE_CACHE_PREFIX,
-} from "./constants";
-
-// Get the installation URL for HubSpot
-export const getHubSpotInstallationUrl = async (workspaceId: string) => {
- const state = nanoid(16);
-
- const params = new URLSearchParams({
- client_id: HUBSPOT_CLIENT_ID,
- scope: HUBSPOT_APP_SCOPES.join(" "),
- redirect_uri: HUBSPOT_REDIRECT_URI,
- state,
- });
-
- await redis.set(`${HUBSPOT_STATE_CACHE_PREFIX}:${state}`, workspaceId, {
- ex: 30 * 60,
- });
-
- return `https://app.hubspot.com/oauth/authorize?${params.toString()}`;
-};
diff --git a/apps/web/lib/integrations/hubspot/oauth.ts b/apps/web/lib/integrations/hubspot/oauth.ts
new file mode 100644
index 0000000000..ec2dcf1e01
--- /dev/null
+++ b/apps/web/lib/integrations/hubspot/oauth.ts
@@ -0,0 +1,30 @@
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { z } from "zod";
+import { OAuthProvider } from "../oauth-provider";
+
+const hubSpotTokenSchema = z.object({
+ access_token: z.string(),
+ refresh_token: z.string(),
+ scopes: z.array(z.string()),
+ hub_id: z.number(),
+ expires_in: z.number().describe("Expires in seconds."),
+ created_at: z.number(),
+});
+
+export const hubSpotOAuthProvider = new OAuthProvider<typeof hubSpotTokenSchema>({
+ name: "HubSpot",
+ clientId: process.env.HUBSPOT_CLIENT_ID || "",
+ clientSecret: process.env.HUBSPOT_CLIENT_SECRET || "",
+ authUrl: "https://app.hubspot.com/oauth/authorize",
+ tokenUrl: "https://api.hubapi.com/oauth/v1/token",
+ redirectUri: `${APP_DOMAIN_WITH_NGROK}/api/hubspot/callback`,
+ redisStatePrefix: "hubspot:oauth:state",
+ scopes: [
+ "oauth",
+ "crm.objects.contacts.read",
+ "crm.objects.contacts.write",
+ "crm.objects.deals.read",
+ "crm.schemas.contacts.write",
+ ],
+ tokenSchema: hubSpotTokenSchema,
+});
diff --git a/apps/web/lib/integrations/hubspot/schema.ts b/apps/web/lib/integrations/hubspot/schema.ts
index 0c04d3dbfd..41a2980f8e 100644
--- a/apps/web/lib/integrations/hubspot/schema.ts
+++ b/apps/web/lib/integrations/hubspot/schema.ts
@@ -8,7 +8,7 @@ export const hubSpotAuthTokenSchema = z.object({
scopes: z.array(z.string()),
hub_id: z.number(),
expires_in: z.number().describe("Expires in seconds."),
- created_at: z.number(),
+ created_at: z.number().optional(),
});
// Integration settings
diff --git a/apps/web/lib/integrations/oauth-provider.ts b/apps/web/lib/integrations/oauth-provider.ts
new file mode 100644
index 0000000000..1c9e461bc3
--- /dev/null
+++ b/apps/web/lib/integrations/oauth-provider.ts
@@ -0,0 +1,95 @@
+import { getSearchParams, nanoid } from "@dub/utils";
+
+import { z } from "zod";
+import { redis } from "../upstash";
+
+export interface OAuthProviderConfig {
+ name: string;
+ clientId: string;
+ clientSecret: string;
+ authUrl: string;
+ tokenUrl: string;
+ redirectUri: string;
+ scopes: string[];
+ redisStatePrefix: string;
+ tokenSchema: z.ZodSchema;
+}
+
+const codeExchangeSchema = z.object({
+ code: z.string(),
+ state: z.string(),
+});
+
+export class OAuthProvider<T extends z.ZodSchema> {
+ constructor(private provider: OAuthProviderConfig) {}
+
+ async generateAuthUrl(contextId: string) {
+ const state = nanoid(16);
+ await redis.set(`${this.provider.redisStatePrefix}:${state}`, contextId, {
+ ex: 30 * 60,
+ });
+
+ const searchParams = new URLSearchParams({
+ client_id: this.provider.clientId,
+ redirect_uri: this.provider.redirectUri,
+ scope: this.provider.scopes.join(" "),
+ response_type: "code",
+ state,
+ });
+
+ return `${this.provider.authUrl}?${searchParams.toString()}`;
+ }
+
+ async exchangeCodeForToken(request: Request): Promise<{
+ contextId: string;
+ token: z.infer<T>;
+ }> {
+ const { code, state } = codeExchangeSchema.parse(
+ getSearchParams(request.url),
+ );
+
+ const stateKey = `${this.provider.redisStatePrefix}:${state}`;
+
+ const contextId = await redis.getdel<string>(stateKey);
+
+ if (!contextId) {
+ throw new Error(`[${this.provider.name}] Invalid or expired state.`);
+ }
+
+ const response = await fetch(this.provider.tokenUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams({
+ code,
+ client_id: this.provider.clientId,
+ client_secret: this.provider.clientSecret,
+ redirect_uri: this.provider.redirectUri,
+ grant_type: "authorization_code",
+ }),
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ console.error(`[${this.provider.name}] exchangeCodeForToken`, data);
+
+ throw new Error(
+ `[${this.provider.name}] Failed to exchange authorization code. Please try again.`,
+ );
+ }
+
+ const token = this.provider.tokenSchema.parse(data);
+
+ return {
+ token,
+ contextId,
+ };
+ }
+}
+
+// TODO:
+// HubSpot
+// Slack
+// PayPal