### Installation Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Command to install the nest-authz package. ```bash $ npm install --save nest-authz ``` -------------------------------- ### Module Registration Example 1 Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Example of registering AuthZModule with model and policy paths, including custom user and resource context functions. ```typescript import { AuthZModule, AuthPossession } from 'nest-authz'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ AuthZModule.register({ model: 'model.conf', policy: TypeORMAdapter.newAdapter({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'password', database: 'nestdb' }), userFromContext: (ctx) => { const request = ctx.switchToHttp().getRequest(); return request.user && request.user.username; }, resourceFromContext: (ctx, perm) => { const request = ctx.switchToHttp().getRequest(); return { type: perm.resource, id: request.id }; } }), ], controllers: [AppController], providers: [AppService] }) ``` -------------------------------- ### Module Registration Example 2 (Preferred) Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Example of registering AuthZModule using an enforcerProvider, preferred for its flexibility, with custom user context function. ```typescript import { AuthZModule, AUTHZ_ENFORCER } from 'nest-authz'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule, ConfigService } from './config.module'; import * as casbin from 'casbin'; @Module({ imports: [ ConfigModule, AuthZModule.register({ imports: [ConfigModule], enforcerProvider: { provide: AUTHZ_ENFORCER, useFactory: async (configSrv: ConfigService) => { const config = await configSrv.getAuthConfig(); return casbin.newEnforcer(config.model, config.policy); }, inject: [ConfigService], }, userFromContext: (ctx) => { const request = ctx.switchToHttp().getRequest(); return request.user && { username: request.user.username, isAdmin: request.user.isAdmin }; } }), ], controllers: [AppController], providers: [AppService] }) ``` -------------------------------- ### Using AuthZRBACService Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Example demonstrating how to inject and use AuthZRBACService to check user permissions for a specific action. ```typescript import { Controller, Get, UnauthorizedException, Req } from '@nestjs/common'; import { AuthZGuard, AuthZRBACService, AuthActionVerb, AuthPossession, UsePermissions } from 'nest-authz'; @Controller() export class AppController { constructor(private readonly rbacSrv: AuthZRBACService) {} @Get('users') async findAllUsers(@Req() request: Request) { let username = request.user['username']; // If there is a policy `p, root, user, read:any` in policy.csv // then user `root` can do this operation // Using string literals for simplicity. const isPermitted = await this.rbacSrv.hasPermissionForUser(username, "user", "read:any"); if (!isPermitted) { throw new UnauthorizedException( 'You are not authorized to read users list' ); } // A user can not reach this point if he/she is not granted for permission read users // ... } } ``` -------------------------------- ### Using @UsePermissions Decorator with resourceFromContext Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Example of using 'resourceFromContext' to dynamically determine the resource based on the request context. ```typescript @UsePermissions({ action: AuthActionVerb.READ, resource: 'User', resourceFromContext: (ctx, perm) => { const req = ctx.switchToHttp().getRequest(); return { type: perm.resource, id: req.id }; } }) async userById(id: string) {} ``` -------------------------------- ### Using AuthZService for In-Method Permission Checks Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Example of injecting and using AuthZService within a controller method to perform permission checks. ```typescript import { Controller, Get, UnauthorizedException, Req } from '@nestjs/common'; import { AuthZGuard, AuthZService, AuthActionVerb, AuthPossession, UsePermissions } from 'nest-authz'; @Controller() export class AppController { constructor(private readonly authzSrv: AuthZService) {} @Get('users') async findAllUsers(@Req() request: Request) { let username = request.user['username']; // If there is a policy `p, root, user, read:any` in policy.csv // then user `root` can do this operation // Using string literals for simplicity. const isPermitted = await this.authzSrv.hasPermissionForUser(username, "user", "read:any"); if (!isPermitted) { throw new UnauthorizedException( 'You are not authorized to read users list' ); } // A user can not reach this point if he/she is not granted for permission read users // ... } } ``` -------------------------------- ### Using @UsePermissions Decorator with Basic Permissions Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Example of applying the @UsePermissions decorator to a NestJS route to enforce read permissions on 'USER' resource. ```typescript @Get('users') @UseGuards(AuthZGuard) @UsePermissions({ action: AuthActionVerb.READ, resource: 'USER', possession: AuthPossession.ANY }) async findAllUsers() {} ``` -------------------------------- ### Using @UsePermissions Decorator with Multiple Permissions Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Shows how to apply multiple permission checks to a single route, requiring all to be satisfied. ```typescript @UsePermissions({ action: AuthActionVerb.READ, resource: 'USER_ADDRESS', possession: AuthPossession.ANY }, { action; AuthActionVerb.READ, resource: 'USER_ROLES', possession: AuthPossession.ANY }) ``` -------------------------------- ### Using @UsePermissions Decorator with Object Resource Source: https://github.com/apache/casbin-nest-authz/blob/master/README.md Demonstrates using an object for the 'resource' property in @UsePermissions to support ABAC models. ```typescript @UsePermissions({ action: AuthActionVerb.READ, resource: {type: 'User', operation: 'single'}, possession: AuthPossession.ANY }) async userById(id: string) {} @UsePermissions({ action: AuthActionVerb.READ, resource: {type: 'User', operation: 'batch'}, possession: AuthPossession.ANY }) async findAllUsers() {} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.