Gate is an authorization module for NestJS.
$ npm install --save nestjs-gate
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()
- Author - Rahul Kadyan
- Twitter - @znck0
NestJS Gate is MIT licensed.