Когда вы вызываете метод signInWithEmailAndPassword()
и он успешен, пользователь входит в систему. Поэтому, если я правильно понимаю ваше функциональное требование, вам не нужно использовать onAuthStateChanged()
.
Вы можете сделать что-то вроде этого:
function login() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().signInWithEmailAndPassword(email, password)
.then(userCredential => {
console.log("User " + userCredential.user.uid + " LOGGED IN");
window.location = 'admin-console.html';
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
//Throw an error
});
}
function logout() {
firebase.auth().signOut()
.then(() => {
console.log("User SIGNED OUT");
window.location = 'index.html';';
})
}
function initApp() {
console.log('start initApp');
document.getElementById('loginbutton').addEventListener('click', login, false);
document.getElementById('logoutbutton').addEventListener('click', logout, false);
}
window.onload = function () {
console.log('initialize app');
initApp();
};
Обратите внимание, что вам нужно добавить кнопку logoutbutton
. Если вы хотите иметь только одну кнопку переключения (а не одну кнопку loginbutton
плюс одну кнопку logoutbutton
), вы можете легко адаптировать приведенный выше код.