Skip to content

Instantly share code, notes, and snippets.

@jozefhruska
Created September 6, 2021 07:35
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jozefhruska/daed673268cfb91956f2b2a060059cc6 to your computer and use it in GitHub Desktop.
Save jozefhruska/daed673268cfb91956f2b2a060059cc6 to your computer and use it in GitHub Desktop.
Auth0 Action - Account linking
/**
* Handler that will be called during the execution of a PostLogin flow.
*
* @param {Event} event - Details about the user and the context in which they are logging in.
* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
*/
exports.onExecutePostLogin = async (event, api) => {
const axios = require("axios");
const ManagementClient = require("auth0").ManagementClient;
const { CLIENT_ID, CLIENT_SECRET } = event.secrets;
// Get the Management API v2 token
const {
data: { access_token },
} = await axios
.post(
"https://DOMAIN/oauth/token",
{
grant_type: "client_credentials",
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
audience: "https://DOMAIN/api/v2/",
},
{
headers: { "content-type": "application/json" },
}
)
.catch((error) => {
console.log(error.request.data);
});
// Create an instance of the Management API client
const management = new ManagementClient({
token: access_token,
domain: "DOMAIN",
});
// Check if there already is an account with this email address
const users = await management.getUsersByEmail(event.user.email);
console.log('Users count:', users.length);
// If there isn't any account with this email address, return and let user continue
// There should never be more than 2 accounts with the same address, but just in case this happens somehow,
// we return here, so that a new account will be created for this user (better than to crash with error)
if (users.length !== 2) {
return;
}
// Link user accounts
const linkedUserIdentities = await management.users.link(users[1].user_id, {
user_id: users[0].user_id,
provider: users[0].identities[0].provider,
});
// Leave custom claim to let FE know
api.idToken.setCustomClaim("https://DOMAIN/account_linking_data", {
primary_user_id: users[1].user_id,
secondary_user_id: users[0].user_id,
});
// Return the linked account instead so user can continue without re-authentication
event.user = {
...users[1],
identities: linkedUserIdentities
};
return {
user: {
...users[1],
identities: linkedUserIdentities
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment