Post-Login Action to Trigger MFA OTP or Email as Fallback

Problem statement

There is a business need for a Post-Login Action for new users to enroll in MFA OTP. Users are also implicitly enrolled in Email MFA once they verify their email address. Currently, the MFA OTP enrollment option is not being seen for users logging in for the first time, and returning users are only being prompted for Email MFA.

Are there any examples of how to write a Post-Login Action that would accommodate both OTP and Email MFA for the user base?

Solution

The following Action will check a user’s enrolled factors and prompt the user to enroll in enabled MFA factors if they have not enrolled already. Otherwise, users will be prompted with OTP and have the Email factor available as a fallback as well.

NOTE: This is not production-ready code and should always be heavily tested before using it in any production environment.

exports.onExecutePostLogin = async (event, api) => {
 
    const enrolledFactors = (event.user.enrolledFactors || []).filter(f => f.type !== 'email').map(f => ({ type: f.type }));

    if (enrolledFactors.length == 0) {
        api.multifactor.enable("any", {allowRememberBrowser: false});
    } else {
        api.authentication.challengeWith(
    {type:'otp'}, {additionalFactors:[{type:'email'}]});
    }

};