{"_id":"@beamnetwork/eco-nest-authz","_rev":"31-eb75d3a3c68762c0effb6eb50b3f3c81","name":"@beamnetwork/eco-nest-authz","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@beamnetwork/eco-nest-authz","version":"1.0.0","keywords":[],"author":{"name":"dreamdevil00"},"license":"MIT","_id":"@beamnetwork/eco-nest-authz@1.0.0","maintainers":[{"name":"mattfysh","email":"mattfysh@gmail.com"},{"name":"yabloki","email":"kirill@beam.io"},{"name":"tastycode","email":"tastycode@protonmail.com"},{"name":"thorvald","email":"thorvald@natvig.com"},{"name":"mgregson","email":"mgregson@gregson.io"},{"name":"stoyand","email":"stoyan@beam.io"},{"name":"aleph2012","email":"satish@beam.io"}],"homepage":"https://github.com/dreamdevil00/nest-authz#readme","bugs":{"url":"https://github.com/dreamdevil00/nest-authz/issues"},"dist":{"shasum":"d5bef3f8026770643905bc471feebc96ca143db3","tarball":"https://registry.npmjs.org/@beamnetwork/eco-nest-authz/-/eco-nest-authz-1.0.0.tgz","fileCount":59,"integrity":"sha512-KjMZ/MgQF4OYeH8xa5AbM4TThXG6LIOxxMVkdYdfqaKmyRGqDI4ff7rUSS1MDfQyGwQDuMNPVm1Z1jlFwvVPCA==","signatures":[{"sig":"MEQCIDSAvmfQVXD/BQ1ClfaFt5kKiNvZr6p81uEu1yozcjb8AiBrhYwrNx0OfcEdyLwd84T3QD9j6MO0Ehtpr046zzrDOg==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":102017,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJh2BaACRA9TVsSAnZWagAATc8QAIiBsH/9senIykJWlwKP\nGyWkuSlGNpwEh8B0j5wrVyDXNKAc3YsUfVr4+Jx5mdxCFYRDImyadUOSVY87\n4hAVZWF8dAhquv7gej2LNJHCotpmzmJYXNfT5OAr2ZkzKRUfu6T39sXXBPh8\nHqrlPqZL05Eg9JXQgtihDN4Btr9f/tbQjzyQ5RL3nSFpxKYzDIhJpFc676tB\njgBeyzOPobfc/Mnwh7Q1SYUIJ2gddHykuXrbellZwWoXgqom4J6e5MtFzzX+\n5cCy32fAVMp6FnXJvn10PrQJUpSjl1YzK3otj1QiGD/Zxdno7bs9Ibx5bUpt\nyEXLAoy3xOFX0EbdHsUzK/hn0Tr02r64J7DjMNz1kldjzU9A4jll9CN0/W6o\n0scmL7gy2vPGNNHEr1I5Xhds1NQwm2E9+jcM/pF/r7clj0FTGk1pu9iv/sAP\nBL0xE0ihQNv6owY3ZknHlF/Ed4DEVzi+zYbFeeYuoGtmFWtfPj4VLby7enLN\np31q/TQvm8dfCil9zoCtmCTWHFsw2y8lomLg6y7CoL4BRYxWNfiVLzvzYmMp\n4gaj5m17iHSfz6galJPjQJlxheZe4QJM4rElMx1AQyO/WCQYd3UrsYN0jMcD\nuxeUgWkjTAAk9vJnw5evKXJTGNcTcj3UwyLm+fiVdr+OJUrewpS+vt3TEERD\n53nw\r\n=QMiE\r\n-----END PGP SIGNATURE-----\r\n"},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":">=8.9.0"},"gitHead":"1896dbcb8c43ae687aae8bc15d381b148c818fd3","scripts":{"lint":"tslint -p tsconfig.json -c tslint.json","test":"jest","build":"rimraf dist && tsc -p tsconfig.json","clean":"rimraf dist","format":"prettier --write \"src/**/*.ts\"","release":"standard-version","prepublish":"yarn lint && yarn build"},"_npmUser":{"name":"aleph2012","email":"satish@beam.io"},"repository":{"url":"git+https://github.com/dreamdevil00/nest-authz.git","type":"git"},"_npmVersion":"6.11.3","description":"基于 node-casbin 实现的 RBAC 权限控制模块。","directories":{"test":"test"},"_nodeVersion":"12.11.0","dependencies":{"casbin":"^4.2.1"},"_hasShrinkwrap":false,"devDependencies":{"jest":"24.9.0","rxjs":"6.5.4","rimraf":"3.0.1","tslint":"5.11.0","ts-jest":"24.3.0","ts-node":"8.6.2","prettier":"1.19.1","typescript":"3.7.5","@types/jest":"24.9.0","@types/node":"11.15.4","@nestjs/core":"6.11.11","@nestjs/common":"6.11.11","reflect-metadata":"0.1.13","standard-version":"7.1.0"},"peerDependencies":{"rxjs":"^6.2.2","@nestjs/core":"^6.0.0","@nestjs/common":"^6.0.0","reflect-metadata":"^0.1.12"},"_npmOperationalInternal":{"tmp":"tmp/eco-nest-authz_1.0.0_1586450489437_0.058076676487373025","host":"s3://npm-registry-packages"}}},"time":{"created":"2020-04-09T16:41:29.437Z","modified":"2026-08-13T14:00:01.105Z","1.0.0":"2020-04-09T16:41:29.596Z"},"bugs":{"url":"https://github.com/dreamdevil00/nest-authz/issues"},"author":{"name":"dreamdevil00"},"license":"MIT","homepage":"https://github.com/dreamdevil00/nest-authz#readme","keywords":[],"repository":{"url":"git+https://github.com/dreamdevil00/nest-authz.git","type":"git"},"description":"基于 node-casbin 实现的 RBAC 权限控制模块。","maintainers":[{"email":"satish@beam.io","name":"aleph2012"},{"email":"mdavid@eco.com","name":"mdavid123"},{"email":"matt@eco.com","name":"seveyeco"}],"readme":"# nest-authz\n\nA access control library for [NestJS](https://nestjs.com/) which built on [node-casbin](https://github.com/casbin/node-casbin).\n\nCasbin is a powerful and efficient open-source access control library. It provides support for enforcing authorization based on various access control models like ACL, RBAC, ABAC. For detailed info, check out the [official docs](https://casbin.org/en/)\n\n## How to use\n\n### Installation\n\n```bat\n$ npm install --save nest-authz\n```\n\n### Define Access Control Model\n\nFirstly, you should create your own casbin access control model. Checkout [related docs](https://github.com/casbin/node-casbin#supported-models) if you have not.\n\n### Initialization\n\nRegister nest-authz with options in the AppModule as follows:\n\n```\nAuthZModule.register(options)\n```\n\n`options` is an object literal containing options.\n\n- `model` is a path string to the casbin model.\n- `policy` is a path string to the casbin policy file or adapter\n- `usernameFromContext` (REQUIRED) is a function that accepts `ExecutionContext`(the param of guard method `canActivate`) as the only parameter and returns either the username as a string or null. The `AuthZGuard` uses username to determine user's permission internally.\n- `enforcerProvider` Optional enforcer provider\n- `imports` Optional list of imported modules that export the providers which   are required in this module.\n\nThere are two ways to configure enforcer, either `enforcerProvider`(optional with `imports`) or `model` with `policy`\n\nAn example configuration which reads username from the http request.\n\n```typescript\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [\n    AuthZModule.register({\n      model: 'model.conf',\n      policy: TypeORMAdapter.newAdapter({\n        name: 'casbin',\n        type: 'mysql',\n        host: 'localhost',\n        port: 3306,\n        username: 'root',\n        password: 'password',\n        database: 'nestdb'\n      }),\n      usernameFromContext: (ctx) => {\n        const request = ctx.switchToHttp().getRequest();\n        return request.user && request.user.username;\n      }\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService]\n})\n```\n\nor\n\n```typescript\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ConfigModule, ConfigService } from './config.module';\nimport { AUTHZ_ENFORCER } from 'nest-authz';\n\n@Module({\n  imports: [\n    ConfigModule,\n    AuthZModule.register({\n      imports: [ConfigModule],\n      enforcerProvider: {\n        provide: AUTHZ_ENFORCER,\n        useFactory: async (configSrv: ConfigService) => {\n          const config = await configSrv.getAuthConfig();\n          return casbin.newEnforcer(config.model, config.policy);\n        },\n        inject: [ConfigService],\n      },\n      usernameFromContext: (ctx) => {\n        const request = ctx.switchToHttp().getRequest();\n        return request.user && request.user.username;\n      }\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService]\n```\n\nThe latter one is preferred.\n\n### Checking Permissions\n\n#### Using `@UsePermissions` Decorator\n\nThe `@UserPermissions` decorator is the easiest and most common way of checking permissions. Consider the method shown below:\n\n```typescript\n  @Get('users')\n  @UseGuards(AuthZGuard)\n  @UsePermissions({\n    action: AuthActionVerb.READ,\n    resource: 'USER',\n    possession: AuthPossession.ANY\n  })\n  async findAllUsers() {}\n\n```\n\nThe `findAllUsers` method can not be called by a user who is not granted the permission to read any user.\n\nThe value of property `resource` is a magic string just for demonstrating. In the real-world applications you should avoid magic strings. Resources should be kept in the separated file like `resources.ts`\n\nThe param of `UsePermissions` are some objects with required properties `action`、 `resource`、 `possession` and an optional `isOwn`.\n\n- `action` is an enum value of `AuthActionVerb`.\n- `resource` is a resource string the request is accessing.\n- `possession` is an enum value of `AuthPossession`.\n- `isOwn` is a function that accepts `ExecutionContext`(the param of guard method `canActivate`) as the only parameter and returns boolean. The `AuthZGuard` uses it to determine whether the user is the owner of the resource. A default `isOwn` function which returns `false` will be used if not defined.\n\nYou can define multiple permissions, but only when all of them satisfied, could you access the route. For example:\n\n```\n@UsePermissions({\n  action: AuthActionVerb.READ,\n  resource: 'USER_ADDRESS',\n  possession: AuthPossession.ANY\n}, {\n  action; AuthActionVerb.READ,\n  resource: 'USER_ROLES,\n  possession: AuthPossession.ANY\n})\n```\n\nOnly when the user is granted both permissions of reading any user address and reading any roles, could he/she access the route.\n\n#### Using `AuthzRBACService` or `AuthzManagementService`\n\nWhile the `@UsePermissions` decorator is good enough for most cases, there are situations where we may want to check for a permission in a method's body. We can inject and use `AuthzRBACService` or `AuthzManagementService` which are wrappers of casbin api for that as shown in the example below:\n\n```typescript\nimport { Controller, Get, UnauthorizedException } from '@nestjs/common';\nimport {\n  AuthZGuard,\n  AuthZRBACService,\n  AuthActionVerb,\n  AuthPossession,\n  UsePermissions\n} from 'nest-authz';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly rbacSrv: AuthZRBACService) {}\n\n  @Get('users')\n  async findAllUsers() {\n    const isPermitted = await this.rbacSrv.hasPermissionForUser();\n    if (!isPermitted) {\n      throw new UnauthorizedException(\n        'You are not authorized to read users list'\n      );\n    }\n    // A user can not reach this point if he/she is not granted for permission read users\n  }\n}\n```\n\n## Example\n\nFor more detailed information, checkout the working example in\ndirectory `/example`\n\n## License\n\nThis project is licensed under the MIT license.\n\n## Contact\n\nIf you have any issues or feature requests, contact me. PR is welcomed.\n\n- dreamdeviloo@163.com\n","readmeFilename":"README.md"}