Skip to content

Instantly share code, notes, and snippets.

@mathiasconradt
Last active June 8, 2022 03:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathiasconradt/c7105065db96a5e5681c86e34d2cf727 to your computer and use it in GitHub Desktop.
Save mathiasconradt/c7105065db96a5e5681c86e34d2cf727 to your computer and use it in GitHub Desktop.
Auth0: Link Accounts with Same Email Address while Merging Metadata
function (user, context, callback) {
const request = require('request');
// 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);
}
const userApiUrl = auth0.baseUrl + '/users';
const userSearchApiUrl = auth0.baseUrl + '/users-by-email';
request({
url: userSearchApiUrl,
headers: {
Authorization: 'Bearer ' + auth0.accessToken
},
qs: {
email: user.email
}
},
function (err, response, body) {
if (err) return callback(err);
if (response.statusCode !== 200) return callback(new Error(body));
var data = JSON.parse(body);
// Ignore non-verified users and current user, if present
data = data.filter(function (u) {
return u.email_verified && (u.user_id !== user.user_id);
});
if (data.length > 1) {
return callback(new Error('[!] Rule: Multiple user profiles already exist - cannot select base profile to link with'));
}
if (data.length === 0) {
console.log('[-] Skipping link rule');
return callback(null, user, context);
}
const originalUser = data[0];
const provider = user.identities[0].provider;
const providerUserId = user.identities[0].user_id;
user.app_metadata = user.app_metadata || {};
user.user_metadata = user.user_metadata || {};
auth0.users.updateAppMetadata(originalUser.user_id, user.app_metadata)
.then(auth0.users.updateUserMetadata(originalUser.user_id, user.user_metadata))
.then(function() {
request.post({
url: userApiUrl + '/' + originalUser.user_id + '/identities',
headers: {
Authorization: 'Bearer ' + auth0.accessToken
},
json: { provider: provider, user_id: String(providerUserId) }
}, function (err, response, body) {
if (response && response.statusCode >= 400) {
return callback(new Error('Error linking account: ' + response.statusMessage));
}
context.primaryUser = originalUser.user_id;
callback(null, user, context);
});
})
.catch(function (err) {
callback(err);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment