Firebase Auth login state persistence is not working

On an ionic/AngularJS/Cordova IOS app.

I'm trying to set a persistence login using mail/password (followed Firebase documentation : https://firebase.google.com/docs/auth/web/auth-state-persistence). But I can't figured out what is wrong with my code. My app is starting on the login page, when a user is clicking on the "Connexion button", it's trigger the login function.

The login is working, but when I'm closing the app (without logging out), restarting it, I'm still on the login page. The login is not persistent.

So I guess, one problem, might be the persistency call not well placed...Is it ? According to this post : Firebase 3.0 session persistance it could have someting related to firebase.auth().onAuthStateChanged(function(user), but I don't know...

// EMAIL CONNEXION TRIGGERED WHEN CONNEXION BUTTON IS HIT

$scope.loginEmail = function($email, $password){
  
  firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(function() {
    var alertPopup;
    
    function signInSuccess(response) {
  
				$state.go("menu.VN");
    }

    function signInError(response) {
    
        var errorCode = null;
        errorCode = response.code;
        if ($email === ""){
             alertPopup = $ionicPopup.alert({
                    title: 'Something wrong...',
                    cssClass: 'pop',
                    template: '<div class="center-form">Need an email address...</div>'
                });   
        }
}

return firebase.auth().signInWithEmailAndPassword($email, $password)
  .then(signInSuccess)
  .catch(signInError);

     })
     .catch(function(error) {
    // Handle persistence Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

};
<label>
          <span>Email</span>
          <input type="email" placeholder="" ng-model="data.email">
</label>

<label>
          <span>Password</span>
          <input type="password" placeholder="" ng-model="data.password">
</label>
    
<button ng-click="loginEmail(data.email, data.password )">Connexion</button>

Answers:

Answer

To persist your state, you should use firebase.auth.Auth.Persistence.LOCAL and not firebase.auth.Auth.Persistence.SESSION.

There are known issues with localStorage in Cordova iOS apps being volatile. Firebase Auth used to rely on localStorage but the latest version uses more reliable indexedDB to persist the user state. When this is not available, it falls back to localStorage. In that case, you could use this Microsoft plugin for indexedDB.

tldr; migrate to the latest version of Firebase Auth and use the Cordova indexedDB plugin when indexedDB is not available.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.