Vuefire onAuthStateChanged returns user then null on refresh

384 Views Asked by At

A while ago I built an application with firebase Vue & Vuefire. During development of this when I saved changes of this the application would stay signed in and would auto refresh my project. However I never realised until I picked it back up recently is that When you manually refresh the page this signs out the user. I am using signInWithEmailAndPassword as my only login option and whenever I sign in and refresh it on onAuthStateChanged observer I can see in my log's that a user is present and instantly after is the same log with the user being null and is never authenticated. I want it to re-authenticate and sign in which I thought it would do that automatically as the default authentication persistance local says

"Indicates that the state will be persisted even when the browser window is closed or the activity is destroyed in React Native. An explicit sign out is needed to clear that state. Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only."

My login code looks something like the below

  firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
  }).then(function(){
    console.log('sign in');

Then the user is logged in and on refresh this code is called from Vuejs before created on the vue instance

  beforeCreate: function(){

    firebase.auth().onAuthStateChanged((user) => {
      console.log("On Auth State Changed", user)
        if (!user) {
          console.log("User not logged in");
          // router.replace('/login'); 

        } else{

          // var credential;

          this.user = user;
          // https://github.com/vuejs/vuefire/blob/master/src/vuefire.js#L169
          console.log('snapshot', user);

          user.providerData.forEach(function (profile) {
            console.log("Sign-in provider: " + profile.providerId);
            console.log("  Provider-specific UID: " + profile.uid);
            console.log("  Name: " + profile.displayName);
            console.log("  Email: " + profile.email);
            console.log("  Photo URL: " + profile.photoURL);
          });

          db.ref('posts/list').on('value', function(snapshot) {
                console.log(snapshot.val())
              }, function(error) {
                console.error(error);
              });
          // user.getIdToken(true).then(function(idToken){
          //   console.log('NEW TOKEN: ', idToken);
          // });
          // router.replace('/');
        }
    }).bind(this);

  },

From this I see the console log's for the user but no database data. Directly after that I see console.log("User not logged in");

0

There are 0 best solutions below