Checking if User is Logged in via Express.js and Firestore

Issue

I am trying to determine if a user is logged in via Express.js and Firestore. The idea is to have the login/create user form displayed on the url path, ‘/’. However, if the user is logged in, then the app will redirect the user to the user’s dashboard page. This would happen when the user logs in or creates an account.

When I run my code I get the error

TypeError: admin.auth(...).onAuthStateChanged is not a function

I’ve realized that the admin package doesn’t have onAuthStateChanged as that is something that only exists for the client-side. However, I was wondering how I would implement loading a different view depending on if the user is logged in or not from the server side? Is it even good for me to do this via the server-side or is there a better way for me to approach this?

const admin = require('firebase-admin')
...

app.get('/', (req, res) => {
    admin.auth().onAuthStateChanged(function(user) {

        // render user dashboard if user is logged in 
        if (user) {
            getRestaurant('KOBmyfQEu4urNGgBTuiJ').then(data => {
                let ambassadorPromise = getAmbassadorInfo('KOBmyfQEu4urNGgBTuiJ')
                let activityPromise = getActivityFeed('KOBmyfQEu4urNGgBTuiJ')
        
                var restaurantName = data['name']
                var totalScans = data['total_scans']
        
                Promise.all([ambassadorPromise, activityPromise]).then(values => {
                    ...
        
                    res.render('dashboard', {restaurantName, totalScans, ambassadorList, activityList})
                })
            })
        } 

        // render account creation/login page is user is not logged in
        else {
            res.render('auth')
        }
      });

})

Solution

onAuthStateChanged is a function in Firebase Client SDK. Usually you would get the ID Token using Client SDK and then pass it in your API request but here it seems you need to authenticate user before the page renders. In such case you should use session cookies. Once the the user logs in, make an API request to server, generate the cookie using createSessionCookie() method and set it.
You can then verify the cookie before rendering the page.

You can find most of the code to implement this and detailed information in the documentation.

Answered By – Dharmaraj

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published