@@ -59,6 +59,8 @@ export const createCallbackEndpoint = (
59
59
const useEmailAsIdentity = pluginOptions . useEmailAsIdentity ?? false ;
60
60
const excludeEmailFromJwtToken =
61
61
! useEmailAsIdentity || pluginOptions . excludeEmailFromJwtToken || false ;
62
+ const onUserNotFoundBehavior =
63
+ pluginOptions . onUserNotFoundBehavior || "create" ;
62
64
63
65
// /////////////////////////////////////
64
66
// beforeOperation - Collection
@@ -117,17 +119,27 @@ export const createCallbackEndpoint = (
117
119
118
120
let user = existingUser . docs [ 0 ] as User ;
119
121
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
+ }
131
143
} else {
132
144
// Update existing user with latest info from provider
133
145
userInfo . collection = authCollection ;
0 commit comments