如果用户通过Firebase登录,如何显示不同的页面

4

我有一个小问题,似乎很简单,但我无法想清楚该怎么做。

我有一个使用Firebase存储数据的express应用程序。我可以通过客户端脚本登录、注册和注销,但我的问题是:如何通过express检查用户是否已登录,以便能够向已登录的用户发送不同的页面?

这是我目前的代码:

var firebase = require('firebase');
// Initialize Firebase
var config = {
 serviceAccount: "./Chat Application-ad4eaaee3fcc.json",
 databaseURL: "MY_DATABASE_URL"
};
firebase.initializeApp(config);

然后我想为已登录的用户显示一个特殊页面,这是我尝试过的:

router.get("/special-page", function(req, res, next) {
    var user = firebase.auth().currentUser;
    console.log(user); // this variable gets undefined
    if(user) {
        res.render("special-page");
    } else {
        res.redirect("/");
  }
});

我知道这可能看起来是一个简单的问题,但任何帮助都将不胜感激!
提前致谢。
1个回答

6
用户端和服务器端是完全不同的执行区域。因此,正如您可能猜到的那样,在客户端进行身份验证后,在服务器上调用 firebase.auth().currentUser 是无法生效的。
服务器进程没有这些信息,除非客户端告诉它。
您可以有一个请求头,告诉“我已登录为XXX”,但这并不安全,因为服务器无法验证该信息,恶意用户可以假装成另一个用户。
在您的用例中,唯一的解决方案是向服务器提供Firebase令牌,然后服务器需要对该令牌进行验证,才能100%确定客户端身份验证。
我在我的React应用程序中需要这个功能来进行服务器端渲染,以下是我的实现方式:
  • 在用户认证时,设置包含Firebase令牌的cookie。
  • 用户注销时取消该cookie。
  • 在服务器端,读取cookie以在每个请求中验证客户端用户。
以下是客户端代码:
const setAppCookie = () => firebase.auth().currentUser &&
    firebase.auth().currentUser.getToken().then(token => {
        cookies.set('token', token, {
            domain: window.location.hostname,
            expire: 1 / 24, // One hour
            path: '/',
            secure: true // If served over HTTPS
        });
    });

const unsetAppCookie = () => 
    cookies.remove('token', {
        domain: window.location.hostname,
        path: '/',
    });

// triggered by firebase auth changes, this is where you deal
// with your users authentication in your app
fbAuth.onAuthStateChanged(user => {
    if (!user) {
        // user is logged out
        return;
    } 
    // user is logged in
    setAppCookie();
    // Reset cookie before hour expires 
    // (firebase tokens are short lived, say the docs)
    setInterval(setAppCookie, 3500);
});

[...]

// In the logout code
unsetAppCookie();

服务器端的代码:

// Before serving express app, enable cookie parsing
app.use(cookieParser());

// In the code dealing with your requests
const { token } = req.cookies;

if (!token) {
    // renderWithoutUser();
}

//
// If user found in cookie, verify the token and render with logged in store
//
console.log('Verifying token', token);
firebase.auth().verifyIdToken(token)
    .then(decodedToken => {
        const uid = decodedToken.sub;
        console.log('User is authenticated for this request', uid);
        // renderWithUser();
    })
    .catch(err => {
        console.error('WARNING token invalid or user not found', err);
        // renderWithoutUser();
    });

你好!我正在尝试实现你的解决方案,但遇到了一个问题:https://dev59.com/5lgR5IYBdhLWcg3wGaOb 你能否帮忙看一下呢?^^ - Coder1000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接