I have a vue
project and laravel
as a back-end
, i have to check if an user has permissions to access a resource or a view, in the backend i use laravel permissions to accomplish this, and it work fine, the problem i have now is in the front end.
I fetch the users permissions when it login and save it on the localStorage
, now how can i prevent a user for enter a certain route if the user does not have the permissions for it?
for example i have these routes
{
path: 'users',
name: 'Users',
component: Users,
meta : {
permissions: 'read_users'
}
},
{
path: 'roles-permissions',
name: 'RolesPermissions',
component: RolesPermissions,
meta : {
permissions: 'read_roles'
}
},
{
path: 'roles-permissions/create',
name: 'CreateRolesPermissions',
component: CreateRolesPermissions,
meta : {
permissions: 'create_roles'
}
},
{
path: 'roles-permissions/:id/edit',
name: 'EditRolesPermissions',
component: EditRolesPermissions,
meta : {
permissions: 'edit_roles'
}
},
{
path: 'customers',
name: 'Clientes',
component: CustomersList
}
if the user does not have a permission in ['read_roles','create_roles','edit_roles','read_users']
she should be redirected to customers
.
var permissions = localStorage.getItem('permissions'); var can = to.meta.permissions ? (permissions.includes(to.meta.permissions) || to.meta.permissions == '*') : true;
how can this be done?
Here is a great example of implementing authentication with Vue router: https://scotch.io/tutorials/vue-authentication-and-route-handling-using-vue-router
Basically, you can check permissions before letting the user open the protected component. The easiest way to achieve this is using router guards. In your router definitions:
{
path: '/protected',
beforeEnter(to, from, next) {
if (isAuthenticated()) {
if (!hasPermissionsNeeded(to)) {
next('/page-to-show-for-no-permission');
} else {
next();
}
} else {
next('/page-to-show-for-unauthenticated-users');
}
}
}
This guard will protect from entering /protected
url. Here you can check the working codepen: https://codepen.io/anon/pen/JwxoMe
Below is an example of aa guard for all routes:
router.beforeEach((to, from, next) => {
if (isAuthenticated()) {
if (!hasPermissionsNeeded(to)) {
next('/page-to-show-for-no-permission');
} else {
next();
}
} else {
next('/page-to-show-for-unauthenticated-users');
}
})
More about router guards: https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With