Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Firebase auth persistence not working

Firebase auth does not persist logged in user and everytime I refresh or reopen app I have to sign in again.

I have tried setting persistence to local and the callback does verify its set but the persistence is still no working

For setting persistence I am using...

  //set auth persistence
  firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
    .then(function() {
      console.log("successfully set the persistence");

    })
    .catch(function(error){
    console.log("failed to ser persistence: " + error.message)
  });

. . . For signing in I am using this code

firebase.auth().signInWithEmailAndPassword(email, password)
      .then((user) =>{
        this.checkAccountStatus(user.uid, user.email);
      })
      .catch(function(error) {
      // Handle Errors here.

      var errorCode = error.code;
      var errorMessage = error.message;

      console.log(errorMessage)
      // ...
    });

And here is the code I am using to check login status...

if (firebase.auth().currentUser) {
        const currentUser = firebase.auth().currentUser;
        console.log("Signed in username" + currentUser.displayName);

        this.props.navigation.navigate('AppTab');
      }else{
        console.log("no user signed in");
        this.props.navigation.navigate('AuthTab');
      }

if there anything I am not doing right

like image 457
Nouman Tahir Avatar asked Sep 10 '17 17:09

Nouman Tahir


People also ask

Does Firebase authenticate persist?

Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only. Indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed. Applies only to web apps.

What is onAuthStateChanged used for?

In most scenarios using Authentication, you will want to know whether your users are currently signed-in or signed-out of your application. The module provides a method called onAuthStateChanged which allows you to subscribe to the users current authentication state, and receive an event whenever that state changes.

What is onAuthStateChanged Firebase?

According to the documentation, the onAuthStateChanged() function returns. The unsubscribe function for the observer. So you can just: var unsubscribe = firebase.


1 Answers

You don't need to set persistence. Firebase handles it for you by default. You just need to call this function to check whether user is logged or not:

firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log('user is logged');
      }
});

This will not be triggered only if user has sign out or cleaned app data.

You can find more details in the official docs: https://firebase.google.com/docs/auth/web/manage-users

Hope it helps.

like image 112
soutot Avatar answered Oct 07 '22 02:10

soutot