Skip to content

Instantly share code, notes, and snippets.

@stalniy
Created January 5, 2018 20:58
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stalniy/5adcccf8117177078ada0454e6a6d300 to your computer and use it in GitHub Desktop.
Save stalniy/5adcccf8117177078ada0454e6a6d300 to your computer and use it in GitHub Desktop.
CASL Vue routes
import { AbilityBuilder, Ability } from 'casl'
// Alternatively this data can be retrieved from server
export default function defineAbilitiesFor(user) {
const { rules, can } = AbilityBuilder.extract()
can('read', 'User')
can('update', 'User', { id: user.id })
if (user.role === 'doctor') {
can('manage', 'Patient', { treatedBy: user.id })
}
return new Ability(rules)
}
import router from '...'
import defineAbilitiesFor from '...'
import currentUser from '...' // in real app this is retrieved from server
const abilities = defineAbilitiesFor(currentUser)
// conditional logic based on attributes and resources should be used in specific component template.
// Take a look at https://github.com/stalniy/casl-vue-example/blob/master/src/components/TodoList.vue (i.e., $can usage)
//
router.beforeEach((to, from, next) => {
const canNavigate = to.matched.some(route => {
return abilities.can(route.meta.action || 'read', route.meta.resource)
})
if (!canNavigate) {
return next('/')
}
next()
})
export default [
{
path: '/users/:id',
component: UserProfile,
meta: {
resource: 'User',
}
},
{
path: '/patients',
component: PatientList,
meta: {
resource: 'Patient'
}
}
]
@cheesepaulo
Copy link

Hello, i need help.

How to import auth.js in main.js?

@stalniy
Copy link
Author

stalniy commented Apr 29, 2020

Use import and specify path to auth.js

Nothing special

@pisseleo
Copy link

pisseleo commented Apr 1, 2022

hello every one, i'm using laravel spatie permission and i'm having difficult to use this plugin.
here is my error

app.js:90441 RangeError: Maximum call stack size exceeded
at i.rulesFor (app.js:561:4704)
at i.n.relevantRuleFor (app.js:561:3058)
at i.n.can (app.js:561:2959)
at app.js:123108:61
at Array.some ()
at canNavigate (app.js:123107:21)
at app.js:123567:85
at iterator (app.js:90487:7)
at step (app.js:90129:9)
at runQueue (app.js:90137:3)

i have an array of permission and role, i't recognizes the role but not getting the permissions. i dont know how to deal with the ability.resource on my route guard

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment