首页 > 解决方案 > 在导航到新页面之前检查用户身份验证 ID 是否存在于 firebase 数据库中

问题描述

用户登录成功后,我想使用用户 UID 来验证用户是否选择了正确的学校,我已经能够完成这个任务,但问题是,我必须点击两次登录按钮才能采取行动影响。

var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
  var email = document.getElementById("email").value;
  var password = document.getElementById("password").value;
  var s = document.getElementById("school");
  var school = s.options[s.selectedIndex].value;
  e.preventDefault();

  if (school == null || school == "") {
    alert("Please select your school")
    return false;
  } else if (email == null || email == "") {
    alert('email can\'t be empty')
    return false;
  } else if (password == null || password == "") {
    alert("Password ca\'t be empty")
    return false;
  } else {
    toggleSignIn();
//After signing in, use the user auth id to check if the user exist in the selected school
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        ref = database.ref('/schools/')
        userId = firebase.auth().currentUser.uid;

        ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {

          if (snapshot.exists()) {
            document.location.href = "/Result"
          } else {
            alert("You have selected the wrong school")
          }

        });

      }
    });
  }


}

标签: javascriptfirebase-realtime-databasefirebase-authentication

解决方案


onAuthStateChanged在这样的点击处理程序中有一个监听器是非常不寻常的。你更有可能想要类似的东西:

    ...
  } else {
    toggleSignIn();
    ref = database.ref('/schools/')
    userId = firebase.auth().currentUser.uid;

    ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {

      if (snapshot.exists()) {
        document.location.href = "/Result"
      } else {
        alert("You have selected the wrong school")
      }
    });
  }

顺便说一句:如果您可以通过查询为用户查找学校,是否有任何具体原因为什么您不简单地在表单中为他们预先填充该值?


推荐阅读