Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase detect user login from node.js backend

I am using node.js as a backend for my web app. In the server, I have

  res.sendFile(path.join(__dirname, "../public/html/main/profile.html"));
});

But I only want to send the file is the user is logged in. I am trying to figure out how to detect that with Firebase in node.js. I tried to initialize the app in node.js by doing

var firebase = require("firebase");
var config = {
  apiKey: "<API_KEY>",
  authDomain: "<PROJECT_ID>.firebaseapp.com",
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
  storageBucket: "<BUCKET>.appspot.com",
};
firebase.initializeApp(config);

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {}
})

But even I have an user signed in in the front-end, it seems like the "user" variable is false from the backend. How do I detect if an user is logged or not from node.js backend?

Thanks in advance.

like image 937
Chen Avatar asked Jul 21 '26 19:07

Chen


1 Answers

You have to pass the ID token to your server. On the client, you would get the ID token.

firebase.auth().currentUser.getIdToken()
  .then(function(idToken) {
    // You need to send the ID token to your server.
  })
  .catch(function(error) {
    // Error occurred.
  });

On the backend you pass it and verify the ID token with the Firebase Admin SDK:

// idToken comes from the client app
admin.auth().verifyIdToken(idToken)
  .then(function(decodedToken) {
    var uid = decodedToken.uid;
    // ...
    // You can return the file now.
  }).catch(function(error) {
    // Handle error
  });
like image 62
bojeil Avatar answered Jul 23 '26 11:07

bojeil