Skip to content

RBAC (Role Based Access Control)

RBAC is a method of restricting access based of user role. This is a common method of access control in application.

How it works

  1. User login to the application
  2. User will have a role assigned to them
  3. User will have access to certain feature based on their role

How to manage RBAC

Role management stored in database at table role

prisma
model role {
  id          String   @id @default(cuid())
  name        String   @unique
  description String?
  created_at  DateTime @default(now())
  updated_at  DateTime @updatedAt

  user_roles user_roles[]
}

model user_roles {
  id      String @id @default(cuid())
  user_id String
  role_id String

  user user @relation(fields: [user_id], references: [id], onDelete: Cascade, onUpdate: Cascade)
  role role @relation(fields: [role_id], references: [id], onDelete: Cascade, onUpdate: Cascade)

  @@unique([user_id, role_id])
}

How to Setup RBAC on API Endpoint

First, create a API endpoint that need to be protected

typescript
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) { }

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }
}

Then, add a decorator @RequireAuthWlRoles to the endpoint

typescript
@RequireAuthWlRoles(['admin'])
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) { }
  ...
}

That's it, now you have protected the endpoint with RBAC. Only user with role admin can access the endpoint.

Whitelist and blacklist role

@RequireAuthWlRoles is a Whitelist (Wl) Role, it means that only user with the role specified in the array can access the endpoint.

If you want to use Blacklist (Bl) Role, you can use @RequireAuthBlRoles decorator.