Fix unwanted access to user restricted routes with a global navigation guard

This commit is contained in:
Bubka 2020-10-06 20:34:00 +02:00
parent 2b6864f57c
commit 27c7b9b880
2 changed files with 24 additions and 15 deletions

View File

@ -16,13 +16,13 @@ import Errors from './views/Error'
const router = new Router({
mode: 'history',
routes: [
{ path: '/', name: 'accounts', component: Accounts, props: true },
{ path: '/login', name: 'login',component: Login },
{ path: '/register', name: 'register',component: Register },
{ path: '/settings', name: 'settings',component: Settings },
{ path: '/create', name: 'create',component: Create },
{ path: '/edit/:twofaccountId', name: 'edit',component: Edit },
{ path: '/accounts', name: 'accounts', component: Accounts, meta: { requiresAuth: true }, alias: '/', props: true },
{ path: '/settings', name: 'settings', component: Settings, meta: { requiresAuth: true } },
{ path: '/create', name: 'create', component: Create, meta: { requiresAuth: true } },
{ path: '/edit/:twofaccountId', name: 'edit', component: Edit, meta: { requiresAuth: true } },
{ path: '/login', name: 'login', component: Login },
{ path: '/register', name: 'register', component: Register },
{ path: '/password/request', name: 'password.request', component: PasswordRequest },
{ path: '/password/reset/:token', name: 'password.reset', component: PasswordReset },
@ -33,4 +33,22 @@ const router = new Router({
],
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// Accesses to restricted pages without a jwt token are routed to the login page
if ( !localStorage.getItem('jwt') ) {
next({
name: 'login'
})
}
// If the jwt token is invalid, a 401 unauthorized is send by the php backend
else {
next()
}
}
else {
next()
}
});
export default router

View File

@ -271,16 +271,7 @@
this.editMode = state
this.$parent.showToolbar = state
},
},
beforeRouteEnter (to, from, next) {
if ( ! localStorage.getItem('jwt')) {
return next('login')
}
next()
}
};