GithubHelp home page GithubHelp logo

gossi / ember-ability Goto Github PK

View Code? Open in Web Editor NEW
8.0 2.0 0.0 891 KB

Abilities for controlling authorisation in ember apps

License: MIT License

JavaScript 44.47% TypeScript 45.06% HTML 8.92% Handlebars 1.17% CSS 0.38%

ember-ability's Introduction

ember-ability

Connect your plain guards, questions or abilities with Ember's DI system, the owner.

The successor to ember-can.

Compatibility

  • Ember.js v3.28 or above
  • Embroider or ember-auto-import v2

Installation

ember install ember-ability

Example

Let's say we want to put a link to registration, but only when the user is not already logged in. We have an ability canRegister, which is based on the isAuthenticated from session service from ember-simple-auth:

const canRegister = ability(({ services }) => () => {
  const { session } = services;

  return !session.isAuthenticated;
});

<template>
  {{#if (canRegister)}}
    <LinkTo @route="registration">Register</LinkTo>
  {{/if}}
</template>

Wait? The Owner does not provide destructuring by default, what is happening here? Since in an ability we are interesting in reading information, we can utilize a read API of the owner, with syntactical sugar from ember-sweet-owner.

Real World Usage

At best - and this is what ember-ability is created for - is to connect an existing business logic available in plain js/ts with Ember. In a blog engine, we want to control editing of a blog post. As business logic is considered to be pure, here is the relevant snippet:

// @my-blog/core

export interface User {
  id: number;
  givenName: string;
  familyName: string;
  admin: boolean;
}

export interface Post {
  id: string;
  author: User;
  title: string;
  content: string;
}

export function canEdit(post: Post, user: User) => {
  return post.author.id === user.id || user.admin;
}

The canEdit function controls whether this functionality is available to a given user. Since this is plain typescript, this can be properly unit tested to ensure business logic works as expected.

In an Ember world, the User is available via service. Let's say as currentUser of the user service. And we can use the above function like so:

import Component from '@glimmer/component';
import UserService from '@my-blog/ember-app/services/user';
import { canEdit } from '@my-blog/core';

export default class AppNavigation extends Component {
  @service declare user: UserService;
  
  <template>
    {{#if (canEdit @post this.user.currentUser)}}
      <LinkTo @route="post.edit" @model={{@post}}>Edit Post</LinkTo>
    {{/if}}
  </template>
}

But this is cumbersome, with the usage of ember-ability, the API can be reduced to a minimum:

import { canEdit as upstreamCanEdit} from '@my-blog/core';
import { ability } from 'ember-ability';

const canEdit = ability(({ services }) => 
  (post: Post) => upstreamCanEdit(post, services.user.currentUser)
);

<template>
  {{#if (canEdit @post)}}
    <LinkTo @route="post.edit" @model={{@post}}>Edit Post</LinkTo>
  {{/if}}
</template>

Code for the example is available in two packages:

Migration from ember-can

As ember-ability is the successor to embe-can here is a practical guide to migrate over`. This is a two step process, to properly plan tech debt tickets.

The guide focuses on the PostAbility:

// app/abilities/post.ts

import { service } from '@ember/service';
import { Ability } from 'ember-can';
import UserService from '../services/user';

export default class PostAbility extends Ability {
  @service declare user: UserService;

  get canEdit() {
    return this.user.currentUser.admin || this.model.author.id === this.user.currentUser.id;
  }
}

1. Extract Pure Ability

As first step, extract the canEdit accessor into its own function. At this point you should consider creating a plain js/ts package, that holds your business logic. A pure package has proven to be the best place. Type your Post and User objects. Move focus to the signature of your pure ability functions.

// @blog/core/post/abilities.ts

import type { Post } from '../post';
import type { User } from '../../user';

export function canEdit(post: Post, user: User) {
  return user.admin || post.author.id === user.id;
}

Next step would be to create fixtures for User and Post. Don't use fake-data. Record real traffic from your apps and store these payloads as fixtures. With production-like fixtures, write unit tests for the function above.

In a second effort use the unit-tested function in the PostAbility

// @blog/app/abilities/post.ts

import { service } from '@ember/service';
import { Ability } from 'ember-can';
import UserService from '../services/user';
+ import { canEdit } from '@blog/core/post/abilities';

export default class PostAbility extends Ability {
  @service declare user: UserService;

  get canEdit() {
-    return this.user.currentUser.admin || this.model.author.id === this.user.currentUser.id;
+    return canEdit(this.model, this.user.currentUser);
  }
}

2. Replace ember-can with ember-ability

When replacing an ember-can ability class with many functions, these newly created abilities can either live organized together in one module or folder, for re-use in many locations - or locally on the component/route. Both approaches will be explained in the following, also with the two ways to connect them to your components: co-located templates and single file components.

Using Co-located Templates

When using co-located templates, the backing class will pipe the ability into the template. In this scenario, the ability is placed into its own module.

// app/abilities/post.ts

import { ability } from 'ember-ability';
import { canEdit as upstreamCanEdit } from '@blog/core/post/abilities';

export const canEdit = ability(({ services }) => 
  (post: Post) => upstreamCanEdit(post, services.user.currentUser)
);

... and use the backing class to pipe the ability into the template...

import { canEdit } from 'app/abilities/post';

export class Post extends Component {
  canEdit = canEdit;
}

... to use it in the template:

{{#if (this.canEdit @post)}}
  <LinkTo @route="post.edit" @model={{@post}}>Edit Post</LinkTo>
{{/if}}

Using Single File Compponents (SFC)

SFCs allow to keep things local in one file, let's do so:

import { ability } from 'ember-ability';
import { canEdit as upstreamCanEdit } from '@blog/core/post/abilities';

export const canEdit = ability(({ services }) => 
  (post: Post) => upstreamCanEdit(post, services.user.currentUser)
);

<template>
  ...

  {{#if (canEdit @post)}}
    <LinkTo @route="post.edit" @model={{@post}}>Edit Post</LinkTo>
  {{/if}}
</template>

ember-ability's People

Contributors

gossi avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ember-ability's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • Update Testing Dependencies (concurrently, ember-qunit, qunit, qunit-dom)
  • Update babel monorepo to v7.24.7 (@babel/core, @babel/eslint-parser, @babel/plugin-proposal-decorators, @babel/preset-typescript, @babel/runtime)
  • Update Type Definitions (@types/eslint, @types/qunit, @types/rsvp)
  • Update dependency @glint/environment-ember-loose to v1.4.0
  • Update dependency @glint/template to v1.4.0
  • Update dependency ember-cli-babel to v8.2.0
  • Update dependency ember-resources to v6.5.1
  • Update dependency release-it to v17.3.0
  • Update dependency rollup to v4.18.0
  • Update dependency typescript to v5.4.5
  • Update dependency webpack to v5.92.0
  • Update embroider monorepo (@embroider/addon-dev, @embroider/addon-shim, @embroider/compat, @embroider/core, @embroider/test-setup, @embroider/webpack)
  • Update jest monorepo to v29.7.0 (@jest/globals, jest)
  • Update Testing Dependencies (major) (ember-qunit, qunit-dom)
  • Update dependency @release-it-plugins/lerna-changelog to v7
  • Update dependency ember-resolver to v12
  • Update dependency ember-template-imports to v4
  • Update embroider monorepo to v4 (major) (@embroider/test-setup, @embroider/webpack)
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • wyvox/action v1
  • wyvox/action v1
  • wyvox/action v1
  • wyvox/action v1
  • wyvox/action v1
  • wyvox/action v1
  • ubuntu 22.04
.github/workflows/release.yml
  • wyvox/action v1
npm
blog-example/core/package.json
  • @gossi/config-eslint ^0.12.0
  • @gossi/config-prettier ^0.8.0
  • @jest/globals ^29.0.3
  • @pollyjs/core ^6.0.6
  • @swc/cli ^0.3.0
  • @swc/core ^1.3.1
  • @swc/jest ^0.2.22
  • @typescript-eslint/eslint-plugin ^7.11.0
  • @typescript-eslint/parser ^7.11.0
  • @types/eslint ^8.44.2
  • chokidar ^3.5.3
  • concurrently ^8.2.0
  • eslint ^8.56.0
  • jest ^29.0.3
  • prettier ^3.2.5
  • typescript ^5.1.6
  • node >= 18
blog-example/web-app/package.json
  • @babel/core ^7.24.6
  • @babel/eslint-parser ^7.24.6
  • @ember/optional-features ^2.0.0
  • @ember/string ^3.1.1
  • @ember/test-helpers ^3.2.0
  • @embroider/compat ^3.2.1
  • @embroider/core ^3.2.1
  • @embroider/webpack ^3.1.5
  • @glimmer/component ^1.1.2
  • @glimmer/tracking ^1.1.2
  • @glint/core ^1.4.0
  • @glint/environment-ember-loose ^1.4.0
  • @glint/environment-ember-template-imports 1.4.0
  • @glint/template ^1.4.0
  • @gossi/config-eslint ^0.12.0
  • @gossi/config-prettier ^0.8.0
  • @gossi/config-stylelint ^0.9.0
  • @gossi/config-targets ^0.9.0
  • @gossi/config-template-lint ^0.8.0
  • @tsconfig/ember ^3.0.0
  • @types/qunit ^2.19.6
  • @types/rsvp ^4.0.4
  • @typescript-eslint/eslint-plugin ^7.11.0
  • @typescript-eslint/parser ^7.11.0
  • broccoli-asset-rev ^3.0.0
  • concurrently ^8.2.0
  • ember-auto-import ^2.6.3
  • ember-cli ~5.6.0
  • ember-cli-babel ^8.2.0
  • ember-cli-dependency-checker ^3.3.2
  • ember-cli-htmlbars ^6.3.0
  • ember-cli-inject-live-reload ^2.1.0
  • ember-cli-sri ^2.1.1
  • ember-link ^3.1.0
  • ember-load-initializers ^2.1.2
  • ember-qunit ^8.0.0
  • ember-resolver ^11.0.1
  • ember-resources ^6.3.1
  • ember-source ~5.6.0
  • ember-template-imports ^4.1.1
  • ember-template-lint ^6.0.0
  • eslint ^8.56.0
  • eslint-plugin-ember ^12.1.1
  • loader.js ^4.7.0
  • msw ^1.2.3
  • prettier ^3.2.5
  • qunit ^2.19.4
  • qunit-dom ^3.0.0
  • stylelint ^16.6.1
  • typescript ^5.1.6
  • webpack ^5.88.2
  • node 16.* || >= 18
ember-ability/package.json
  • @embroider/addon-shim ^1.8.6
  • ember-sweet-owner ^0.2.0
  • @babel/core ^7.24.6
  • @babel/eslint-parser ^7.24.6
  • @babel/plugin-proposal-class-properties ^7.18.6
  • @babel/plugin-proposal-decorators ^7.24.6
  • @babel/preset-typescript ^7.24.6
  • @babel/runtime ^7.24.6
  • @embroider/addon-dev ^4.1.0
  • @glint/core ^1.4.0
  • @glint/environment-ember-loose ^1.4.0
  • @glint/template ^1.4.0
  • @gossi/config-eslint ^0.12.0
  • @gossi/config-prettier ^0.8.0
  • @gossi/config-targets ^0.9.0
  • @release-it-plugins/lerna-changelog ^6.1.0
  • @rollup/plugin-babel ^6.0.4
  • @rollup/plugin-node-resolve ^15.2.3
  • @tsconfig/ember ^3.0.0
  • @typescript-eslint/eslint-plugin ^7.11.0
  • @typescript-eslint/parser ^7.11.0
  • concurrently ^8.2.0
  • ember-source ~5.6.0
  • ember-resources ^6.3.1
  • eslint ^8.56.0
  • eslint-plugin-ember ^12.1.1
  • prettier ^3.2.5
  • release-it ^17.0.0
  • rollup ^4.0.0
  • typescript ^5.1.6
  • node 18.* || >= 20
package.json
  • concurrently ^8.2.2
  • node 20.14.0
test-app/package.json
  • @babel/core ^7.24.6
  • @babel/eslint-parser ^7.24.6
  • @ember/optional-features ^2.0.0
  • @ember/string ^3.1.1
  • @ember/test-helpers ^3.2.0
  • @embroider/compat ^3.2.1
  • @embroider/test-setup ^3.0.1
  • @embroider/webpack ^3.1.5
  • @glimmer/component ^1.1.2
  • @glimmer/tracking ^1.1.2
  • @glint/core ^1.4.0
  • @glint/template ^1.4.0
  • @glint/environment-ember-loose ^1.4.0
  • @glint/environment-ember-template-imports 1.4.0
  • @gossi/config-eslint ^0.12.0
  • @gossi/config-prettier ^0.8.0
  • @gossi/config-targets ^0.9.0
  • @gossi/config-template-lint ^0.8.0
  • @tsconfig/ember ^3.0.0
  • @types/qunit ^2.19.6
  • @types/rsvp ^4.0.4
  • @typescript-eslint/eslint-plugin ^7.11.0
  • @typescript-eslint/parser ^7.11.0
  • broccoli-asset-rev ^3.0.0
  • concurrently ^8.2.0
  • ember-auto-import ^2.6.3
  • ember-cli ~5.6.0
  • ember-cli-babel ^8.2.0
  • ember-cli-dependency-checker ^3.3.2
  • ember-cli-htmlbars ^6.2.0
  • ember-cli-inject-live-reload ^2.1.0
  • ember-disable-prototype-extensions ^1.1.3
  • ember-load-initializers ^2.1.2
  • ember-qunit ^8.0.0
  • ember-resolver ^11.0.1
  • ember-resources ^6.4.0
  • ember-source ~5.6.0
  • ember-source-channel-url ^3.0.0
  • ember-template-imports ^4.1.1
  • ember-template-lint ^6.0.0
  • ember-try ^3.0.0
  • eslint ^8.56.0
  • eslint-plugin-ember ^12.1.1
  • loader.js ^4.7.0
  • pnpm-sync-dependencies-meta-injected ^0.0.14
  • prettier ^3.2.5
  • qunit ^2.19.4
  • qunit-dom ^3.0.0
  • typescript ^5.1.6
  • webpack ^5.88.2

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.