@ttou/nest-casbin
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.1 • Public • Published

    安装

    npm install --save @ttou/nest-casbin casbin typeorm-adapter

    快速开始

    import { Module } from '@nestjs/common'
    import { CasbinModule } from 'nest-winston'
    import * as winston from 'winston'
    
    @Module({
      imports: [
        CasbinModule.forRoot({
          // 模块配置
        })
      ]
    })
    export class AppModule {}

    异步配置

    import { Module } from '@nestjs/common'
    import { CasbinModule } from '@ttou/nest-casbin'
    
    @Module({
      imports: [
        CasbinModule.forRootAsync({
          useFactory: () => ({
            // options
          }),
          inject: []
        })
      ]
    })
    export class AppModule {}

    另外, 也可以使用 useClass 语法:

    CasbinModule.forRootAsync({
      useClass: WinstonConfigService
    })

    Restful 守卫示例

    model.conf

    [request_definition]
    r = sub, obj, act
    
    [policy_definition]
    p = sub, obj, act
    
    [policy_effect]
    e = some(where (p.eft == allow))
    
    [matchers]
    m = r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)
    

    restful.guard.ts

    import {
      CanActivate,
      ExecutionContext,
      ForbiddenException,
      Inject,
      Injectable
    } from '@nestjs/common'
    import { CasbinModule } from '@ttou/nest-casbin'
    
    @Injectable()
    export class RestfulGuard implements CanActivate {
      canActivate(context: ExecutionContext) {
        const req = context.switchToHttp().getRequest()
        const { url, method } = req
        const user = req.user
    
        const path = url.split('?')[0]
        const isAllowed = CasbinModule.enforcer.enforceSync(
          user.username,
          path,
          method
        )
    
        if (isAllowed) {
          return true
        }
    
        throw new ForbiddenException()
      }
    }

    Keywords

    Install

    npm i @ttou/nest-casbin

    DownloadsWeekly Downloads

    6

    Version

    1.0.1

    License

    MulanPSL2

    Unpacked Size

    20.6 kB

    Total Files

    11

    Last publish

    Collaborators

    • avatar