在Firebase托管项目中,firebase.auth()。currentUser / firebase.auth()。onAuthStateChanged无法正常运行

时间:2019-09-11 13:55:11

标签: node.js firebase-authentication

相同的代码在简单节点JavaScript应用程序中可以正常工作,但是我使用Firebase CLI创建了另一个项目,在这里我使用相同的中间件功能来获取当前用户,并且它始终返回null。我都尝试过

  1. firebase.auth().currentUser

  2. firebase.auth().onAuthStateChanged返回null

相同的代码在Node + Firebase应用中运行正常

返回当前用户的中间件:

const admin = require('../config/config-firebase-admin');
const client = require('../config/config');

module.exports.isAuthenticated = function(req, res, next){

let currentUser = client.auth.currentUser;

if(currentUser !== null) {
    // lookup the user's role
    admin.auth.getUser(currentUser.uid).then((userRecord) => {
    //console.log(userRecord);
    if(userRecord.customClaims.admin === true){
        userRole = "admin";
    }
    if(userRecord.customClaims.editor === true){
        userRole = "editor";
    }
    if(userRecord.customClaims.subscriber === true){
        userRole = "subscriber";
    }
    let user = {
        email: currentUser.email,
        displayName: currentUser.displayName,
        userPhotoUrl: currentUser.photoURL,
        loginStatus: true,
        role: userRole
    };
    //console.log("Loggedin User: "+JSON.stringify(user));
    req.user = user;
    next();
    return null;
    });
}
else{
    let user = {
        email: "",
        displayName: "Guest",
        userPhotoUrl: "images/guest.jpg",
        loginStatus: false,
        role: ""
    };
    //console.log("Guest User: "+JSON.stringify(user));
    req.user = user;
    next();
    return null;
}
return null;
}

0 个答案:

没有答案