如果用户通过 firebase 登录,如何显示不同的页面 [英] How to show different page if user is logged in via firebase

查看:23
本文介绍了如果用户通过 firebase 登录,如何显示不同的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,这似乎很容易,但我似乎无法思考该怎么做.

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

这是我目前的代码:

var firebase = require('firebase');//初始化 Firebase变量配置 = {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;控制台日志(用户);//这个变量未定义如果(用户){res.render("特殊页面");} 别的 {res.redirect("/");}});

我知道这似乎是一个简单的问题,但任何帮助将不胜感激!

提前致谢.

解决方案

用户端和服务器端是完全不同的执行区域.因此,正如您可能猜到的,如果身份验证发生在客户端,则在服务器上调用 firebase.auth().currentUser 将无法工作.

服务器进程没有这个信息,除非客户端告诉他.

你可以有一个请求标头告诉我登录为 XXX",但它不安全,因为服务器将无法验证该信息,并且恶意用户可以假装是另一个用户.

在您的用例中,唯一的解决方案是向服务器提供 Firebase 令牌,然后服务器需要针对 Firebase 服务器验证此令牌,只有这样才能 100% 确定客户端身份验证.

我需要在我的 React 应用程序中使用它来进行服务器端渲染,我是这样做的.

  • 在用户身份验证后,设置一个包含 firebase 令牌的 cookie
  • 在用户注销时取消设置 cookie
  • 在服务器中,读取 cookie 以在每次请求时对客户端用户进行身份验证

客户端代码:

const setAppCookie = () =>firebase.auth().currentUser &&firebase.auth().currentUser.getToken().then(token => {cookies.set('token', token, {域:window.location.hostname,expire: 1/24,//一小时小路: '/',安全:真//如果通过 HTTPS 提供服务});});const unsetAppCookie = () =>cookies.remove('token', {域:window.location.hostname,小路: '/',});//由 firebase auth 更改触发,这是您处理的地方//在您的应用程序中使用您的用户身份验证fbAuth.onAuthStateChanged(用户 => {如果(!用户){//用户已注销返回;}//用户已登录setAppCookie();//在小时到期前重置 cookie//(firebase 令牌是短暂的,比如文档)setInterval(setAppCookie, 3500);});[...]//在注销代码中unsetAppCookie();

服务器中的代码:

//服务express app前,开启cookie解析app.use(cookieParser());//在处理您的请求的代码中const { token } = req.cookies;如果(!令牌){//renderWithoutUser();}////如果用户在 cookie 中找到,验证令牌并使用登录的商店呈现//console.log('验证令牌', 令牌);firebase.auth().verifyIdToken(token).then(decodedToken => {const uid = decodedToken.sub;console.log('用户已针对此请求进行身份验证', uid);//renderWithUser();}).catch(错误 => {console.error('WARNING token invalid or user not found', err);//renderWithoutUser();});

I have a slight problem, and it seems to be an easy one, but I cannot seem to wrap my head around what to do.

I have an express app, that uses Firebase to store data. I am able to login, register and log out trough a client side script, but my problem is: How do I check via express if a user is logged in, to be able to send a different page to the logged in users?

This is my code so far:

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

and then I want to show a special page for logged in users, and this is what I have tried:

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("/");
  }
});

I know this might seem like an easy question, but any help would be much appreciated!

Thanks in advance.

解决方案

The user side, and server side, are completely different execution areas. Hence, as you probably guessed, calling firebase.auth().currentUser on the server cannot work if the authentication occurred on the client.

The server process just does not have this information, unless the client tells him.

You could just have a request header telling "i am logged as XXX", but it would not be secure, because the server would not be able to verify that information, and a malicious user could pretend to be another one.

The only solution to this, in your use case, is to provide the Firebase token to the server, and then the server needs to verify this token against firebase server, and only then it will be 100% sure about the client authentication.

I needed that in my React app for Server Side Rendering, here is how I did it.

  • Upon user authentication, set a cookie that contains the firebase token
  • Unset the cookie when the users logs out
  • In the server, read the cookie to authenticate client user at each request

Code in the client :

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();

Code in the server:

// 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();
    });

这篇关于如果用户通过 firebase 登录,如何显示不同的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆