-
-
Save tecfu/506f32510529d7c93c2b01a21987919b to your computer and use it in GitHub Desktop.
CASL Vue routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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