Currently, I am developing a Vue.js application that requires the implementation of router guards to restrict access based on user roles and prevent unauthorized users from accessing the application.
The login process involves integrating an external application (specifically WSO2 Identity Server), and the user information obtained is stored in a Vuex store.
The issue arises because the login function operates asynchronously. Consequently, when the router guards are triggered, user info is not yet available. To address this, I invoked the login function within an anonymous asynchronous function and enclosed the guards within its then
block.
As I couldn't find any examples of this technique online, I would appreciate feedback on whether this approach is correct or if there is a more effective method for handling this dilemma. Thank you all in advance.
Below is an extract of my router code:
... router code
(async function() {
// fetches user data and stores them in the Vuex storage
await userService.initUserData();
})().then( function() {
const isAuthenticated = store.getters.getIsAuthenticated;
const userRole = store.getters.getUserRole;
router.beforeEach((to, from, next) => {
// verifies if the user is logged in,
// redirects to the login page (LoginPage) if not
if (to.name !== 'LoginPage' && !isAuthenticated) {
next({ name: 'LoginPage' });
} else {
if (to.meta.customerAuth) {
if (userRole === 'Customer') {
next();
} else if (userRole === 'Admin') {
next({ name: 'AdminView' });
} else {
next({ name: 'LoginPage' });
}
} else if (to.meta.adminAuth) {
if (userRole === 'Admin') {
next();
} else if (userRole === 'Customer') {
next({ name: 'CustomerView' });
} else {
next({ name: 'LoginPage' });
}
}
}
})
}
);