Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Auth - User not logged in after Firebase sign up and redirect

I am creating an account for a user with firebase. After the account is created, I redirect to the home page, which checks if I am logged in. Oddly enough, I am not logged in.

On Create Account Page:

createAccount() {
  firebaseAuth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((user) => {
    // write some data to database
    firebase.database().ref().child('users').child(user.uid).child('someKey').set(this.state.email).then(function() {
      // send email verification
      user.sendEmailVerification().then(function() {
        console.log("sent email verification");
        // Go to home page
        this.props.history.push('/home');
      }.bind(this)).catch(function(error) {
        console.log("Error: account created but no verification email sent.");
      }.bind(this));
    }.bind(this)).catch((error) => {
      console.log('Error: while writing to database');
    });
  // catch any error while creating user
  }).catch((error) => {
    console.log('Error: while creating account');
  });
}

On Home Page:

componentDidMount() {
  firebase.auth().onAuthStateChanged(function (user) {
    if (!user) {
      console.log("no user logged in");  
      this.props.history.replace('/login'); // ISSUE: Always redirected to login, even after signup and login
      return
    } else {
      console.log("Woo! User is logged in!");
    }
  }.bind(this))
}

Alternative attempts:

  • I have tried explicitly logging the user in after signup, but the same result occurs
  • replaced this.createAccount with () => this.createAccount for onClick handler (same result)
  • used firebase.auth() instead of firebaseAuth() (same result)

Does anyone understand why I am not logged in?

** EDIT: **

Below is how I am initializing my app:

<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "XXXXXXXXX",
    authDomain: "myproject.firebaseapp.com",
    databaseURL: "https://myproject.firebaseio.com",
    projectId: "XXXXXXXXX",
    storageBucket: "XXXXXXXXX.appspot.com",
    messagingSenderId: "XXXXXXXXX"
  };
  firebase.initializeApp(config);
</script>

It may be worth noting: If I sign in with an account that was not just created (or if I wait a while and then sign in to the account I created), there doesn't seem to be an issue with retaining the authorization when redirected. It seems to be that it's only when I create a new user and then redirect that it loses the logged in user.

like image 457
Rbar Avatar asked Feb 27 '18 03:02

Rbar


People also ask

What does Firebase auth () CurrentUser return?

If a user isn't signed in, CurrentUser returns null. Note: CurrentUser might also return null because the auth object has not finished initializing.


1 Answers

I have the same setup and it works fine.

I have my auth state change listener at the top of my router...

state = { user: null };

componentDidMount() {
   firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ user });
      } else {
        this.props.history.push('/login');
      }
   });
 }

In Login.js I have a form that connects to a login function similar to yours...

login() {
    firebase
      .auth()
      .signInWithEmailAndPassword(this.state.email, this.state.password)
      .then(res => {
        this.props.history.push('/');
      })
      .catch(err => console.error(error));
  }

The only thing that I can think of you gave history.replace, try changing to history.push.

If that doesn't work is there any chance you can set up a https://codesandbox.io/ with a mcve and I'd be happy to debug it https://stackoverflow.com/help/mcve

like image 127
Josh Pittman Avatar answered Sep 28 '22 13:09

Josh Pittman