I'm using firebase to do authentication in my vuejs app. In my root (main.js) vue component.
created() {
auth.onAuthStateChanged((user) => {
this.$store.commit('user/SET_USER', user);
if (user && user.emailVerified) {
this.$store.dispatch('user/UPDATE_VERIFIED', {
userId: user.uid,
});
// SUCCESSFUL LOGIN
this.$router.replace('dashboard');
} else if (user && !user.emailVerified) {
this.$router.replace('verify');
}
});
So essentially, my router navigation guard is checking auth status and doing routing before each route as well.
router.beforeEach((to, from, next) => {
const currentUser = firebaseApp.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const allowUnverified = to.matched.some(record => record.meta.allowUnverified);
if (requiresAuth && !currentUser) {
next('login');
} else if (currentUser
&& !currentUser.emailVerified
&& !allowUnverified
&& to.path !== '/verify') {
next('verify');
} else if (!requiresAuth && currentUser) {
next('dashboard');
} else {
next();
}
});
What happens is, when you refresh the page (with a valid auth token), you hit branch 1 of the route guard, stateChanges and the handler is called to redirect to /dashboard. So refreshing while logged in, always brings you to the dashboard route instead of the current route youre on.
How can I handle this case? Adding a beforeEnter guard to each auth component smells bad to me Data Fetching Vue Docs.
Should this be in the store instead of the created hook on the root instance? Any help is greatly appreciated. This pattern is stumping me.