{"id":13807722,"url":"https://github.com/minutebase/ember-can","last_synced_at":"2025-05-16T05:06:43.857Z","repository":{"id":22980796,"uuid":"26331004","full_name":"minutebase/ember-can","owner":"minutebase","description":"Simple authorisation addon for Ember apps","archived":false,"fork":false,"pushed_at":"2025-04-25T21:26:20.000Z","size":2196,"stargazers_count":272,"open_issues_count":12,"forks_count":50,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-25T22:26:53.988Z","etag":null,"topics":["addon","authorization","ember"],"latest_commit_sha":null,"homepage":"http://ember-can.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/minutebase.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2014-11-07T17:53:08.000Z","updated_at":"2025-04-25T21:25:49.000Z","dependencies_parsed_at":"2024-11-15T22:52:45.451Z","dependency_job_id":"d8f43c9b-bc66-40bc-aef9-ca5374856a8f","html_url":"https://github.com/minutebase/ember-can","commit_stats":{"total_commits":210,"total_committers":43,"mean_commits":4.883720930232558,"dds":0.6904761904761905,"last_synced_commit":"7a58baa3aa7d8fd9dfdf98fdfe08efde2b468354"},"previous_names":[],"tags_count":40,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/minutebase%2Fember-can","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/minutebase%2Fember-can/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/minutebase%2Fember-can/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/minutebase%2Fember-can/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/minutebase","download_url":"https://codeload.github.com/minutebase/ember-can/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254471061,"owners_count":22076585,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["addon","authorization","ember"],"created_at":"2024-08-04T01:01:29.549Z","updated_at":"2025-05-16T05:06:43.841Z","avatar_url":"https://github.com/minutebase.png","language":"JavaScript","readme":"# Ember-can\n\n\u003ca href=\"http://badge.fury.io/js/ember-can\" title=\"Package version\"\u003e\n  \u003cimg src=\"https://badge.fury.io/js/ember-can.svg\"/\u003e\n\u003c/a\u003e\n\n\u003ca href=\"https://emberobserver.com/addons/ember-can\" title=\"Ember Observer\"\u003e\n  \u003cimg src=\"http://emberobserver.com/badges/ember-can.svg\" alt=\"Ember Observer\"/\u003e\n\u003c/a\u003e\n\n[![CI](https://github.com/minutebase/ember-can/actions/workflows/ci.yml/badge.svg)](https://github.com/minutebase/ember-can/actions/workflows/ci.yml)\n\n---\n\nSimple authorisation addon for Ember.\n\n## Installation\n\nInstall this addon via ember-cli:\n\n```\nember install ember-can\n```\n\nAfter installation you will need to add the following import to your app.js or app.ts:\n\n```js\nimport { extendResolver } from 'ember-can';\n```\n\nNext, replace `Resolver = Resolver;` with:\n\n```js\nResolver = extendResolver(Resolver);\n```\n\nWithout this update, the app will encounter an error where it cannot find your abilities.\n\nAfter these changes your app file should look something like:\n\n```js\nimport Application from '@ember/application';\nimport Resolver from 'ember-resolver';\nimport loadInitializers from 'ember-load-initializers';\nimport config from 'my-app/config/environment';\nimport { extendResolver } from 'ember-can';\n\nexport default class App extends Application {\n  modulePrefix = config.modulePrefix;\n  podModulePrefix = config.podModulePrefix;\n  Resolver = extendResolver(Resolver);\n}\n\nloadInitializers(App, config.modulePrefix);\n```\n\n## Compatibility\n\n- Ember.js v4.12 or above\n- Embroider or ember-auto-import v2\n\n## Quick Example\n\nYou want to conditionally allow creating a new blog post:\n\n```hbs\n{{#if (can 'create post')}}\n  Type post content here...\n{{else}}\n  You can't write a new post!\n{{/if}}\n```\n\nWe define an ability for the `Post` model in `/app/abilities/post.js`:\n\n```js\n// app/abilities/post.js\n\nimport { inject as service } from '@ember/service';\nimport { Ability } from 'ember-can';\n\nexport default class PostAbility extends Ability {\n  @service session;\n\n  @computed('session.currentUser')\n  get user() {\n    return this.session.currentUser;\n  }\n\n  @readOnly('user.isAdmin') canCreate;\n  get canCreate() {\n    return this.user.isAdmin;\n  }\n}\n```\n\nWe can also re-use the same ability to check if a user has access to a route:\n\n```js\n// app/routes/posts/new.js\n\nimport Route from '@ember/routing/route';\nimport { inject as service } from '@ember/service';\n\nexport default class NewPostRoute extends Route {\n  @service abilities;\n\n  beforeModel(transition) {\n    let result = super.beforeModel(...arguments);\n\n    if (this.abilities.cannot('create post')) {\n      transition.abort();\n      return this.transitionTo('index');\n    }\n\n    return result;\n  }\n}\n```\n\nAnd we can also check the permission before firing action:\n\n```js\nimport Component from '@ember/component';\nimport { inject as service } from '@ember/service';\nimport { action } from '@ember/object';\n\nexport default class CreatePostComponent extends Component {\n  @service abilities;\n\n  @action\n  createPost() {\n    if (this.abilities.can('create post', this.post)) {\n      // create post!\n    }\n  }\n});\n```\n\n## Helpers\n\n### `can`\n\nThe `can` helper is meant to be used with `{{if}}` and `{{unless}}` to protect a block (but can be used anywhere in the template).\n\n```hbs\n{{can 'doSth in myModel' model extraProperties}}\n```\n\n- `\"doSth in myModel\" ` - The first parameter is a string which is used to find the ability class call the appropriate property (see [Looking up abilities](#looking-up-abilities)).\n\n- `model` - The second parameter is an optional model object which will be given to the ability to check permissions.\n\n- `extraProperties` - The third parameter are extra properties which will be assigned to the ability\n\n**As activities are standard Ember objects and computed properties if anything changes then the view will\nautomatically update accordingly.**\n\n#### Example\n\n```hbs\n{{#if (can 'edit post' post)}}\n  ...\n{{else}}\n  ...\n{{/if}}\n```\n\nAs it's a sub-expression, you can use it anywhere a helper can be used.\nFor example to give a div a class based on an ability you can use an inline if:\n\n```hbs\n\u003cdiv class={{if (can 'edit post' post) 'is-editable'}}\u003e\n\n\u003c/div\u003e\n```\n\n### `cannot`\n\nCannot helper is a negation of `can` helper with the same API.\n\n```hbs\n{{cannot 'doSth in myModel' model extraProperties}}\n```\n\n## Abilities\n\nAn ability class protects an individual model which is available in the ability as `model`.\n\n**Please note that all abilites names have to be in singular form**\n\n```js\n// app/abilities/post.js\n\nimport { computed } from '@ember/object';\nimport { Ability } from 'ember-can';\n\nexport default class PostAbility extends Ability {\n  // only admins can write a post\n  @computed('user.isAdmin')\n  get canWrite() {\n    return this.user.isAdmin;\n  }\n\n  // only the person who wrote a post can edit it\n  @computed('user.id', 'model.author')\n  get canEdit() {\n    return this.user.id === this.model.author;\n  }\n}\n\n// Usage:\n// {{if (can \"write post\" post) \"true\" \"false\"}}\n// {{if (can \"edit post\" post user=author) \"true\" \"false\"}}\n```\n\n## Additional attributes\n\nIf you need more than a single resource in an ability, you can pass them additional attributes.\n\nYou can do this in the helpers, for example this will set the `model` to `project` as usual,\nbut also `member` as a bound property.\n\n```hbs\n{{#if (can 'remove member from project' project member=member)}}\n  ...\n{{/if}}\n```\n\nSimilarly using `abilities` service you can pass additional attributes after or instead of the resource:\n\n```js\nthis.abilities.can('edit post', post, { author: bob });\nthis.abilities.cannot('write post', null, { project: project });\n```\n\nThese will set `author` and `project` on the ability respectively so you can use them in the checks.\n\n## Looking up abilities\n\nIn the example above we said `{{#if (can \"write post\")}}`, how do we find the ability class \u0026 know which property to use for that?\n\nFirst we chop off the last word as the resource type which is looked up via the container.\n\nThe ability file can either be looked up in the top level `/app/abilities` directory, or via pod structure.\n\nThen for the ability name we remove some basic stopwords (of, for in) at the end, prepend with \"can\" and camelCase it all.\n\nFor example:\n\n| String                    | property           | resource                | pod                           |\n| ------------------------- | ------------------ | ----------------------- | ----------------------------- |\n| write post                | `canWrite`         | `/abilities/post.js`    | `app/pods/post/ability.js`    |\n| manage members in project | `canManageMembers` | `/abilities/project.js` | `app/pods/project/ability.js` |\n| view profile for user     | `canViewProfile`   | `/abilities/user.js`    | `app/pods/user/ability.js`    |\n\nCurrent stopwords which are ignored are:\n\n- for\n- from\n- in\n- of\n- to\n- on\n\n## Custom Ability Lookup\n\nThe default lookup is a bit \"clever\"/\"cute\" for some people's tastes, so you can override this if you choose.\n\nSimply extend the default `AbilitiesService` in `app/services/abilities.js` and override `parse`.\n\n`parse` takes the ability string eg \"manage members in projects\" and should return an object with `propertyName` and `abilityName`.\n\nFor example, to use the format \"person.canEdit\" instead of the default \"edit person\" you could do the following:\n\n```js\n// app/services/abilities.js\nimport Service from 'ember-can/services/abilities';\n\nexport default class AbilitiesService extends Service {\n  parse(str) {\n    let [abilityName, propertyName] = str.split('.');\n    return { propertyName, abilityName };\n  }\n}\n```\n\nYou can also modify the property prefix by overriding `parseProperty` in our ability file:\n\n```js\n// app/abilities/feature.js\nimport { Ability } from 'ember-can';\nimport { camelize } from '@ember/string';\n\nexport default class FeatureAbility extends Ability {\n  parseProperty(propertyName) {\n    return camelize(`is-${propertyName}`);\n  },\n};\n```\n\n## Injecting the user\n\nHow does the ability know who's logged in? This depends on how you implement it in your app!\n\nIf you're using an `Ember.Service` as your session, you can just inject it into the ability:\n\n```js\n// app/abilities/foo.js\nimport { Ability } from 'ember-can';\nimport { inject as service } from '@ember/service';\n\nexport default class FooAbility extends Ability {\n  @service session;\n}\n```\n\nThe ability classes will now have access to `session` which can then be used to check if the user is logged in etc...\n\n## Components \u0026 computed properties\n\nIn a component, you may want to expose abilities as computed properties\nso that you can bind to them in your templates.\n\n```js\nimport Component from '@ember/component';\nimport { inject as service } from '@ember/service';\nimport { computed } from '@ember/object';\n\nexport default class MyComponent extends Component {\n  @service abilities; // inject abilities service\n\n  post = null; // received from higher template\n\n  @computed('post')\n  get ability() {\n    return this.abilities.abilityFor('post', this.post /*, customProperties */);\n  }\n}\n\n// Template:\n// {{if ability.canWrite \"true\" \"false\"}}\n```\n\n## Accessing abilities within an Ember engine\n\nIf you're using [engines](http://ember-engines.com/) and you want to access an _ability_ within it, you will need it to be present in your Engine’s namespace. This is accomplished by doing what is called a \"re-export\":\n\n```javascript\n//my-engine/addon/abilities/foo-bar.js\nexport { default } from 'my-app/abilities/foo-bar';\n```\n\n## Upgrade guide\n\nSee [UPGRADING.md](https://github.com/minutebase/ember-can/blob/master/UPGRADING.md) for more details.\n\n## Testing\n\nMake sure that you've either `ember install`-ed this addon, or run the addon\nblueprint via `ember g ember-can`. This is an important step that teaches the\ntest resolver how to resolve abilities from the file structure.\n\n### Unit testing abilities\n\nAn ability unit test will be created each time you generate a new ability via\n`ember g ability \u003cname\u003e`. The package currently supports generating QUnit and\nMocha style tests.\n\n### Integration testing in your app\n\nFor testing you should not need to specify anything explicitly. Anyway, you can\nstub the service following [the official EmberJS guide](https://guides.emberjs.com/release/testing/testing-components/#toc_stubbing-services) if needed.\n\n## Development\n\n### Installation\n\n- `git clone https://github.com/minutebase/ember-can.git`\n- `cd ember-can`\n- `npm install`\n\n### Linting\n\n- `npm run lint:hbs`\n- `npm run lint:js`\n- `npm run lint:js -- --fix`\n\n### Running tests\n\n- `ember test` – Runs the test suite on the current Ember version\n- `ember test --server` – Runs the test suite in \"watch mode\"\n- `ember try:each` – Runs the test suite against multiple Ember versions\n\n### Running the dummy application\n\n- `ember serve`\n- Visit the dummy application at [http://localhost:4200](http://localhost:4200).\n\nFor more information on using ember-cli, visit [https://ember-cli.com/](https://ember-cli.com/).\n\n## Contributing\n\nSee the [Contributing](CONTRIBUTING.md) guide for details.\n\n## License\n\nThis version of the package is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n","funding_links":[],"categories":["Packages"],"sub_categories":["Security"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fminutebase%2Fember-can","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fminutebase%2Fember-can","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fminutebase%2Fember-can/lists"}