首页 > 解决方案 > 如何根据我的实时数据库 Firebase 中的角色为用户和自由职业者分别登录

问题描述

您好,我正在使用 Firebase 实时数据库和使用 nodejs 或 javascript 进行身份验证的 Web 应用程序。

这是我的实时数据库,我想制作一个登录表单,如果用户 = 用户,他将进入用户索引,如果用户 = 自由职业者,他将进入自由职业者索引。

这是我正在调整或尝试的代码行,但它并没有妨碍我。

        <script>

            firebase.auth().onAuthStateChanged(function(user)
            {
                if(user)
                {
                    var userID = firebase.auth().currentUser.uid;

                    firebase.database().ref('Users/' + userID).once('value').then(function(snapshot)
                    {
                        if (snapshot.val())
                        {
                            window.location.href = "index.html";
                        }
                        else
                        {
                            window.location.href = "okay.html";
                        }
                    });

                }
            });

        </script>

希望我能在这里得到反馈或答案。我几乎已经尝试了 2 天,这就是我在这里寻求帮助的原因。非常感谢您的评论和回答,谢谢!

标签: javascriptfirebase-realtime-databasefirebase-authentication

解决方案


使用您当前的数据结构,您需要检查两个位置以确定用户的角色。虽然这在技术上是可行的,但它的效率较低且代码更复杂。

我建议改为存储一个顶级节点(例如UserRoles),您只需在其中保留每个 UID 的角色:

"UserRoles": {
  "uidOfUser1": "Freelancer",
  "uidOfUser2": "User"
}

有了它,你可以在你的onAuthStateChanged回调中加载它:

const ref = firebase.database.ref("UserRoles");
ref.child(user.uid).once("value").then((snapshot) => {
  if (snapshot.val() === "Freelancer") {
    window.location.href = "okay.html";
  }
  else if (snapshot.val() === "User") {
    window.location.href = "index.html";
  }
  else {
    alert("Can't determine role for user: "+user.uid)
  }
});

推荐阅读