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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With