Always maintain original user id. No longer remove old user during sync

This commit is contained in:
Rory Powell 2021-07-08 16:49:07 +01:00
parent 8bea18e696
commit 87f05e7d06
1 changed files with 16 additions and 32 deletions

View File

@ -66,19 +66,19 @@ exports.authenticateThirdParty = async function (
} }
} }
let user
// first time creation // first time creation
if (!dbUser) { if (!dbUser) {
user = constructNewUser(userId, thirdPartyUser) // setup a blank user using the third party id
} else { dbUser = {
// existing user _id: userId,
user = constructMergedUser(userId, dbUser, thirdPartyUser) roles: {},
await db.remove(dbUser._id, dbUser._rev) }
} }
dbUser = syncUser(dbUser, thirdPartyUser)
// create or sync the user // create or sync the user
const response = await db.post(user) const response = await db.post(dbUser)
dbUser = user
dbUser._rev = response.rev dbUser._rev = response.rev
// authenticate // authenticate
@ -96,31 +96,15 @@ exports.authenticateThirdParty = async function (
} }
/** /**
* @returns a user object constructed from existing and third party information * @returns a user that has been sync'd with third party information
*/ */
function constructMergedUser(userId, existing, thirdPartyUser) { function syncUser(user, thirdPartyUser) {
// sync third party fields // provider
const user = constructNewUser(userId, thirdPartyUser) user.provider = thirdPartyUser.provider
user.providerType = thirdPartyUser.providerType
// merge existing fields // email
user.roles = existing.roles user.email = thirdPartyUser.email
user.builder = existing.builder
user.admin = existing.admin
return user
}
/**
* @returns a user object constructed from third party information
*/
function constructNewUser(userId, thirdPartyUser) {
const user = {
_id: userId,
provider: thirdPartyUser.provider,
providerType: thirdPartyUser.providerType,
email: thirdPartyUser.email,
roles: {},
}
if (thirdPartyUser.profile) { if (thirdPartyUser.profile) {
const profile = thirdPartyUser.profile const profile = thirdPartyUser.profile
@ -146,7 +130,7 @@ function constructNewUser(userId, thirdPartyUser) {
} }
} }
// persist oauth tokens for future use // oauth tokens for future use
if (thirdPartyUser.oauth2) { if (thirdPartyUser.oauth2) {
user.oauth2 = { user.oauth2 = {
...thirdPartyUser.oauth2, ...thirdPartyUser.oauth2,