ember-cli-can
v1.0.1
Published
Simple authorisation addon for Ember apps
Downloads
5
Maintainers
Readme
ember-cli-can
Simple authorisation addon for Ember.
NOTE: This addon is an fork of ember-cli-can with some improvements and uptodate.
Breaking Changes
- v0.6.0 - support for unit testing abilities added - run
ember g ember-cli-can
- v0.5.0 - support for Ember 1.13+ using new Ember.Helper, removed injections
- v0.4.0 - stopped singularizing ability names to work with pods
- v0.3.0 - removed
if-can
helper, uses sub-expression instead
See UPGRADING for more details.
Quick Example
You want to conditionally allow creating a new blog post:
{{#if (can "write post")}}
<button type="button" onclick={{action "new"}}>Write Post</button>
{{else}}
You can't write a new post
{{/if}}
We define an ability for the Post
resource in /app/abilities/post.js
:
import Ember from 'ember';
import { Ability } from 'ember-cli-can';
export default Ability.extend({
canWrite: Ember.computed('user.isAdmin', function() {
return this.get('user.isAdmin');
})
});
We can also re-use the same ability to check if a user has access to a route:
import Ember from 'ember';
import { CanMixin } from 'ember-cli-can';
export default Ember.Route.extend(CanMixin, {
beforeModel() {
let result = this._super(...arguments);
if (!this.can('write post')) {
return this.transitionTo('index');
}
return result;
}
});
Installation
Install this addon via ember-cli:
ember install ember-cli-can
Compatibility
| Ember Version | Ember Can Release | | ----------------- | --------------------- | | 1.9.x | 0.2 | | 1.10 through 1.12 | 0.4 | | 1.13 and beyond | 0.5+ |
Abilities
An ability class protects an individual model / resource which is available in the ability as model
.
The ability checks themselves are simply standard Ember objects with computed properties:
import Ember from 'ember';
import { Ability } from 'ember-cli-can';
export default Ability.extend({
// only admins can write a post
canWrite: Ember.computed('user.isAdmin', function() {
return this.get('user.isAdmin');
}),
// only the person who wrote a post can edit it
canEdit: Ember.computed('user.id', 'model.author', function() {
return this.get('user.id') === this.get('model.author');
})
});
Handlebars Helpers
The can
helper is meant to be used with {{if}}
and {{unless}}
to protect a block.
The first parameter is a string which is used to find the ability class call the appropriate property (see Looking up abilities).
The second parameter is an optional model object which will be given to the ability to check permissions.
As activities are standard Ember objects and computed properties if anything changes then the view will automatically update accordingly.
{{#if (can "edit post" post)}}
...
{{else}}
...
{{/if}}
As it's a sub-expression, you can use it anywhere a helper can be used. For example to give a div a class based on an ability you can use an inline if:
<div class="{{if (can 'edit post' post) 'is-editable'}}">
</div>
Additional attributes
If you need more than a single resource in an ability, you can pass them additional attributes.
You can do this in the helpers, for example this will set the model
to project
as usual,
but also member
as a bound property.
{{#if (can "remove member from project" project member=member)}}
...
{{/if}}
Similarly in routes you can pass additional attributes after or instead of the resource:
this.can('edit post', post, { author: bob });
this.can('write post', { project: project });
These will set author
and project
on the ability respectively so you can use them in the checks.
Looking up abilities
In the example above we said {{#if (can "write post")}}
, how do we find the ability class & know which property to use for that?
First we chop off the last word as the resource type which is looked up via the container.
The ability file can either be looked up in the top level /app/abilities
directory, or via pod structure.
Then for the ability name we remove some basic stopwords (of, for in) at the end, prepend with "can" and camelCase it all.
For example:
| String | property | resource | pod |
|-----------------------------|--------------------|-------------------------|--------------------------------|
| write post | canWrite
| /abilities/post.js
| app/pods/post/ability.js
|
| manage members in projects | canManageMembers
| /abilities/projects.js
| app/pods/projects/ability.js
|
| view profile for user | canViewProfile
| /abilities/user.js
| app/pods/user/ability.js
|
Current stopwords which are ignored are:
- for
- from
- in
- of
- to
- on
Custom Ability Lookup
The default lookup is a bit "clever"/"cute" for some people's tastes, so you can override this if you choose.
Simply extend the default CanService
in app/services/can.js
and override parse
.
parse
takes the ability string eg "manage members in projects" and should return an object with propertyName
and abilityName
.
For example, to use the format "person.canEdit" instead of the default "edit person" you could do the following:
// app/services/can.js
import { CanService } from 'ember-cli-can';
export default CanService.extend({
parse(str) {
const [abilityName, propertyName] = str.split('.');
return {
propertyName,
abilityName
}
}
});
Injecting the user
How does the ability know who's logged in? This depends on how you implement it in your app!
If you're using an Ember.Service
as your session, you can just inject it into the ability:
// app/abilities/foo.js
import Ember from 'ember';
import { Ability } from 'ember-cli-can';
export default Ability.extend({
session: Ember.inject.service()
});
If you're using ember-simple-auth, you'll probably want to inject the simple-auth-session:main
session
into the ability classes.
To do this, add an initializer like so:
// app/initializers/inject-session-into-abilities.js
export default {
name: 'inject-session-into-abilities',
initialize(app) {
app.inject('ability', 'session', 'simple-auth-session:main');
}
};
The ability classes will now have access to session
which can then be used to check if the user is logged in etc...
Controllers, components & computed properties
In a controller or component, you may want to expose abilities as computed properties so that you can bind to them in your templates.
To do that there's a helper to lookup the ability for a resource, which you can then alias properties:
import { computed } from 'ember-cli-can';
import Ember from 'ember';
export default Ember.Controller.extend({
post: null, // set by the router
// looks up the "post" ability and sets the model as the controller's "post" property
ability: computed.ability('post'),
// alias properties to the ability for easier access
canEditPost: Ember.computed.reads('ability.canEdit')
});
computed.ability
assumes that the property for the resource is the same as the ability resource.
If that's not the case, include it as the second parameter.
import { computed } from 'ember-cli-can';
import Ember from 'ember';
export default Ember.Controller.extend({
// looks up the "post" ability and sets the model as the controller's "content" property
ability: computed.ability('post', 'content')
});
Testing
Make sure that you've either ember install
-ed this addon, or run the addon
blueprint via ember g ember-cli-can
. This is an important step that teaches the
test resolver how to resolve abilities from the file structure.
Unit testing abilities
An ability unit test will be created each time you generate a new ability via
ember g ability <name>
. The package currently supports generating QUnit and
Mocha style tests.
Unit testing in your app
To unit test modules that use the can
helper, you'll need to explicitly add needs
for the
ability and helper file like this:
needs: ['helper:can', 'ability:foo']
Integration testing in your app
For integration testing components, you should not need to specify anything explicitly. The helper and your abilities should be available to your components automatically.
Installation
git clone <repository-url>
this repositorycd ember-cli-can
npm install
Running
ember serve
- Visit your app at http://localhost:4200.
Running Tests
npm test
(Runsember try:each
to test your addon against multiple Ember versions)ember test
ember test --server
Building
ember build
For more information on using ember-cli, visit https://ember-cli.com/.