I have implemented a function to authorize users, enabling restrictions on specific components based on their permissions. The function currently works effectively with the 'beforeEnter'
navigation guard in Vue Router. However, I am facing difficulties trying to integrate the same function within the router's beforeEach guard.
When attempting to write the function inside the beforeEach guard, I encountered issues with JavaScript functions like 'forEach' and 'includes' not working as expected within router.beforeEach
.
Below is the function used for authorization:
function authorizeUser(to) {
const currentUser = store.getters["auth/isCurrentUser"];
console.log(currentUser);
currentUser.teams.forEach((team) => {
const validPermissions = team.permissions.filter((item) => { return to.meta.neededPermissions.includes(item.permissionType); });
const mappedValidPermissions = validPermissions.map((item) => { return item.permissionType; });
console.log(
JSON.stringify(to.meta.neededPermissions),
JSON.stringify(mappedValidPermissions),
);
if (!to.meta.neededPermissions.every(i => mappedValidPermissions.includes(i))) {
router.push({ path: "/:notFound(.*)" });
}
});
}
Below is the router.beforeEach
navigation guard code snippet:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !store.getters["auth/isLoggedIn"]) {
next({
name: "Authentication",
params: {
desiredRoute: to.fullPath,
},
});
} else {
next();
}
});
I am seeking guidance on how to effectively utilize the above function alongside the specified if condition
within the beforeEach guard to validate each router link before granting access.