Skip to content

znckco/nestjs-gate

Repository files navigation

NestJS Gate

NPM Contributor Covenant CI codecov

Description

Gate is an authorization module for NestJS.

Installation

$ npm install --save nestjs-gate

Quick Start

import { GateModule, Gate, Policy } from "nestjs-gate"
import { Module, Injectable, Controller } from "@nestjs/common"
import { NestFactory } from "@nestjs/core"

// 1. Create policy
@Injectable()
class ResourcePolicy {
  update(user: any, resource: Resource) {
    return true // Check if "user" can update "resource"
  }
}

// 2. Register policy
@Policy(ResourcePolicy)
class Resource {}

// 3. Use Gate for authorization
@Injectable()
class ExampleService {
  async update(resource: Resource) {
    if (await Gate.allows("update", resource)) {
      // Yes, update is allowed.
    } else {
      // No, throw forbidden error.
    }
  }
}

// 3. Use Gate with pipe transform
@Controller()
class ExampleController {
  @Post("/update")
  async update(@Param("id", /* id -> resource */ , can("update")) resource: Resource) {
      // Yes, update is allowed.
  }
}

// 4. Import GateModule and provide your polices.
@Module({ imports: [GateModule], providers: [ResourcePolicy, ExampleService] })
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule)
  await app.listen(3000)
}

bootstrap()

Stay in touch

License

NestJS Gate is MIT licensed.