Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/polar-betterauth/src/hooks/customer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,19 @@ export const onUserUpdate =
}
}
};

export const beforeUserCreate =
(options: PolarOptions) =>
async (user: User, ctx?: GenericEndpointContext) => {
if (ctx && options.skipUserOnExternalIDConflict) {
const { result: existingCustomers } = await options.client.customers.list(
{ email: user.email },
);
const existingCustomer = existingCustomers.items[0];
if (existingCustomer && existingCustomer.externalId !== user.id) {
throw new APIError("CONFLICT", {
message: `Customer with email ${user.email} already exists with a different external ID.`,
});
}
}
};
3 changes: 2 additions & 1 deletion packages/polar-betterauth/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { BetterAuthPlugin } from "better-auth";
import { onUserCreate, onUserUpdate } from "./hooks/customer";
import { beforeUserCreate, onUserCreate, onUserUpdate } from "./hooks/customer";
import type { PolarEndpoints, PolarOptions } from "./types";

export { polarClient } from "./client";
Expand Down Expand Up @@ -28,6 +28,7 @@ export const polar = <O extends PolarOptions>(options: O) => {
databaseHooks: {
user: {
create: {
before: beforeUserCreate(options),
after: onUserCreate(options),
},
update: {
Expand Down
8 changes: 8 additions & 0 deletions packages/polar-betterauth/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ export interface PolarOptions {
* Polar Client
*/
client: Polar;

/**
* Enable customer creation when a user signs up
*/
createCustomerOnSignUp?: boolean;

/**
* A custom function to get the customer create
* params
Expand All @@ -50,6 +52,12 @@ export interface PolarOptions {
) => Promise<{
metadata?: Record<string, string>;
}>;

/**
* Do not create a new user if polar customer exists with different externalId
*/
skipUserOnExternalIDConflict?: boolean;

/**
* Use Polar plugins
*/
Expand Down