Firebase身份验证在重定向时不进行身份验证

时间:2019-11-15 19:27:07

标签: javascript html firebase firebase-authentication

在我的网站中,默认页面是index.html。如果用户未连接,则将其重定向到登录页面。用户登录后,程序应将其重定向回index.html并显示页面。但是,当我登录(并且凭据正确)时,它将再次将我重定向到登录页面。

这是索引页的代码:

var user = firebase.auth().currentUser;

if (!user){
    window.location = 'https://anastasispap.me/auth/login.html';
}

登录页面代码:

const loginForm = document.querySelector('#login-form');

loginForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const email = loginForm['login-email'].value;
    const password = loginForm['login-password'].value;
    console.log(email, password)

    auth.signInWithEmailAndPassword(email, password).then(cred => {
        console.log(cred)
        loginForm.reset()
        window.location.assign("https://anastasispap.me/index.html")

    })
})

感谢您的时间:)

1 个答案:

答案 0 :(得分:2)

页面加载时,

firebase.auth().currentUser不会立即被当前用户填充。相反,您应该附加AuthStateListener来确定用户对象是否可用以及何时可用,如documentation中所述。

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});