如何使用firestore查询为javascript执行基于用户角色的登录
我正在尝试使用javascript和firestore作为后端函数创建登录。我的代码似乎没有执行查询,firebase提供的用户id也没有从云中提取出来。我当前的代码只是将任何用户重定向到patientDashboard.php,而不管他们的“职业” 这是我的密码如何使用firestore查询为javascript执行基于用户角色的登录,javascript,firebase,google-cloud-firestore,firebase-authentication,Javascript,Firebase,Google Cloud Firestore,Firebase Authentication,我正在尝试使用javascript和firestore作为后端函数创建登录。我的代码似乎没有执行查询,firebase提供的用户id也没有从云中提取出来。我当前的代码只是将任何用户重定向到patientDashboard.php,而不管他们的“职业” 这是我的密码 (function(){//initialize the firebase app var config = { }; firebase.initializeApp(config);
(function(){//initialize the firebase app
var config = {
};
firebase.initializeApp(config);
var auth = null;
var loginBtn= document.getElementById('btnLogin');
// var user = db.collection("users");
// var db = firebase.firestore();
firebase.auth.Auth.Persistence.SESSION;
//Login
loginBtn.addEventListener('click', async e => {
e.preventDefault();
if( $('#email').val() != '' && $('#password').val() != '' ){
//login the user
var data = {
email: $('#email').val(),
password: $('#password').val()
};
try{
const userCredential = await firebase.auth().signInWithEmailAndPassword(data.email, data.password);
let uid = userCredential.user.uid;
var documents = await firebase.firestore().collection("users").doc(uid);
documents.get().then(function(doc){
if(doc.data['occupation'] != 'Doctor'){
window.location.href = "patientDashboard.php";
}
else {
window.location.href = "doctorDashboard.php";
}
});
}
catch(err){
console.log("Login Failed!", err);
window.alert("Login Failed!", err);
}
}
});
})();
我想要完成的是一个基于用户职业的正确登录后端功能。但目前它只重定向到前面提到的页面。我怀疑罪魁祸首是我做的查询码 您不能执行文档数据['occulation']
您需要使用以下方法之一:
if(doc.data().occupation != 'Doctor') {...}
if(doc.get('occupation') != 'Doctor') {...}
或使用以下方法:
if(doc.data().occupation != 'Doctor') {...}
if(doc.get('occupation') != 'Doctor') {...}
编辑:
此外,代码中还有另一个错误。您混淆了异步/等待和then方法的使用。您应该如下调整代码
var document = await firebase.firestore().collection("users").doc(uid).get();
//document is a DocumentSnapshot, we can call the get() method
if (document.get('occupation') != 'Doctor'){
window.location.href = "patientDashboard.php";
}
else {
window.location.href = "doctorDashboard.php";
}
请注意,使用此代码并不是实现真正的基于角色的访问控制系统。您只是根据用户文档中的值重定向用户。有人可以很容易地对你的应用程序进行反向工程,并重定向到错误的页面
如果您想建立一个基于角色的访问控制系统,您可能会对这个演示如何处理自定义声明的系统感兴趣。免责声明,我是作者我已经尝试过你的建议,但不管职业如何,程序仍然会将用户登录到patientDashboard.php。documents.get.thenfunctiondoc{…}我感觉这里出现了错误。。。程序仍然会将用户登录到patientDashboard.php。您的确切意思是什么?它是否重定向到patientDashboard.php??基本上,我正在尝试登录一个医生帐户,但它仍然以患者身份登录,并重定向到patientDashboard.php。请注意,如果使用Email和Password登录的调用成功,则该用户以Firebase用户身份登录。这与职业的价值无关。但是现在我看到了你代码中的另一个错误。我将编辑我的答案。@setted注释,我忘记在编辑的第一行末尾添加get!