@microloop/acl-global
TypeScript icon, indicating that this package has built-in type declarations

0.4.4 • Public • Published

@microloop/acl-global

A extension library for @bleco/acl to simplify global roles usage

Installation

NPM:

npm install @microloop/acl-global

Yarn:

yarn add @microloop/acl-global

Usage

  1. Mixin the entity with AclAppRelModelMixin
import {entity} from '@bleco/repo';

// !!! IMPORTANT !!!
// Using @entity decorator to replace @model decorator for inheritance relations
@entity()
export class SomeEnitty extends AclAppRelModelMixin(Entity) {
  // ...
}
  1. Mixin the repository with AclAppRelRepositoryMixin
export class SomeRepository extends AclAppRelRepositoryMixin<
  SomeEnitty,
  typeof SomeEnitty.prototype.id,
  SomeEnittyRelations,
  Constructor<QueryEnhancedCrudRepository<SomeEnitty, typeof SomeEnitty.prototype.id, SomeEnittyRelations>>
>(QueryEnhancedCrudRepository) {
  constructor(
    @inject('datasources.db')
    dataSource: juggler.DataSource,
    // Required
    @repository.getter('AclAppRepository')
    public getAclAppRepository: Getter<AclAppRepository>,
  ) {
    super(SomeEnitty, dataSource);
  }
}
  1. Define the custom entity policy and the global app policy
  • app.policy.ts
// Define the global app policy
export const AppRoles = {
  admin: 'admin',
  user: 'user',
};

export type AppRoles = keyof typeof AppRoles;

export const AppPolicy = defineResourcePolicy({
  model: AclApp,
  roles: ['admin', 'member'],
});
  • some.policy.ts
// Define the custom entity policy
export const SomePolicy = defineResourcePolicy({
  model: SomeEntity,
  roles: ['owner', 'member'],
  relations: ['$app'],
  actions: ['read', 'create', 'delete'],
  roleActions: {
    owner: ['create', 'delete'],
    member: ['read'],
  },
  roleDerivations: {
    owner: ['$app.admin'],
    member: ['owner'],
  },
});
  1. Granting and authorizing
import {GlobalApp} from '@microloop/acl-global';

import {Acl, AclBindings} from '@bleco/acl';

const acl = await app.get<Acl>(AclBindings.ACL);
const roleMappingService = await app.get<AclRoleMappingService>(AclBindings.ROLE_MAPPING_SERVICE);

// Create a custom resource associating with the global app
const someResource = await someRepo.create({$appId: GlobalApp.id /*...*/});

// Grant app admin to someUser
await roleMappingService.add(someUser, AppRoles.admin, GlobalApp);

// Authorize someUser to create someEntity
await acl.authorize(someUser, 'create', someResource); // -> OK
await acl.authorize(someUser2, 'create', someResource); // -> Forbidden

License

Licensed under the MIT license.

Readme

Keywords

none

Package Sidebar

Install

npm i @microloop/acl-global

Weekly Downloads

1

Version

0.4.4

License

MIT

Unpacked Size

9.27 kB

Total Files

12

Last publish

Collaborators

  • towyuan