javascript - 如何根据我的实时数据库 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 天,这就是我在这里寻求帮助的原因。非常感谢您的评论和回答,谢谢!
解决方案
使用您当前的数据结构,您需要检查两个位置以确定用户的角色。虽然这在技术上是可行的,但它的效率较低且代码更复杂。
我建议改为存储一个顶级节点(例如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)
}
});
推荐阅读
- amazon-web-services - 为什么 Cloud9 询问我是否要显示所有 * 可能性(y 或 n)?
- vue.js - 提交表单后重新加载屏幕 - Vue.js
- superset - 无法在 Superset 上使用 Docker 安装加载 CSS
- php - 如何将php文件复制到csv文件并下载?
- node.js - Mac 上的 NPM 问题
- ffmpeg - ffmpeg 在过滤器中使用 setdar
- vb.net - 无法将 EmbedBuilder 类型的 Discord .NET 值转换为 Embed
- python - python中的流架构后端
- c# - Html.Partial 在 MVC 视图中导致 404
- java - .equals() 方法似乎不适合我