0

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?

1 Answer 1

0

What version of vue-router are you using. The current version's signature of beforeEach changed. Instead of calling next, you would optionally return either false or a route location object.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I am using v4, but how to use the above function and condition in the router.beforeEach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.