Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/iamolegga/nestjs-roles
Type safe roles guard and decorator made easy
https://github.com/iamolegga/nestjs-roles
nest nestjs rbac roles
Last synced: 7 days ago
JSON representation
Type safe roles guard and decorator made easy
- Host: GitHub
- URL: https://github.com/iamolegga/nestjs-roles
- Owner: iamolegga
- License: mit
- Created: 2019-11-05T19:17:53.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2024-10-29T02:26:45.000Z (about 2 months ago)
- Last Synced: 2024-10-29T17:23:21.813Z (about 2 months ago)
- Topics: nest, nestjs, rbac, roles
- Language: TypeScript
- Homepage:
- Size: 4.09 MB
- Stars: 220
- Watchers: 5
- Forks: 12
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome - iamolegga/nestjs-roles - Type safe roles guard and decorator made easy (TypeScript)
README
nestjs-roles
Type safe roles guard with the decorator for controller made easy. Just specify how to get `role` from `ExecutionContext`. `nestjs-roles` will do the rest.
## Install
```sh
npm i nestjs-roles
```## Example
First, let's define roles:
```ts
// role.enum.tsexport enum Role {
ADMIN = 'ADMIN',
USER = 'USER',
MODERATOR = 'MODERATOR',
}
```Let's say you use [nestjs-session](http://npm.im/nestjs-session) and keep `role` in `session` property object of `request`. So then create guard with `getRole` callback:
```ts
// roles.guard.tsimport { ExecutionContext } from '@nestjs/common';
import { createRolesGuard } from 'nestjs-roles';
import { Role } from './role.enum';function getRole(context: ExecutionContext) {
const { session } = context.switchToHttp().getRequest();if (!session) return;
// you can use single role or array of roles
// if you provide array of roles, the guard will pass if one of roles is in required roles
return (session as { role?: Role | Role[] }).role;
}export const Roles = createRolesGuard(getRole);
```After that we can set `Roles` guard globally (don't forget to pass `Reflector` instance):
```ts
// bootstrap.tsimport { NestFactory, Reflector } from '@nestjs/core';
import { Roles } from './roles.guard';const app = await NestFactory.create(AppModule);
const reflector = app.get(Reflector);
app.useGlobalGuards(new Roles(reflector));
```All settings are done. Now you can set up access in your controllers:
```ts
// secrets.controller.tsimport { Roles } from './roles.guard';
@Controller('secrets')
@Roles.Params(true) // setup access on Controller for users with any existing role
export class SecretsController {@Get('my')
async readMy() {
// ...
}@Patch(':id')
@Roles.Params(Role.ADMIN) // override access on certain handler
async update() {
// ...
}
}
```Do you use this library?
Don't be shy to give it a star! ★Also if you are into NestJS you might be interested in one of my other NestJS libs.