My router file checking what role is logged in:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAdmin)) {
if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == "admin"){
next()
return
}
next('/auth/login')
}else if (to.matched.some(record => record.meta.requiresStaff)) {
if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == "staff"){
next()
return
}
next('/auth/login')
}else {
next()
}
})
and my admin router is:
const adminRoutes = [
{
path: '/dashboard',
name: 'admin.dashboard.index',
component: () => import( /* webpackChunkName: "admin.dashboard.index" */ '@/views/administrator/dashboard/Index.vue'),
meta: { requiresAdmin: true, requiresStaff: true, layout: 'default' }, /* Look At this Line */
},
// Article Route
{
path: '/article',
name: 'admin.article.index',
component: () => import( /* webpackChunkName: "admin.article.index" */ '@/views/administrator/article/Index.vue'),
meta: { requiresAdmin: true, layout: 'default' },
},
]
I have already add requiresAdmin: true, requiresStaff: true, in meta field. But when i login with admin, its work. But when i login with staff account, i cant reach dashboard page.
Advertisement
Answer
The problem is that when you are logged in as staff and you access the dashboard page, this condition is still true: if (to.matched.some(record => record.meta.requiresAdmin)). But as you have the permission staff you get redirected to the login page.
A solution would be to define the allowed roles per page explicitly.
const adminRoutes = [
{
path: '/dashboard',
name: 'admin.dashboard.index',
component: () => import( /* webpackChunkName: "admin.dashboard.index" */ '@/views/administrator/dashboard/Index.vue'),
meta: { roles: ['admin', 'staff'], layout: 'default' },
},
// Article Route
{
path: '/article',
name: 'admin.article.index',
component: () => import( /* webpackChunkName: "admin.article.index" */ '@/views/administrator/article/Index.vue'),
meta: { roles: ['admin'], layout: 'default' },
},
]
router.beforeEach((to, from, next) => {
const currentRole = VueJwtDecode.decode(localStorage.getItem('accessToken')).sub
const hasPublicAccess = !record.meta.roles || record.meta.roles.length === 0
if (hasPublicAccess || to.matched.some(record => record.meta.roles.includes(currentRole)) {
next()
return
}
next('/auth/login')
return
})