Я пытаюсь защитить маршруты с помощью защиты на основе ролей, однако при выполнении маршрутов проверку выполняйте только на втором маршруте, который я посещаю.Это происходит снова и снова, кажется, что это проблема с дочерними маршрутами, только проверка выполняется во 2-м маршруте, который посещают дети.Я прилагаю свой код
router.beforeEach((to,from, next)=>{
const rolesToPath = (to.meta.roles)?to.meta.roles:null //roles authorized in next path
const reqAuth = to.matched.some(record=> record.meta.auth)
const currentUser = store.state.currentUser //current user With Roles
const homeRoute = '/dashboard'
const loginRoute = '/login'
if (reqAuth && currentUser) {
let auth = matchRoles(rolesToPath,currentUser.roles)
if (auth) {
next()
} else {
next(homeRoute)
}
}
function matchRoles(x,y){ //this function resolve if user is authorized
// to next path
let flag = false
x.forEach((x)=>{
y.forEach((y)=>{
if (x.userRol==y.name) {
flag = true//if role user is on next path
}
})
})
if (flag) return true
return false
}
})
Это маршруты, к которым я хочу применить проверку
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
export default new VueRouter({
mode: 'history', // https://router.vuejs.org/api/#mode
linkActiveClass: 'open active',
scrollBehavior: () => ({ y: 0 }),
routes:[
{
path: '/login',
name: 'Login',
component: Login,
meta : {
auth: false,
},
},
{
path: '/register',
name: 'Register',
component: Register,
meta : {
auth: false,
},
},
{
path: '/',
redirect: '/dashboard',
name: 'Home',
component: DefaultContainer,
meta : {
auth: false,
},
children: [
{
path : 'credenciales',
redirect : '/credenciales/proveedores',
name : 'Credenciales',
component : {
render (c) { return c('router-view') }
},
children: [
{
path : 'proveedores',
name : 'Proveedores',
component : TablaProveedores,
meta : {
auth: true,
roles: [
{
userRol : 'tester',
lock : true,
}
]
},
},
{
path : 'accesos',
name : 'Accesos',
component : TablaProveedores,
meta : {
auth: true,
roles: [
{
userRol : 'admin',
lock : true,
}
]
},
},
]
},
]
})