Skip to content

Commit ab03bde

Browse files
authored
introduce onUserNotFoundBehavior (#43)
1 parent 4f672c1 commit ab03bde

File tree

2 files changed

+33
-11
lines changed

2 files changed

+33
-11
lines changed

src/callback-endpoint.ts

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ export const createCallbackEndpoint = (
5959
const useEmailAsIdentity = pluginOptions.useEmailAsIdentity ?? false;
6060
const excludeEmailFromJwtToken =
6161
!useEmailAsIdentity || pluginOptions.excludeEmailFromJwtToken || false;
62+
const onUserNotFoundBehavior =
63+
pluginOptions.onUserNotFoundBehavior || "create";
6264

6365
// /////////////////////////////////////
6466
// beforeOperation - Collection
@@ -117,17 +119,27 @@ export const createCallbackEndpoint = (
117119

118120
let user = existingUser.docs[0] as User;
119121
if (!user) {
120-
// Create new user if they don't exist
121-
// Generate secure random password for OAuth users
122-
userInfo.password = crypto.randomBytes(32).toString("hex");
123-
userInfo.collection = authCollection;
124-
const result = await req.payload.create({
125-
req,
126-
collection: authCollection,
127-
data: userInfo,
128-
showHiddenFields: true,
129-
});
130-
user = result as unknown as User;
122+
if (onUserNotFoundBehavior === "error") {
123+
throw new Error(
124+
`User not found: ${useEmailAsIdentity ? userInfo.email : userInfo[subFieldName]}`,
125+
);
126+
} else if (onUserNotFoundBehavior === "create") {
127+
// Create new user if they don't exist
128+
// Generate secure random password for OAuth users
129+
userInfo.password = crypto.randomBytes(32).toString("hex");
130+
userInfo.collection = authCollection;
131+
const result = await req.payload.create({
132+
req,
133+
collection: authCollection,
134+
data: userInfo,
135+
showHiddenFields: true,
136+
});
137+
user = result as unknown as User;
138+
} else {
139+
throw new Error(
140+
`Invalid onUserNotFoundBehavior: ${onUserNotFoundBehavior}`,
141+
);
142+
}
131143
} else {
132144
// Update existing user with latest info from provider
133145
userInfo.collection = authCollection;

src/types.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,16 @@ export interface PluginOptions {
113113
req: PayloadRequest,
114114
) => Promise<Record<string, unknown>>;
115115

116+
/**
117+
* Behavior when a user is not found in the database.
118+
* If set to "create", a new user will be created with the information
119+
* returned from the OAuth provider.
120+
* If set to "error", an error will be thrown and the user will not
121+
* be created.
122+
* @default "create"
123+
*/
124+
onUserNotFoundBehavior?: "create" | "error";
125+
116126
/**
117127
* Scope for the OAuth provider.
118128
* The following are scopes for popular OAuth providers:

0 commit comments

Comments
 (0)