user12333470
user12333470

Reputation:

Firebase authentication does not authenticate when redirected

In my website, the defaults page is index.html. If the user is not connected then it redirects him to the login page. When the user has logged in, the program should redirect him back to index.html and show the page. However, when I login(and the credentials are correct), it redirects me again to login page.

Here's the code for index page:

var user = firebase.auth().currentUser;

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

Code for login page:

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")

    })
})

Thanks for your time :)

Upvotes: 1

Views: 437

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317402

firebase.auth().currentUser is not immediately populated with the current user when the page loads. You should instead attach an AuthStateListener to find out if and when the user object is available, as described in the documentation.

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

Upvotes: 1

Related Questions