GeriLife / GeriLife/wellbeing-client
Use route-level metadata and Vuex for route guards
- Dominant language
- Vue
- Stars
- 0
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
We currently have the following route guards defined on the main Router instance:
https://github.com/GeriLife/wellbeing-client/blob/09207281346eee3f1eb01db5fb06f286f40cfd40/src/router/index.js#L30-L51
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.
```js
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
children: [
{
path: 'bar',
component: Bar,
// a meta field
meta: { requiresAuth: true }
}
]
}
]
})
```
```js
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
- [Route Meta Fields](https://router.vuejs.org/guide/advanced/meta.html)
- [Authentication In Vue.js](https://www.smashingmagazine.com/2020/10/authentication-in-vue-js/)
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.