I have integrated Firebase for authentication in my Vue.js application. The main (main.js) Vue component handles the authentication logic as follows:
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');
}
});
In addition, the router navigation guard checks the authentication status and handles routing before each route:
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();
}
});
One issue that arises is when the page is refreshed with a valid authentication token, it always redirects to the '/dashboard' route instead of staying on the current route. How can I handle this scenario without adding a beforeEnter guard to each authentication component? I find that approach to be inefficient. Perhaps moving this logic to the Vuex store instead of the created hook in the root instance could be a better solution. I would appreciate any guidance on this matter as I am struggling with this pattern.