From f14cdc0ca0d9ddab416883bffdb4e9dd34b28c69 Mon Sep 17 00:00:00 2001 From: WilsonLe Date: Wed, 7 May 2025 22:24:05 -0400 Subject: [PATCH] introduce onUserNotFoundBehavior --- src/callback-endpoint.ts | 34 +++++++++++++++++++++++----------- src/types.ts | 10 ++++++++++ 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/callback-endpoint.ts b/src/callback-endpoint.ts index 866de73..4451e27 100644 --- a/src/callback-endpoint.ts +++ b/src/callback-endpoint.ts @@ -59,6 +59,8 @@ export const createCallbackEndpoint = ( const useEmailAsIdentity = pluginOptions.useEmailAsIdentity ?? false; const excludeEmailFromJwtToken = !useEmailAsIdentity || pluginOptions.excludeEmailFromJwtToken || false; + const onUserNotFoundBehavior = + pluginOptions.onUserNotFoundBehavior || "create"; // ///////////////////////////////////// // beforeOperation - Collection @@ -117,17 +119,27 @@ export const createCallbackEndpoint = ( let user = existingUser.docs[0] as User; if (!user) { - // Create new user if they don't exist - // Generate secure random password for OAuth users - userInfo.password = crypto.randomBytes(32).toString("hex"); - userInfo.collection = authCollection; - const result = await req.payload.create({ - req, - collection: authCollection, - data: userInfo, - showHiddenFields: true, - }); - user = result as unknown as User; + if (onUserNotFoundBehavior === "error") { + throw new Error( + `User not found: ${useEmailAsIdentity ? userInfo.email : userInfo[subFieldName]}`, + ); + } else if (onUserNotFoundBehavior === "create") { + // Create new user if they don't exist + // Generate secure random password for OAuth users + userInfo.password = crypto.randomBytes(32).toString("hex"); + userInfo.collection = authCollection; + const result = await req.payload.create({ + req, + collection: authCollection, + data: userInfo, + showHiddenFields: true, + }); + user = result as unknown as User; + } else { + throw new Error( + `Invalid onUserNotFoundBehavior: ${onUserNotFoundBehavior}`, + ); + } } else { // Update existing user with latest info from provider userInfo.collection = authCollection; diff --git a/src/types.ts b/src/types.ts index 63af8ee..147284d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -113,6 +113,16 @@ export interface PluginOptions { req: PayloadRequest, ) => Promise>; + /** + * Behavior when a user is not found in the database. + * If set to "create", a new user will be created with the information + * returned from the OAuth provider. + * If set to "error", an error will be thrown and the user will not + * be created. + * @default "create" + */ + onUserNotFoundBehavior?: "create" | "error"; + /** * Scope for the OAuth provider. * The following are scopes for popular OAuth providers: