Created
May 8, 2017 15:40
-
-
Save jacwright/b429088104a94c5d6e7ef47e9e37b39c to your computer and use it in GitHub Desktop.
Auth0: Link Accounts with Same Email Address while Merging Metadata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function (user, context, callback) { | |
var request = require('request@2.56.0'); | |
var async = require('async@2.1.2'); | |
// Check if email is verified, we shouldn't automatically | |
// merge accounts if this is not the case. | |
if (!user.email_verified) { | |
return callback(null, user, context); | |
} | |
var userApiUrl = auth0.baseUrl + '/users'; | |
user.app_metadata = user.app_metadata || {}; | |
user.user_metadata = user.user_metadata || {}; | |
request({ | |
url: userApiUrl, | |
headers: { | |
Authorization: 'Bearer ' + auth0.accessToken | |
}, | |
qs: { | |
search_engine: 'v2', | |
q: 'email.raw:"' + user.email + '" -user_id:"' + user.user_id + '"', | |
} | |
}, | |
function(err, response, body) { | |
if (err) return callback(err); | |
if (response.statusCode !== 200) return callback(new Error(body)); | |
var data = JSON.parse(body); | |
// Put the oldest last so it will overwrite the newest | |
data.sort(function(a, b) { | |
return b.date.localeCompare(a.date); | |
}); | |
var linkUsers = data.filter(function(targetUser) { | |
if (targetUser.email_verified) { | |
Object.assign(user.app_metadata, targetUser.app_metadata); | |
Object.assign(user.user_metadata, targetUser.user_metadata); | |
return true; | |
} | |
}); | |
if (!linkUsers.length) { | |
return callback(null, user, context); | |
} | |
// save metadata, the oldest should overwrite the newest | |
auth0.users.updateAppMetadata(user.user_id, user.app_metadata) | |
.then(auth0.users.updateUserMetadata(user.user_id, user.user_metadata)) | |
.then(function() { | |
async.each(linkUsers, function(targetUser, cb) { | |
var aryTmp = targetUser.user_id.split('|'); | |
var provider = aryTmp[0]; | |
var targetUserId = aryTmp[1]; | |
console.log('Joining:', { provider: provider, user_id: targetUserId }); | |
request.post({ | |
url: userApiUrl + '/' + user.user_id + '/identities', | |
headers: { | |
Authorization: 'Bearer ' + auth0.accessToken | |
}, | |
json: { provider: provider, user_id: targetUserId } | |
}, function(err, response, body) { | |
if (response.statusCode >= 400) { | |
cb(new Error('Error linking account: ' + response.statusMessage)); | |
} | |
if (!err) { | |
user.identities.push.apply(user.identities, targetUser.identities); | |
} | |
cb(err); | |
}); | |
}, function(err) { | |
callback(err, user, context); | |
}); | |
}).catch(function(err) { | |
callback(err, user, context); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment