Skip to content

Instantly share code, notes, and snippets.

@tecfu
Forked from stalniy/abilities.js
Created August 29, 2019 23:02
Show Gist options
  • Save tecfu/506f32510529d7c93c2b01a21987919b to your computer and use it in GitHub Desktop.
Save tecfu/506f32510529d7c93c2b01a21987919b 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'
}
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment