I have a login action that when it’s the first login, user is allowed do selected between a MFA factor picker. After the first login, user email is verified, so in the second login user will choose between email and the selected MFA in the first login.
How can i get this selected factor (between email and the other factor) to set in the user metadata as preferred MFA, so then in the third and subsequent logins user would be automatically challenged for this factor?
exports.onExecutePostLogin = async (event, api) => {
const lowerCaseConnectionName = event.connection?.name?.toLowerCase();
const isSSOLogin = (!lowerCaseConnectionName.includes('trayt-db'));
console.log(`Is SSO Login: ${isSSOLogin}`);
console.log(event.request.query)
if (isSSOLogin) {
// If the login is from 'trayt', do not prompt MFA.
console.log(`Login from ${event.connection?.name} connection. Skipping MFA.`);
return;
} else {
console.log('Teste', event.user.multifactor)
console.log('Teste2', event.user.enrolledFactors)
//first login
if (!event.user.multifactor?.length) {
console.log("User is not enrolled, email is not considered enrollment")
api.multifactor.enable('any', { allowRememberBrowser: false });
} else {
// second login onwards - already enrolled, challenge
console.log("Enrolled MFA length " + event.user.enrolledFactors.length)
if (event.user.user_metadata.mfaPreference) {
if (event.user.user_metadata.mfaPreference == 'otp') {
console.log('User has OTP as preference');
api.authentication.challengeWith({
type: 'otp',
});
} else if (event.user.user_metadata.mfaPreference == 'phone') {
console.log('User has Phone as preference');
api.authentication.challengeWith({
type: 'phone',
});
} else {
api.authentication.challengeWith({
type: 'email'
});
}
} else {
console.log("No Preference, presenting all options")
api.authentication.challengeWithAny([{
type: 'otp',
}, { type: 'email' }, { type: 'phone' }]);
}
}
}
};