fw-rolepermission
v1.0.3
Published
Nest JS FW packages
Downloads
3
Readme
Description
Nest JS based Permission based authorization module
installation
npm install --save nestjs-rolepermission
Usage
1. Module configuration
import {RolePermissionModule} from "nestjs-rolepermission"
@Module({
imports: [
RolePermissionModule.forRootAsync(RolePermissionDataService),
],
controllers: []
})
export class AppModule {}
2. implement RolePermissionDataService
This service responsible to provide role and permission data to the package in RolePermissionData
format. Developer will implement this service using IRolePermissionDataService
pull the role prmission data from external source or configure static data in RolePermissionData
under getRolePermissionData() method
. please follow the code snipt below.
import { Injectable } from "@nestjs/common";
import { IRolePermissionDataService, RolePermissionData } from "nestjs-rolepermissions";
@Injectable()
export class RolePermissionDataStorageService
implements IRolePermissionDataService {
getRolePermissionData(): RolePermissionData {
return {
roles: ["admin"],
permissions: ["addadmin", "one", "two", "three"],
mapping: [
{
role: "admin",
permissions: ["addadmin"],
},
],
};
}
}
RolePermissionData
export interface RolePermissionData {
roles: string[];
permissions: string[];
mapping: RolePermissionMapping[];
}
RolePermissionData consists of the following keys:
- roles: string array of roles.
- permissions: string array of permissions.
- mapping: array of RolePermissionMapping objects.
3. Setup guard to check authorizatioin
Authorization Controller level
For implementing permission authorization globally for all methods of the controller then instead of defining at method level just declare RolePermissionGuard at controller and define permission like in snipt below.
import { RolePermissionGuard, RolePermissions } from "fw-permissions";
@Controller("user")
@UseGuards(RolePermissionGuard)
@RolePermissions("one")
export class UserController {
@UseGuards(RolePermissionGuard) // permission guard
@RolePermissions("addadmin") // permissions array. action executes only if role has the permission.
@Get("/index")
index() {
return "Welcome to Pooja Loyalty";
}
}
Authorization method level For implementing permission authorization only to sepefic action then declare RolePermissionGuard and RolePermissions like in code snippet below.
import { RolePermissionGuard, RolePermissions } from "fw-permissions";
@Controller("user")
export class UserController {
@UseGuards(RolePermissionGuard) // permission guard
@RolePermissions("addadmin") // permissions array. action executes only if role has the permission.
@Get("/index")
index() {
return "Welcome to Pooja Loyalty";
}
}