I have a function to authorize the user, so the user has restrictions on certain components. The function works well with the 'beforeEnter' navigation-guard. How to use/write the same function in the router beforeEach router-guard?
I tried writing the function in beforeEach but the javascript functions (forEach, includes,..) are not working in the router.beforeEach.
This is the function to authorize
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); }); //returns array of objects
const mappedValidPermissions = validPermissions.map((item) => { return item.permissionType; });// returns array with permissionType
// returned matched permissions
console.log(
JSON.stringify(to.meta.neededPermissions),
JSON.stringify(mappedValidPermissions),
);
if (!to.meta.neededPermissions.every(i=>mappedValidPermissions.includes(i))) {
router.push({ path: "/:notFound(.*)" });
}
});
}
This is the router.beforeEach nav-guard-
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !store.getters["auth/isLoggedIn"]) {
next({
name: "Authentication",
params: {
desiredRoute: to.fullPath,
},
});
} else {
next();
}
});
How to utilize the above function and if condition in beforeEach, so that I can check each router link before giving access?