The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
restructure oauth setup
Kiran Kc38038255572
diff --git a/apps/web/app/api/paypal/callback/route.ts b/apps/web/app/api/paypal/callback/route.tsindex efd22eba99..d430bbdd1a 100644--- a/apps/web/app/api/paypal/callback/route.ts+++ b/apps/web/app/api/paypal/callback/route.ts@@ -1,10 +1,6 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { getSession } from "@/lib/auth";-import {- exchangeCodeForToken,- getUserInfo,- verifyState,-} from "@/lib/paypal/oauth";+import { paypalOAuth } from "@/lib/paypal/oauth";import { prisma } from "@dub/prisma";import { getSearchParams } from "@dub/utils";import { redirect } from "next/navigation";@@ -39,7 +35,7 @@ export const GET = async (req: Request) => {const { code, state } = oAuthCallbackSchema.parse(getSearchParams(req.url));- const isStateValid = await verifyState({+ const isStateValid = await paypalOAuth.verifyState({state,dubUserId: session.user.id,});@@ -51,11 +47,11 @@ export const GET = async (req: Request) => {});}- const accessToken = await exchangeCodeForToken({+ const accessToken = await paypalOAuth.exchangeCodeForToken({code,});- const paypalUser = await getUserInfo({+ const paypalUser = await paypalOAuth.getUserInfo({token: accessToken,});diff --git a/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts b/apps/web/lib/actions/partners/generate-paypal-oauth-url.tsindex 4fcf4687a9..cd889d14ca 100644--- a/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts+++ b/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts@@ -1,6 +1,6 @@"use server";-import { getAuthorizationUrl } from "@/lib/paypal/oauth";+import { paypalOAuth } from "@/lib/paypal/oauth";import { CONNECT_SUPPORTED_COUNTRIES, COUNTRIES } from "@dub/utils";import { authPartnerActionClient } from "../safe-action";@@ -24,7 +24,7 @@ export const generatePaypalOAuthUrl = authPartnerActionClient.action();}- const url = await getAuthorizationUrl({+ const url = await paypalOAuth.getAuthorizationUrl({dubUserId: user.id,});diff --git a/apps/web/lib/paypal/oauth.ts b/apps/web/lib/paypal/oauth.tsindex 71db7387ff..8922a0ce90 100644--- a/apps/web/lib/paypal/oauth.ts+++ b/apps/web/lib/paypal/oauth.ts@@ -16,83 +16,89 @@ interface UserInfo {email_verified: boolean;}-const oauth2 = new AuthorizationCode({- client: {- id: paypalEnv.PAYPAL_CLIENT_ID,- secret: paypalEnv.PAYPAL_CLIENT_SECRET,- },- auth: {- tokenHost: paypalEnv.PAYPAL_API_HOST,- tokenPath: "/v1/oauth2/token",- authorizeHost: paypalEnv.PAYPAL_AUTHORIZE_HOST,- authorizePath: "/signin/authorize",- },- options: {- authorizationMethod: "header",- bodyFormat: "form",- },-});-const REDIRECT_URI = `${APP_DOMAIN_WITH_NGROK}/api/paypal/callback`;const STATE_CACHE_PREFIX = "paypal:oauth:state:";-export async function getAuthorizationUrl({- dubUserId,-}: {- dubUserId: string;-}): Promise<string> {- const state = uuidv4();+export class PayPalOAuth {+ private oauth2: AuthorizationCode;- await redis.set(`${STATE_CACHE_PREFIX}${state}`, dubUserId, {- ex: 60 * 2, // 2 minutes- });+ constructor() {+ this.oauth2 = new AuthorizationCode({+ client: {+ id: paypalEnv.PAYPAL_CLIENT_ID,+ secret: paypalEnv.PAYPAL_CLIENT_SECRET,+ },+ auth: {+ tokenHost: paypalEnv.PAYPAL_API_HOST,+ tokenPath: "/v1/oauth2/token",+ authorizeHost: paypalEnv.PAYPAL_AUTHORIZE_HOST,+ authorizePath: "/signin/authorize",+ },+ options: {+ authorizationMethod: "header",+ bodyFormat: "form",+ },+ });+ }- return oauth2.authorizeURL({- state,- scope: ["email"],- redirect_uri: REDIRECT_URI,- });-}+ async getAuthorizationUrl({+ dubUserId,+ }: {+ dubUserId: string;+ }): Promise<string> {+ const state = uuidv4();-export async function verifyState({- state,- dubUserId,-}: {- state: string;- dubUserId: string;-}) {- return (await redis.get(`${STATE_CACHE_PREFIX}${state}`)) === dubUserId;-}+ await redis.set(`${STATE_CACHE_PREFIX}${state}`, dubUserId, {+ ex: 60 * 2, // 2 minutes+ });-// Exchanges the authorization code for an access token-export async function exchangeCodeForToken({ code }: { code: string }) {- const accessToken: AccessToken = await oauth2.getToken({- code,- redirect_uri: REDIRECT_URI,- });+ return this.oauth2.authorizeURL({+ state,+ scope: ["email"],+ redirect_uri: REDIRECT_URI,+ });+ }- return accessToken.token.access_token;-}+ async verifyState({+ state,+ dubUserId,+ }: {+ state: string;+ dubUserId: string;+ }) {+ return (await redis.get(`${STATE_CACHE_PREFIX}${state}`)) === dubUserId;+ }-// Fetch the user info-export async function getUserInfo({ token }: { token: string }) {- const response = await fetch(- `${paypalEnv.PAYPAL_API_HOST}/v1/identity/openidconnect/userinfo?schema=openid`,- {- headers: {- Authorization: `Bearer ${token}`,- "Content-Type": "application/x-www-form-urlencoded",+ async exchangeCodeForToken({ code }: { code: string }) {+ const accessToken: AccessToken = await this.oauth2.getToken({+ code,+ redirect_uri: REDIRECT_URI,+ });++ return accessToken.token.access_token;+ }++ async getUserInfo({ token }: { token: string }) {+ const response = await fetch(+ `${paypalEnv.PAYPAL_API_HOST}/v1/identity/openidconnect/userinfo?schema=openid`,+ {+ headers: {+ Authorization: `Bearer ${token}`,+ "Content-Type": "application/x-www-form-urlencoded",+ },},- },- );+ );- const data = (await response.json()) as UserInfo;+ const data = (await response.json()) as UserInfo;- if (!response.ok) {- throw new Error("Failed to fetch user info from PayPal.", {- cause: data,- });- }+ if (!response.ok) {+ throw new Error("Failed to fetch user info from PayPal.", {+ cause: data,+ });+ }- return data;+ return data;+ }}++export const paypalOAuth = new PayPalOAuth();