[Vuejs]-Firebase Authentication Vue Router Guard Issue w/ Vuex

0๐Ÿ‘

โœ…

I figured out a way to do this. Login and logout works correctly, notifications work at login and logout (not at all on refresh), the user is perpetually logged in (onAuthState and token updates should handle the 1 hour timeout), and the page loads only after the firebase login finishes so there is no flash of "Login" instead of the username.

main.js

initializeApp(firebaseConfig);

const auth = getAuth();

let app;
auth.onAuthStateChanged(user => {
  console.log('firedOnAuthStateChanged)')
  store.dispatch("setUser", user).then(() => {
    if (!app) {
      app = new Vue({
        router,
        store,
        vuetify,
        render: h => h(App)
      }).$mount('#app')
    }
  }); 
});

authentication.js (module from store.js)

setUser({dispatch, commit}, user) {
    return new Promise((resolve, reject) => {
      if(user)
      {   
        user.getIdToken().then(token => {
          commit('SET_SESSION_TOKEN', token);
          this._vm.$axios.get('/api/user/login',{
              headers: {
                  'Authorization': `Bearer ${token}`
              }
          })
          .then((response) => {
              commit('SET_SESSION_USER', response.data);
              resolve(response);
              
           })
          .catch(error => {
              dispatch('setSnackbar', {
                color: "error",
                timeout: 4000,
                text: 'Failed verifying token on login.'
              });
              reject();
          });
            
        });
      }
      else
      {
        this._vm.$axios.post('/api/user/logout').then((response) => {
          commit('SET_SESSION_USER', null);
          commit('SET_SESSION_TOKEN', null);
        });
        resolve();
      }  
    })
  }

router.js

router.beforeEach((to, from, next) => {
  const auth = getAuth();
  const user = auth.currentUser;
  if (to.matched.some(record => record.meta.authRequired) && !user) {
    next({ path: '/login'})
    } else {
      next();
    }
});

If you know of a more efficient way of doing this, please let me know.

Leave a comment