0.2.0 • Published 6 years ago

nest-dynamic-permission v0.2.0

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

Description

This is a Nest module for making config permission easier.

Installation

$ npm i --save nest-dynamic-permission

Quick Start

Import Module

import { Module } from '@nestjs/common';
import { PermissionModule } from 'nest-dynamic-permission';
import { UserController } from './controllers/UserController';
import { RoleController } from './controllers/RoleControllers';

@Module({
  imports: [PermissionModule.forRoot({UserController, RoleController})],
})
export class ApplicationModule {}

Injection

PermissionService:

import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectDynamicPermission, DynamicPermission } from 'nest-dynamic-permission';

@Injectable()
export class PermissionService implements OnModuleInit{
  constructor(
      @InjectDynamicPermission() private readonly permission: DynamicPermission,
  ) {}
  
  onModuleInit(): any {
      this.permission.collect(async routes => {
          // You can save routes data to db.
      }, 5000);
  }
}

PermissionInterceptor:

import { Injectable, NestInterceptor, ExecutionContext, Observable, ForbiddenException } from '@nestjs/common';
import { InjectDynamicPermission, DynamicPermission } from 'nest-dynamic-permission';

@Injectable()
export class PermissionInterceptorCls implements NestInterceptor {
    constructor(
          @InjectDynamicPermission() private readonly permission: DynamicPermission,
    ) {
        // You can import routes from db use this function.
        // permission.importRoutes([]);
        permission.importPermissions([{role: 'admin', key: 'createUser', strategy: 'forbidden'}]);
    }
      
    intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
        const request = context.switchToHttp().getRequest();
        const role = 'admin';

        
        if (!this.permission.valid(role, request.method, request.url)) {
            throw new ForbiddenException('No api permission')
        }
        return call$;
    }
}

Stay in touch

License

Nest is MIT licensed.