This package allows to integrate @casl/ability into Aurelia application. So, you can show or hide some components, buttons, etc based on user ability to see them.
npm install @casl/aurelia @casl/ability
This package provides Aurelia plugin which provides CanValueConverter
to templates and Ability
instance to dependency injection container
// main.js
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('@casl/aurelia')
aurelia.start().then(() => aurelia.setRoot())
}
By default, this package provides an empty Ability
instance, so you either need to update provided one or provide your own. In case if you want to provide your own, just define it using AbilityBuilder
(or whatever way you prefer):
// ability.js
import { AbilityBuilder } from '@casl/ability'
export const ability = AbilityBuilder.define(can => {
can('read', 'all')
})
Later you can register your Ability
in dependency injection container:
import { Ability } from '@casl/ability'
import { ability } from './ability'
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('@casl/aurelia')
aurelia.container.registerInstance(Ability, ability)
aurelia.start().then(() => aurelia.setRoot())
}
Also it's possible to provide Ability
instance as plugin argument:
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('@casl/aurelia', ability)
Alternatively, you can just inject existing instance and update rules.
Imagine that we have a Session
service which is responsible for user login/logout functionality. Whenever user login, we need to update ability rules with rules which server returns and reset them back on logout. Lets do this:
// session.js
import { Ability } from '@casl/ability'
export class Session {
static inject = [Ability]
constructor(ability) {
this.ability = ability
this.token = ''
}
login(details) {
return fetch('path/to/api/login', { methods: 'POST', body: JSON.stringify(details) })
.then(response => response.json())
.then(session => {
this.ability.update(session.rules)
this.token = session.token
})
}
logout() {
this.token = ''
this.ability.update([])
// or this.ability.update([{ actions: 'read', subject: 'all' }]) to make everything to be readonly
}
}
See @casl/ability package for more information on how to define abilities.
To check permissions in any template you can use CanPipe
:
<div if.bind="'Post' | can: 'create'">
<a click.trigger="createPost()">Add Post</a>
</div>
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for contributing