当前位置: 首页 > 软件库 > 程序开发 > >

ember-can

Simple authorisation addon for Ember apps
授权协议 MIT License
开发语言 JavaScript
所属分类 程序开发
软件类型 开源软件
地区 不详
投 递 者 郭意
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Ember-can


Simple authorisation addon for Ember.

Installation

Install this addon via ember-cli:

ember install ember-can

Compatibility

  • Ember.js v3.20 or above
  • Ember CLI v3.20 or above
  • Node.js v12 or above

Quick Example

You want to conditionally allow creating a new blog post:

{{#if (can "create post")}}
  Type post content here...
{{else}}
  You can't write a new post!
{{/if}}

We define an ability for the Post model in /app/abilities/post.js:

// app/abilities/post.js

import { readOnly } from '@ember/object/computed';
import { Ability } from 'ember-can';

export default Ability.extend({
  session: service(),

  user: readOnly('session.currentUser'),

  canCreate: readOnly('user.isAdmin')
});

We can also re-use the same ability to check if a user has access to a route:

// app/routes/posts/new.js

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  can: service(),

  beforeModel(transition) {
    let result = this._super(...arguments);

    if (this.can.cannot('create post')) {
      transition.abort();
      return this.transitionTo('index');
    }

    return result;
  }
});

And we can also check the permission before firing action:

import Component from '@ember/component';

export default Component.extend({
  can: service(),

  actions: {
    createPost() {
      if (this.can.can('create post', this.post)) {
        // create post!
      }
    }
  }
});

Helpers

can

The can helper is meant to be used with {{if}} and {{unless}} to protect a block (but can be used anywhere in the template).

{{can "doSth in myModel" model extraProperties}}
  • "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).

  • model - The second parameter is an optional model object which will be given to the ability to check permissions.

  • extraProperties - The third parameter are extra properties which will be assigned to the ability

As activities are standard Ember objects and computed properties if anything changes then the view willautomatically update accordingly.

Example

{{#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>

cannot

Cannot helper is a negation of can helper with the same API.

{{cannot "doSth in myModel" model extraProperties}}

Abilities

An ability class protects an individual model which is available in the ability as model.

Please note that all abilites names have to be in singular form

// app/abilities/post.js

import { computed } from '@ember/object';
import { Ability } from 'ember-can';

export default Ability.extend({
  // only admins can write a post
  canWrite: computed('user.isAdmin', function() {
    return this.get('user.isAdmin');
  }),

  // only the person who wrote a post can edit it
  canEdit: computed('user.id', 'model.author', function() {
    return this.get('user.id') === this.get('model.author');
  })
});

// Usage:
// {{if (can "write post" post) "true" "false"}}
// {{if (can "edit post" post user=author) "true" "false"}}

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 using can service you can pass additional attributes after or instead of the resource:

this.get('can').can('edit post', post, { author: bob });
this.get('can').cannot('write post', null, { 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 project canManageMembers /abilities/project.js app/pods/project/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 Service from 'ember-can/services/can';

export default CanService.extend({
  parse(str) {
    let [abilityName, propertyName] = str.split('.');
    return { propertyName, abilityName };
  }
});

You can also modify the property prefix by overriding parseProperty in our ability file:

// app/abilities/feature.js
import { Ability } from 'ember-can';
import { camelize } from '@ember/string';

export default Ability.extend({
  parseProperty(propertyName) {
    return camelize(`is-${propertyName}`);
  },
});

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 { Ability } from 'ember-can';
import { inject as service } from '@ember/service';

export default Ability.extend({
  session: service()
});

The ability classes will now have access to session which can then be used to check if the user is logged in etc...

Components & computed properties

In a component, you may want to expose abilities as computed propertiesso that you can bind to them in your templates.

import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  can: service(), // inject can service

  post: null, // received from higher template

  ability: computed('post', function() {
    return this.get('can').abilityFor('post', this.get('post') /*, customProperties */);
  }),
});

// Template:
// {{if ability.canWrite "true" "false"}}

Optional way

Optionally you can use ability computed to simplify the syntax:

import Component from '@ember/component';
import { ability } from 'ember-can/computed';

export default Component.extend({
  can: service(), // inject can service

  post: null, // received from higher template

  ability: ability('post')
});

If the model property is not the same as ability name you can pass a second argument:

ability: ability('post', 'myModelProperty')

Accessing abilities within an Ember engine

If you're using engines 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":

//my-engine/addon/abilities/foo-bar.js
export { default } from 'my-app/abilities/foo-bar';

Upgrade guide

See UPGRADING.md for more details.

Testing

Make sure that you've either ember install-ed this addon, or run the addonblueprint via ember g ember-can. This is an important step that teaches thetest 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 viaember g ability <name>. The package currently supports generating QUnit andMocha style tests.

Integration testing in your app

For testing you should not need to specify anything explicitly. Anyway, you canstub the service following the official EmberJS guide if needed.

Development

Installation

  • git clone https://github.com/minutebase/ember-can.git
  • cd ember-can
  • npm install

Linting

  • npm run lint:hbs
  • npm run lint:js
  • npm run lint:js -- --fix

Running tests

  • ember test – Runs the test suite on the current Ember version
  • ember test --server – Runs the test suite in "watch mode"
  • ember try:each – Runs the test suite against multiple Ember versions

Running the dummy application

For more information on using ember-cli, visit https://ember-cli.com/.

Contributing

See the Contributing guide for details.

License

This version of the package is available as open source under the terms of the MIT License.

  • Ember.js - About Ember.js - About More Productive Out of the Box.   Write dramatically less code with Ember's Handlebars integrated templates that update automatically when the underlying data changes

  • Angular.js 拥抱 HTML/CSS Misko Hevery(Angular.js的开发者之一)回答了这一问题,他的主要观点如下: 在HTML中加入太多逻辑不是好做法。Angular.js只放置绑定,而不是逻辑,建议把逻辑放入控制器中。但绑定同样是信息,通常,这些信息可以放在三个地方: 代码。但这使得程序模块化很成问题,因为HTML与代码紧密耦合,要想重新组成一个应用程序非常困难。 HT

  • In lieu of app-specific, fully-qualified, field-tested recommendations, a recommendation for how often to call emberTick() is this:   -Call the function as much as possible to preserve stack timing an

 相关资料
  • Ember检查器是一个浏览器插件,用于调试Ember应用程序。 灰烬检查员包括以下主题 - S.No. 灰烬检查员方式和描述 1 安装Inspector 您可以安装Ember检查器来调试您的应用程序。 2 Object Inspector Ember检查器允许与Ember对象进行交互。 3 The View Tree 视图树提供应用程序的当前状态。 4 检查路由,数据选项卡和库信息 您可以看到检查

  • 英文原文: http://emberjs.com/guides/getting-ember/index/ Ember构建 Ember的发布管理团队针对Ember和Ember Data维护了不同的发布方法。 频道 最新的Ember和Ember Data的 Release,Beta 和 Canary 构建可以在这里找到。每一个频道都提供了一个开发版、最小化版和生产版。更多关于不同频道的信息可以查看博客

  • ember-emojione ember-emojione is your emoji solution for Ember, based on the EmojiOne project. EmojiOne version 2 is used, which is free to use for everyone (CC BY-SA 4.0), you're only required to giv

  • Ember 3D Ember 3D is an Ember addon for using Three.js - an easy to use, lightweight, javascript 3D library. It is designed to: Prescribe a solid file structure to Three.js code using ES6 modules. Ena

  • Ember Table An addon to support large data set and a number of features around table. Ember Table canhandle over 100,000 rows without any rendering or performance issues. Ember Table 3.x supports: Emb

  • vscode-ember This is the VSCode extension to use the Ember Language Server. Features All features currently only work in Ember-CLI apps that use classic structure and are a rough first draft with a lo

  • ember-headlessui This is a work-in-progress implementation of: https://github.com/tailwindlabs/headlessui A set of completely unstyled, fully accessible UI components for Ember.js, designed to integra

  • Ember Popper An Ember-centric wrapper around Popper.js. Currently an alpha in active development. See the dummy app for examples Compatibility Ember.js v3.12 or above Ember CLI v2.13 or above Node.js