I've implemented Firebase (aka. Google Identity Platform) into my Vue project. I want to protect specific routes, so I've added the following:
// router/index.js
{
path: '/profile',
name: 'Profile',
component: Profile,
beforeEnter: (to, from, next) => {
if (firebase.auth().currentUser) {
next()
} else {
next({
path: '/login',
})
}
}
},
This works! However, it would become unmanageable if I did that for every route.
To make it tidy, I tried putting it into a function (within the route file and tried externally) but it won't work because Firebase hasn't been initialized at the time it is parsed so it throws an error saying to initialize Firebase first.
Firebase is initialised in my main.js
file:
// main.js
// Firebase configuration
var firebaseConfig = {
// Config details redacted
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
Ideally what I am after is something similar to what Auth0 provides in there SDK example:
// router/index.js
//...some route
beforeEnter: authGuard()
Then authGuard
would be in an external file. This file would hold the function that checks if a user is authenticated or not. Then I can add it to routes as needed.