Firebase身份验证需要两个“登录”调用

时间:2019-03-20 23:18:45

标签: javascript html firebase firebase-realtime-database firebase-authentication

我正在尝试为Web应用程序对身份验证层进行硬编码,因此我可以查看用户是否为“管理员”。如果我没有在登录功能之前放置“ if语句”,则登录有效。但是,当我添加它时,它要求我按下登录按钮两次才能起作用。

登录功能:

function login() {
  var userEmail = document.getElementById("email_field").value;
  var userPass = document.getElementById("password_field").value;
  var login = [];
  var usersRef = firebase.database().ref("Parking Lots");
  usersRef.orderByChild("admin").on("value", function (snapshot) {
    snapshot.forEach(function (childSnapshot) {
      var childData = childSnapshot.val();
      login.push(childData.admin);
    });
  });
  firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
    .then(function () {
      if(login.includes(userEmail)){
       return firebase.auth().signInWithEmailAndPassword(userEmail, userPass);
      }
    })
    .catch(function (error) {
      window.alert("Fail");
      var errorCode = error.code;
      var errorMessage = error.message;
    });
}

HTML登录按钮:

我进行了一些研究,当您将按钮的类型设置为“ button”时,它对其他人还是有用的,但对我却不起作用。

<div id="login_div" class="main-div">
    <h3>Firebase Web login Example</h3>
    <input type="email" placeholder="Email..." id="email_field" />
    <input type="password" placeholder="Password..." id="password_field" />
    <button type="button" onclick="login()">Login to Account</button>
  </div>

编辑: 新的工作登录功能:

function login() {
  var userEmail = document.getElementById("email_field").value;
  var userPass = document.getElementById("password_field").value;
  var login = [];

  var usersRef = firebase.database().ref("Parking Lots");
  return usersRef.orderByChild("admin").once("value").then(function (snapshot) {
    snapshot.forEach(function (childSnapshot) {
      var childData = childSnapshot.val();
      login.push(childData.admin);
    });
    if(login.includes(userEmail)){
      firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
      .then(function () {
        return firebase.auth().signInWithEmailAndPassword(userEmail, userPass);
      })
      .catch(function (error) {
        window.alert("Password incorrect");
        var errorCode = error.code;
        var errorMessage = error.message;
      });
    }
    else {
      window.alert("Please enter another email");
    }
  });
}

2 个答案:

答案 0 :(得分:1)

on()是异步的,并在数据库发生任何事情之前立即返回。您传递给on()的回调的第一个响应很可能会在调用signInWithEmailAndPassword之后触发。您可能应该改用once(),并在尝试处理查询结果之前使用它返回的promise。另外,您应该使用once(),因为我强烈怀疑您不希望每次给定位置的数据更改时都继续调用该侦听器。

答案 1 :(得分:0)

在我的情况下,我忘记为提交登录表单的按钮添加 type 按钮属性..将其设置为 type="button" 后一切正常.. 花了 3 小时解决这个问题