Я пытаюсь жестко закодировать слой аутентификации для моего веб-приложения, чтобы я мог видеть, является ли пользователь «администратором» или нет. Вход в систему работает, если я не поставлю «оператор 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 type = "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>
Edit:
Новая рабочая функция входа в систему:
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");
}
});
}