npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

acl-nest

v1.4.0

Published

ACL nestjs module functionality using casbin package

Downloads

480

Readme

ACL Nest

Package version Package types definitions Package types definitions Top language Package downloads

ACL nestjs module functionality using casbin package.

Install package from npm.

npm i acl-nest --save

Usage

Module registration

First, register AccessControlModule into your App/Root module.

import {Module} from "@nestjs/common";
import {AccessControlModule} from "acl-nest/AccessControlModule";
import * as path from "path";

@Module({
  imports: [
    AccessControlModule.register(
      'path to your model config or function wich returns model as text',
      'path to your policy config or function wich returns policy as text',
      (params, context, accessControlService)=>{
        const request = context.switchToHttp().getRequest();
        request.user = request.headers['x-user'] // here you can do any custom logic
        return accessControlService.hasPermission([request.user, ...params])
      }
    )
  ],
  controllers: [YourController]
})
export class CustomTestingModule{}

Note: Example of casbin configurations can be found here

Adding controller

Decorate you controller methods

@Controller()
export class YourController {
  @Get('getName')
  @AccessControlAction(['name', 'read']) // this params are based on you model
  public getName(): string {
    return 'Bob'
  }
}

Custom validation function

You can specify and override your validation logic if you need it. Just define the function for validation the same as it is in the register module action.

@Controller()
export class YourController {
    @Get('getLastName')
    @AccessControlAction(['name', 'read'], (params, context, accessControlService) => {
      const request = context.switchToHttp().getRequest();
      return accessControlService.hasPermission([request.headers['x-user-name'], ...params])
    })
    public getLastName(): string {
      return 'Wick'
    }
}

Direct call of AccessControlService logic

Sometimes you need to check permission in the profound context of your application. In this case, you can use AccessControlService directly. Just inject AccessControlService.

@Controller()
export class YourController {

    public constructor(
      private readonly accessControlService: AccessControlService
    ) {
    }

    @Get('getAge')
    public async getAge(
      @Req() request: Request
    ): Promise<number> {
      // we need to call checkPermission instead of hasPermission
      // because check permission will throw same Error as Guard used in decorators, instead or returning boolean
      await this.accessControlService.checkPermission([request.headers['x-user'], 'age', 'read'])
      return 32;
    }
}

Advanced usage

More complex logic before handling permissions

Sometimes is necessary to load some user data, or handle some requests to auth users before checking permissions. But the registered validation function has available only ExecutionContext which cannot help us to get some other service to load users for example. A good approach here is to use middleware executed before Guards or register modules asynchronously.

1. Register Module asynchronous with injected dependencies

@Module({
  imports: [
    AccessControlModule.registerAsync({
      inject: [UserService], // you can inject anything here
      useFactory: (userService: UserService) => {
        return {
          modelPath: path.join(__dirname, '..', 'config', 'model.test.conf'),
          policyPath: path.join(__dirname, '..', 'config', 'policy.test.conf'),
          validationFunction: async (params, context, accessControlService) => {
            const request = context.switchToHttp().getRequest();
            const userName = await userService.getUserFromRequest(request) // you can use injected service
            return accessControlService.hasPermission([userName, ...params])
          },
        }
      }
    })
  ],
})
export class TestingModuleAsync {
}

2. Middleware usage

First create middleware
@Injectable()
export class UserMiddleware implements NestMiddleware {

  constructor(
    private readonly userService: UserService
  ) {}

  public async use(req: any, res: any, next: () => void): Promise<any> {
    req.userEntity = await this.userService.loadUser()
    next()
  }

}
Register middleware and write your validation function
@Module({
  imports: [
    AccessControlModule.register(
      'path to your model config or function wich returns model as text',
      'path to your policy config or function wich returns policy as text',
      (params, context, accessControlService) => {
        const request = context.switchToHttp().getRequest();
        return accessControlService.hasPermission([request.userEntity.name, ...params])
      }
    )
  ],
  providers: [UserService],
})
export class YourModule implements NestModule {
  configure(consumer: MiddlewareConsumer): any {
    consumer
      .apply(UserMiddleware)
      .forRoutes('*')
  }
}

Multiple parameters

You can even specify multiple parameters like objects, and actions from a model.

@Controller()
export class YourController {

  @Get('getNameAndAge')
  @AccessControlAction([['name', 'age'], 'read'])
  public getNameAndAge(): string {
    return 'Bob 32'
  }

  @Get('writeNameAndAge')
  @AccessControlAction([['name', 'age'], ['read', 'write']])
  public writeNameAndAge(): string {
    return 'Bob 32 written'
  }
}

In this case, all combinations of specified parameters will be checked. The reason why this functionality was created is to have the option to check all permissions without specifying unnecessary aliases for other model properties.