Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use route-level metadata and Vuex for route guards #47

Open
brylie opened this issue Apr 18, 2021 · 0 comments
Open

Use route-level metadata and Vuex for route guards #47

brylie opened this issue Apr 18, 2021 · 0 comments

Comments

@brylie
Copy link
Member

brylie commented Apr 18, 2021

We currently have the following route guards defined on the main Router instance:

Router.beforeEach(async (to, from, next) => {
if (to.path.startsWith("/resident/")) {
next();
return;
}
if (to.path === "/login" && !!getCookie("token")) {
next("/");
return;
}
if (to.path === "/login" && !getCookie("token")) {
next();
return;
}
const result = await checkIfLoggedIn();
if (!result) {
next("/login");
return;
}
next();
});

There seem to be three main guards:

  • ensure logged in (on all routes)
  • allow anonymous access (used on /resident)
  • redirect if already logged in (on /login route)

The first condition in the route guards is to check what the current path is. Since routes are defined by path, the path check is somewhat redundant.

One conventional approach is to use the route meta field to define a property requiresAuth, as follows. Notice the use of a Vuex store for an authentication token.

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})
router.beforeEach((to, from, next) => {
  if(to.matched.some(record => record.meta.requiresAuth)) {
    if (store.getters.isAuthenticated) {
      next()
      return
    }
    next('/login')
  } else {
    next()
  }
})

Refactor the route guards into re-usable functions and apply requresAuth meta attribute directly in the relevant route definitions.

Resources

@brylie brylie changed the title Move navigation guards to route-level rather than on all routes Use route-level metadata and Vuex for route guards Apr 18, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant