Vue Js – How to setup roles in your application

If you have Vue.js and Vuex installed, you should see a router.js file in the main folder.

Open it and add this code in it(Modify the routes as required of course):

const router = new Router({
mode: 'history',
routes: [
//ADMIN
{
path: '/admin',
name: 'admin',
component: AdminPanelIndex,
meta: {
requiresAuth: true, <---- enabled
adminAuth: true, <--- enabled
userAuth: false,
layout: "k-backend-admin",
title: 'Admin area',
},
},
//USERS ONLY
{
path: '/admin/adminBlogging',
name: 'admin-blogging',
component: AdminBlogging,
meta: {
requiresAuth: true, <--- enabled
adminAuth: false,
userAuth: true, <--- enabled
layout: "k-backend-admin",
title: 'View Blog Posts',
},
},
]
});


router.beforeEach((to, from, next) => {
let role = localStorage.getItem('rid'); //<--Get role from API results
let accessToken = localStorage.getItem('accessToken');

if (to.meta.requiresAuth) {
if (!role || !accessToken) {
router.push({path: '/login'});
} else {
if (to.meta.adminAuth) {
if (role === "admin") {
return next();
} else {
router.push({path: '/login'});
}
} else if (to.meta.userAuth) {
if (role === "user") {
return next();
} else {
router.push({path: '/login'});
}
}
}
} else {
return next();
}

});

export default router;

As you can see, we have added a router.beforeEach function which will check your user's role each time you call a new route(page).

You can add as many roles as you wish.

All you will have to do is make sure that you pass the role name from your API as "admin" or "user", and that;s it job done!

I will write another tutorial on how to pass role names from the Laravel API very soon,

Stay tuned!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Disclaimer:

As an Amazon Associate I earn from qualifying purchases. This post may contain affiliate links which means I may receive a commission for purchases made through links.