Is it possible implimenting onAuthStateChanged() via a Axios request?

I am currently doing my final year project for college and it's using the FERN stack and Ionic to create an app that displays temperature information. The problem I am facing is when I refresh my browser it logs the user out.

Is it possible to implement a way to check if the user authentication status has changed via an Axios Request to onAuthStateChanged() or should I just import firebase admin so I can use the auth functions within the Ionic app itself?

I already use the Auth as middleware for the API requests for the temperatures so I would nearly be implementing the Auth module twice but if it makes it easier to use the onAuthStateChanged() function I don't mind implementing it that way. I also do the login functionality and registration functionality in the backend of the app.

As of current I log the user in and stores a token:

    const handleLogin = async () => {
        await axios.post('http://localhost:3000/login', {
            email: email,
            password: password
        }).then(res => {
            localStorage.setItem('Token', `Bearer ${res.data.token}`);
            console.log(res);
            onLogin();
        }).catch(err => {
            console.log(err);
        });
    }

This is my loginUser function which sends back the token:

exports.loginUser = (req, res) => {
    const user = {
        email: req.body.email,
        password: req.body.password
    }

    const { valid, errors } = validateLoginData(user);
    if (!valid) return res.status(400).json(errors);

    firebase
        .auth()
        .signInWithEmailAndPassword(user.email, user.password)
        .then((data) => {
            return data.user.getIdToken();
        })
        .then((token) => {
            return res.json({ token });
        })
        .catch((error) => {
            console.error(error);
            return res.status(403).json({ message: 'Invalid email or password.  Please try again'});
        })
};

What would be the best way to implement the onAuthStateChanged() function within my code? I saw in a tutorial that when they logged a user in it used the IndexedDB to store the authUser key and value. My code does not store this information just the token.

Answers 1

  • User authentication state is a mechanism defined and implemented by the Firebase SDKs. You're calling the REST API, which means that you're not using a Firebase SDK and thus there is no auth state change notification mechanism.

    You could implement your own mechanism of course, which would involve tracking when ID tokens expire, auto-renewing them just before that, registering listeners, notifying those listeners, and probably quite a few things that I'm overlooking right now.

    You'd be re-implementing a significant part of she Firebase SDK though. So at that point, consider why you aren't using the Firebase SDK to begin with.


Related Articles