Reputation: 7118
I am returning user type in all my components but i need to add validation of it in my routes, not sure how to.
This is my route.js
file where the routes i need users to be authenticated are defined in meta
import Vue from "vue";
import VueRouter from 'vue-router';
import store from './store';
Vue.use(VueRouter);
const router = new VueRouter({
mode: "history",
routes: [
// ADMIN ROUTES
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
requiresAuth: true,
layout: 'admin'
}
},
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isLoggedIn) {
next({
name: 'login'
})
} else {
next()
}
} else {
next()
}
})
router.afterEach((to, from) => {
Vue.nextTick(() => {
document.title = to.pageTitle || 'CC';
});
});
export default router;
As you can see I have requiresAuth: true,
which only allows authenticated user to access this route, I also need to add another value which says if user type == admin
that way not all logged in users can access to such route but only admins.
This is my logged user info which is accessible in all components and is included type
value
How can I add user type to routes meta?
Note
my type value can be one of this 3 conditions
- admin (admins role)
- customer (any other user role)
- undefined (user with no role assigned)
Forgot to mention that in all my components I also have this function
beforeRouteEnter (to, from, next) {
const token = localStorage.getItem('access_token')
return token ? next() : next('/login')
},
This simply check if my user is logged in based on saved token in localStorage
I've also tried to get my user type in component function like code below, but is returned this.$store
is undefined
beforeRouteEnter (to, from, next) {
if (this.$store.getters.loggedUser.type != 'admin') {
next({
name: 'home'
})
} else {
next()
}
}
Upvotes: 0
Views: 1728
Reputation: 1542
The component instance this
is not avaliable inside beforeRouteEnter
See here.
One way to do what you want is to add another meta attribute to your admin routes and check the user type for each route that has admin: true
.
Your router code would look something like this:
const router = new VueRouter({
mode: "history",
routes: [
// ADMIN ROUTES
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
requiresAuth: true,
layout: 'admin',
admin: true
}
},
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isLoggedIn) {
next({
name: 'login'
})
}
}
if (to.matched.some(record => record.meta.admin)) {
if (store.getters.loggedUser.type !== 'admin') {
// Do something if the user is not an admin
// maybe redirect to a forbidden page
}
}
next()
})
Upvotes: 1