Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法读取属性';getIdToken';在firebase中实现会话cookie后返回null_Javascript_Node.js_Firebase_Firebase Realtime Database_Firebase Authentication - Fatal编程技术网

Javascript 无法读取属性';getIdToken';在firebase中实现会话cookie后返回null

Javascript 无法读取属性';getIdToken';在firebase中实现会话cookie后返回null,javascript,node.js,firebase,firebase-realtime-database,firebase-authentication,Javascript,Node.js,Firebase,Firebase Realtime Database,Firebase Authentication,我使用link在firebase项目上实现了cookie会话 我正在尝试在客户端获取idToken以将其发送到服务器端。 以下是我在客户端使用的代码: $(function(){ $.ajax({ url: "/checkSession", type: 'post', success: function(data) { if(data.status === "ok" &

我使用link在firebase项目上实现了cookie会话
我正在尝试在客户端获取
idToken
以将其发送到服务器端。
以下是我在客户端使用的代码:

$(function(){
    $.ajax({
        url: "/checkSession",
        type: 'post',
        success: function(data) {
            if(data.status === "ok" && data.user){
                const user = data.user;
                const emailVerified = user.email_verified;
                const uid = user.uid;

                if (emailVerified){
                    firebase.database().ref().child("users").child(uid).child("username").once("value", snapshot => {
                        const username = snapshot.val();
                        firebase.auth().currentUser.getIdToken(true).then(idToken => {
                        // Doesn't work...
                        })
                    }).catch(err => {
                        console.log(err)
                    });
                }
            }
        }
    }); 
});
下面是检查会话的服务器:

app.post("/checkSession", (req, res, next) => {
    const sessionCookie = req.cookies.session || '';
    admin
        .auth()
        .verifySessionCookie(sessionCookie, true)
        .then(user => {
            res.json({
                status: "ok",
                user
            })
        })
        .catch((error) => {
            res.json({
                status: "error",
            })
        });
})
除此函数外,所有功能都正常运行:
firebase.auth().currentUser.getIdToken(true).then(idToken=>{…})
并且它抛出了
无法读取null属性“getIdToken”的错误

更新:这是我正在使用的登录方法。我将false传递给
httpOnly
secure
,因为我正在本地测试它

app.post("/SignInUser", (req, res, next) => {
    const idToken = req.body.idToken.toString();
    const expiresIn = 60 * 60 * 24 * 10 * 1000; // 10 days

    admin
        .auth()
        .verifyIdToken(idToken)
        .then(function (decodedClaims) {
            if (new Date().getTime() / 1000 - decodedClaims.auth_time < 5 * 60) {
                return admin.auth().createSessionCookie(idToken, { expiresIn });
            }
        })
        .then(function (sessionCookie) {
            const options = { maxAge: expiresIn, httpOnly: false, secure: false};
            res.cookie("session", sessionCookie, options);
            return res.json({
                status: "ok"
            })
        })
        .catch(function (error) {
            return res.json({
                status: "error",
                message: "Unauthorized request!"
            })
        });
})

Firebase auth是异步的,您需要等待它完全初始化,然后才能尝试引用
currentUser
。有关如何执行此操作的更多信息,请参阅


要将其简化为更简单的术语,在调用任何引用
currentUser
的函数之前,您需要先聆听
onAuthStatusChanged()
并等待它返回
null
User
对象。我会给你具体的代码更改,但相关部分不在问题中。

你能检查“firebase.auth().currentUser”是否为空吗?@SergeyReus是的,它为空!即使浏览器中存在会话。Firebase auth不会触发,因为我没有使用Firebase的主要身份验证功能,我正在使用cookie会话。我更新了帖子,请检查,谢谢。我不确定您是否正确实现了Firebase auth。在客户端,如果尚未进行身份验证(
signInWith\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。您的错误是由于您未等待SDK初始化或用户未经过身份验证而导致的。如果您在我的另一个答案中遵循这个示例,在
onAuthStatusChanged()
给您一个最终的身份验证状态之前,您不会调用
/checkSession
,那么它将起作用,承诺!顺便说一句,这里唯一相关的代码是您的客户端代码。但是他们的官方文档没有使用
onAuthStatusChanged()
,是的,用户正在进行身份验证,我检查了。
function getUserSnapshotOrVerifyUserId(username, idToken, cb) {
    if (username == null || username.length == 0 || idToken == null || idToken.length == 0)
        return cb({
            status: "error",
            errorMessage: "Missing params."
        }, null);

    admin.auth().verifyIdToken(idToken).then(decodedToken => {
        let uid = decodedToken.uid;

        admin.database().ref().child("users").orderByChild("username").equalTo(username).once('value', snapshot => {
            if (!snapshot.exists())
                return cb({
                    status: "error",
                    message: "invalid-profile"
                });

            snapshot.forEach(child => {
                const id = child.val().id;
                if (id !== uid)
                    return cb({
                        status: "error",
                        message: "Invalid ID"
                    });

                admin.database().ref("users/" + id).once("value", snapshot => {
                    if (!snapshot.exists())
                        return cb({
                            status: "error",
                            errorMessage: "user not found."
                        });

                    return cb(null, id, snapshot);
                });
            });
        });
    }).catch(err => cb({
        status: "error",
        message: err
    }));
}

app.post("/getUserProfile", (req, res, next) => {
    const username = req.body.username || req.query.username;
    const idToken = req.body.idToken;

    getUserSnapshotOrVerifyUserId(username, idToken, (err, id, snapshot) => {
        if (err) return res.json(err);

        let userdata = {
            username: snapshot.val().username,
            name: snapshot.val().name,
        }

        res.json({
            status: "ok",
            userdata
        })
    })
})