How to check if user is authenticated in Firebase and Express/Node.js?

六月ゝ 毕业季﹏ 提交于 2019-12-10 18:42:49

问题


If I have a page that can only be accessed by authenticated users, how do I check if a user is authenticated or not?

I tried using (firebase.auth().currentUser !== null) but I am getting an error saying: TypeError: firebase.auth is not a function

I have the following configuration:

const express = require('express'),
      firebase = require('firebase'),
      app = express();

app.use(express.static("/public"));

var config = {
   apiKey: "xxxx",
   authDomain: "xxxx",
   databaseURL: "xxxx",
   projectId: "xxxx",
   storageBucket: "xxxx",
   messagingSenderId: "xxxx"
};

firebase.initializeApp(config); 

app.get("/dashboard", (request, response) => {
   if (firebase.auth().currentUser !== null){
       response.render("dashboard.ejs")
   }
   else{
       response.render("login.ejs");
   }
});

回答1:


Your code is in an Express app, which means it runs on the server. The Firebase SDK you're using is meant for use on client devices, and won't work well in your Express environment. There is no concept of a "current user" on the server. Of course a user ID can be passed to the server with each request, but the server itself is stateless.

In your Express server you'll want to use the Firebase Admin SDK. Have a look at this Cloud Functions sample on how to build an authenticated endpoint.



来源:https://stackoverflow.com/questions/50643768/how-to-check-if-user-is-authenticated-in-firebase-and-express-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!