@@ -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 ;
0 commit comments