Согласно приведенной ниже реализации, он проверяет только аутентификацию текущего пользователя, но не авторизацию . Вы должны иметь роль как свойство в объекте authenticUser
, вы можете дефилировать все доступные роли в массиве:
const Roles = ['doctor', 'Patient'];const authUser = {acces_token: 'xxx', роль: 'пациент'};
всегда пустой объект {} является правдивым, поэтому я добавил
!! Object.keys (authUser) .length
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
const authUser = JSON.parse(window.localStorage.getItem('authUser'));
if (!!Object.keys(authUser).length && authUser.access_token && Roles.includes(authUser.role)) {
next();
} else {
next({ name: 'login' });
}
}
});
Кроме того, необходимо использовать предварительные маршруты gaurds или некомпонентную защиту, чтобы иметь строгие полномочия для ограничения пользователя
защита перед маршрутизатором
const router = new VueRouter({
routes: [
{
path: '/patient',
component: Patient,
beforeEnter: (to, from, next) => {
if (authUser.role === 'patient' || authUser.role === 'doctor') {
next();
} else { //access denied }
}
}
]
})
Встроенная защита
const patientComponent = {
template: `...`,
beforeRouteEnter (to, from, next) {
if (authUser.role === 'patient' || authUser.role === 'doctor') {
// enter
} else { this.$router.push('/accessDenied') }
}
}
const doctorComponent = {
template: `...`,
beforeRouteEnter (to, from, next) {
if (authUser.role === 'doctor') {
// enter
} else { this.$router.push('/accessDenied') }
}
}
Обновленное исправление:
const rolehash = {
1: 'admin',
2: 'doctor',
3: 'patient',
4: 'administrator'
}
Ваш вопрос, если пользователь терпелив ипытаясь нажать url localhost: 8080: // doctor, он должен перенаправить на пациента и не должен вводить
Допустим, здесь auth.role 3
routes: [
{
path: '/doctor',
component: Doctor,
beforeEnter: (to, from, next) => {
if (authUser.role === 2) {
next();
}
else {
next({ path: `/${roleshash[authUser.role]}` })
}
}
}
]
также вы можетепопробуйте этот подход также внутри компонента Doctor
import store from 'store';
beforeRouteEnter (to, from, next) {
if (store.authUser.role === 2) {
next();
}
else {
next({ path: `/${roleshash[authUser.role]}` })
}
},