diff --git a/src/Core/Services/Implementations/OrganizationService.cs b/src/Core/Services/Implementations/OrganizationService.cs index 222e325394..b0a5a05d82 100644 --- a/src/Core/Services/Implementations/OrganizationService.cs +++ b/src/Core/Services/Implementations/OrganizationService.cs @@ -1184,10 +1184,28 @@ namespace Bit.Core.Services } } - // Add new users if(newUsers?.Any() ?? false) { - var existingUsersSet = new HashSet(existingExternalUsers.Select(u => u.ExternalId)); + // Marry existing users + var existingUsersEmailsDict = existingUsers + .Where(u => string.IsNullOrWhiteSpace(u.ExternalId)) + .ToDictionary(u => u.Email); + var newUsersEmailsDict = newUsers.ToDictionary(u => u.Email); + var usersToAttach = existingUsersEmailsDict.Keys.Intersect(newUsersEmailsDict.Keys).ToList(); + foreach(var user in usersToAttach) + { + var orgUserDetails = existingUsersEmailsDict[user]; + var orgUser = await _organizationUserRepository.GetByIdAsync(orgUserDetails.Id); + if(orgUser != null) + { + orgUser.ExternalId = newUsersEmailsDict[user].ExternalId; + await _organizationUserRepository.UpsertAsync(orgUser); + existingExternalUsersIdDict.Add(orgUser.ExternalId, orgUser.Id); + } + } + + // Add new users + var existingUsersSet = new HashSet(existingExternalUsersIdDict.Keys); var usersToAdd = newUsersSet.Except(existingUsersSet).ToList(); var seatsAvailable = int.MaxValue; @@ -1220,23 +1238,6 @@ namespace Bit.Core.Services } } } - - var existingUsersEmailsDict = existingUsers - .Where(u => string.IsNullOrWhiteSpace(u.ExternalId)) - .ToDictionary(u => u.Email); - var newUsersEmailsDict = newUsers.ToDictionary(u => u.Email); - var usersToAttach = existingUsersEmailsDict.Keys.Intersect(newUsersEmailsDict.Keys).ToList(); - foreach(var user in usersToAttach) - { - var orgUserDetails = existingUsersEmailsDict[user]; - var orgUser = await _organizationUserRepository.GetByIdAsync(orgUserDetails.Id); - if(orgUser != null) - { - orgUser.ExternalId = newUsersEmailsDict[user].ExternalId; - await _organizationUserRepository.UpsertAsync(orgUser); - existingExternalUsersIdDict.Add(orgUser.ExternalId, orgUser.Id); - } - } } // Groups