@@ -11,7 +11,9 @@ import _ from 'underscore';
1111
1212import { normalizers , fromTemplate , renameInvalidProperties } from './transform_helpers' ;
1313import { isURL } from '../../../lib/utils/isURL' ;
14+ import { client } from '../../../server/database/utils' ;
1415import { callbacks } from '../../../server/lib/callbacks' ;
16+ import { saveUserIdentity } from '../../lib/server/functions/saveUserIdentity' ;
1517import { notifyOnUserChange } from '../../lib/server/lib/notifyListener' ;
1618import { registerAccessTokenService } from '../../lib/server/oauth/oauth' ;
1719import { settings } from '../../settings/server' ;
@@ -366,17 +368,55 @@ export class CustomOAuth {
366368 }
367369
368370 const serviceIdKey = `services.${ serviceName } .id` ;
369- const update = {
370- $set : {
371- name : serviceData . name ,
372- ...( this . keyField === 'username' && serviceData . email && { emails : [ { address : serviceData . email , verified : true } ] } ) ,
373- [ serviceIdKey ] : serviceData . id ,
371+ const successCallbacks = [
372+ async ( ) => {
373+ const updatedUser = await Users . findOneById ( user . _id , { projection : { name : 1 , emails : 1 , [ serviceIdKey ] : 1 } } ) ;
374+ if ( updatedUser ) {
375+ const { _id, ...diff } = updatedUser ;
376+ void notifyOnUserChange ( { clientAction : 'updated' , id : user . _id , diff } ) ;
377+ }
374378 } ,
375- } ;
379+ ] ;
380+
381+ const session = client . startSession ( ) ;
382+ try {
383+ // Extend the session to match the ExtendedSession type expected by saveUserIdentity
384+ Object . assign ( session , {
385+ onceSuccesfulCommit : ( cb ) => {
386+ successCallbacks . push ( cb ) ;
387+ } ,
388+ } ) ;
389+
390+ session . startTransaction ( ) ;
391+
392+ const updater = Users . getUpdater ( ) ;
376393
377- await Users . update ( { _id : user . _id } , update ) ;
394+ if ( this . keyField === 'username' && serviceData . email ) {
395+ updater . set ( 'emails' , [ { address : serviceData . email , verified : true } ] ) ;
396+ }
397+
398+ updater . set ( serviceIdKey , serviceData . id ) ;
399+
400+ await saveUserIdentity ( {
401+ _id : user . _id ,
402+ name : serviceData . name ,
403+ updater,
404+ session,
405+ updateUsernameInBackground : true ,
406+ // Username needs to be included otherwise the name won't be updated in some collections
407+ username : user . username ,
408+ } ) ;
409+ await Users . updateFromUpdater ( { _id : user . _id } , updater , { session } ) ;
410+
411+ await session . commitTransaction ( ) ;
412+ } catch ( e ) {
413+ await session . abortTransaction ( ) ;
414+ throw e ;
415+ } finally {
416+ await session . endSession ( ) ;
417+ }
378418
379- void notifyOnUserChange ( { clientAction : 'updated' , id : user . _id , diff : update } ) ;
419+ void Promise . allSettled ( successCallbacks . map ( ( cb ) => cb ( ) ) ) ;
380420 }
381421 } ) ;
382422
0 commit comments