@microloop/acl-global
v0.4.4
Published
A extension library for @bleco/acl to simplify global roles usage
Downloads
7
Readme
@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
- 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) {
// ...
}
- 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);
}
}
- 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'],
},
});
- 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.