The Firebase Auth Multifactor feature does not include the multiFactor property in the user object

Looking to implement Multi-Factor Authentication (MFA) in my web app, but encountering an issue where the multiFactor property is missing in the code snippet below:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.2/firebase-app.js";
import { getAuth, RecaptchaVerifier, PhoneAuthProvider, signInWithEmailAndPassword } 
    from "https://www.gstatic.com/firebasejs/9.6.2/firebase-auth.js";

const firebaseConfig = {
    ...
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

auth.onAuthStateChanged((user) => {
    const userEl = document.getElementById('user');
    if (user) {
            userEl.innerHTML = `${user.email} logged in. ${JSON.stringify(
            user.multiFactor.enrolledFactors
        )}`;
    } else {
        userEl.innerHTML = 'signed out';
    }
});

window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {
    'size': 'invisible',
    'callback': (response) => {
        console.log('captcha solved!');
    }
}, auth);

const enrollBtn = document.getElementById('enroll-button');

enrollBtn.onclick = () => {
    signInWithEmailAndPassword(auth, '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98faf4f9faf4f9d8fff5f9f1f4b6fbf7f5">[email protected]</a>', 'foobar').then(() => {
        const user = auth.currentUser;
        if (!user) {
            return alert('User not logged!');
        }

        const phoneNumber = document.getElementById('enroll-phone').value;

        console.log(user);

        user.multiFactor.getSession().then((session) => {
            const phoneOpts = {
                phoneNumber,
                session,
            };

            const phoneAuthProvider = new PhoneAuthProvider();

            phoneAuthProvider.verifyPhoneNumber(
                phoneOpts,
                window.recaptchaVerifier
            ).then((verificationId) => {
                window.verificationId = verificationId;
                alert('sms text sent!');
            });
        });
    });
};

The error states that user.multiFactor is undefined, causing the code to fail at the getSession method resulting in the console error: "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getSession')".

It's worth noting that MFA is enabled in the Firebase project as shown in the screenshot below:

enter image description here

**************** UPDATE *******************

A possible solution is to update the code snippet as follows:

const mfaUser = multiFactor(user);    
mfaUser.getSession().then((session) => {

However, implementing this change results in a new error when calling verifyPhoneNumber:

VM21778 index.html:315 TypeError: Cannot read properties of undefined (reading 'tenantId')
    at _addTidIfNecessary (firebase-auth.js:1934:14)
    at startEnrollPhoneMfa (firebase-auth.js:6778:125)
    at _verifyPhoneNumber (firebase-auth.js:8500:40)

It's important to note that Multi-Tenancy is disabled in the project, raising questions about the cause of the 'tenantId' error.

Answer №1

Modified to:

let multiFactorAuthUser = multiFactor(user);    
multiFactorAuthUser.getSession().then((session) => {

as well as:

let phoneAuthenticationProvider = new PhoneAuthProvider(auth);

Uncertain whether Firebase Authentication documentation is outdated or if I'm approaching it differently. XD

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to showcase JSON data on a webpage?

Currently, I have a total of 3 different objects containing education details in my JSON data. While I am able to display them in the console using a for loop, I am only able to show one object in my HTML output. How can I push all three details to my HTML ...

Express.js automatically sets timeouts for requests to static files

I've been facing this issue for several weeks now - after launching, Express functions properly for a few hours and then suddenly stops serving static files. The situation is as follows: GET / 304 153ms GET /js/bootstrap.min.js 200 120000ms GET /img/ ...

What is the best way to store user input in local storage using Vue.js?

Following the official Vue.js site, I have been trying to implement Framework 7. However, when using an input field, [object InputEvent] is displayed both when typing text and attempting to save it. Is there a way to store a name in local storage and have ...

Tips for refreshing jQuery to ensure it functions smoothly for subsequent tasks

I am facing an issue with running a second process under JQuery, as shown in the code snippet below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type=" ...

Losing $scope reference when incorporating a directive within the controller scope

I have a scenario in my code where I am using two directives. One directive is within the controller scope, while the other directive is not located in the html section. <div ng-show="isStore==true"> <packgroup-directive> ...

Retrieve the modal ID when the anchor tag is clicked in order to open the modal using PHP

I am facing an issue with opening a modal and passing the id value using JavaScript. The id value is shown in a hidden input field. <a href="#modal2" data-toggle="modal" data-id="<?php echo $CRow['id'];?>" id="<?php echo $CRow[& ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

When using the Infinite Scroll React component, only a single new set of objects is loaded as you scroll down, and the loading

My React component is designed to load 6 images at a time as the page is scrolled down, creating an infinite scroll effect similar to what YouTube and Reddit now use. Currently, when the page loads, it shows the initial 6 images correctly. However, as I c ...

Issues have been identified with the functionality of the Am charts v3 XY in conjunction with a

I'm currently working on a project with angularJS and utilizing the npm package amcharts3 "^3.21.15". I've encountered a minor issue regarding the logarithmic scale in my XY chart. Below is my chart without the logarithmic scale: View working ch ...

Utilize a button within a form to add additional variables to a URL that already contains variables from a separate form

I operate a website that features a search bar and checkboxes for adding variables to the URL: term = "test" variable1=1 url/search?term=test&variable1=1 After completing the initial search, I have additional forms on the left side of the page with m ...

Theme not being rendered properly following the generation of a dynamic component in Angular

I am currently working on an Angular 9 application and I have successfully implemented a print functionality by creating components dynamically. However, I have encountered an issue where the CSS properties defined in the print-report.component.scss file a ...

The AudioPlayerStatus module in Discord JS is a powerful tool for managing

Could you explain why this code snippet: client.player.once(AudioPlayerStatus.Idle, () => { console.log(client.playlist); next.run(message, args, client); client.playlist.shift(); return; }); is b ...

Issues arise when trying to use the Jquery append() method in conjunction with Angular

We are currently utilizing jquery version 1.9.1 and angular version 1.2.13 for our project. Our wysiwyg editor is functioning well, as we are able to save HTML into the database and load it back using the jquery append function successfully. However, we ar ...

Verify if a personalized angular directive is able to display or conceal an element

I have a custom directive that toggles the visibility of an element based on the value of another service. I attempted to write a test to verify if the directive functions as intended. Initially, I used the ":visible" selector in my test, but it consistent ...

Navigate to the top of the page using Vue Router when moving to a new

Currently, in my Vue application, whenever I click on a <router-link>, it directs me to the new page but at the same scroll position as the previous one. This happens because the link only replaces the component. I am curious to know if there is a s ...

Body Zoom Browser

My website features buttons for zooming in and out, labeled as A + and A-. I wanted to make sure that the entire body of the website could be magnified easily. That's why I came up with this code: <html> <body> <style> .cont ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...

Having trouble with Instafeed JS loading?

I am currently experimenting with instafeed.js, but I am encountering difficulties getting it to load on a basic bootstrap page. While everything else on my page loads successfully, this particular container remains empty without any Instagram code presen ...

Easily targeting elements and their descendants in jquery: What you need to know!

Within a div, there are nested divs that contain tables and other divs. How can I use jquery to select both the parent div and its children? The parent div has the class "AccordionTitle AccordionTitle-selected". I have attempted the following: var klo=$( ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...