// src/auth/roles.enum.ts
export enum Role {
USER = 'user',
MODERATOR = 'moderator',
ADMIN = 'admin',
}
// src/auth/roles.decorator.ts
import { SetMetadata } from '@nestjs/common';
import { Role } from './roles.enum';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
// src/auth/interfaces/user.interface.ts
export interface RequestUser {
sub: string; // user ID
username: string;
roles: Role[];
}
// src/auth/guards/roles.guard.ts
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../roles.decorator';
import { Role } from '../roles.enum';
import { RequestUser } from '../interfaces/user.interface';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user: RequestUser = request.user;
return requiredRoles.some((role) => user.roles?.includes(role));
}
}
// src/auth/guards/jwt-auth.guard.ts (example JWT guard, assuming @nestjs/jwt and @nestjs/passport are installed)
// This is a basic JWT guard. Customize your JWT strategy to populate request.user with roles.
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
handleRequest(err: any, user: any) {
if (err || !user) {
throw err || new UnauthorizedException('Unauthorized');
}
return user;
}
}
// src/app.module.ts (or auth.module.ts)
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { JwtModule } from '@nestjs/jwt';
// ... other imports
import { RolesGuard } from './auth/guards/roles.guard';
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard'; // Optional global, but better per-route
@Module({
imports: [
JwtModule.register({
secret: 'your-secret', // Use env vars in production
signOptions: { expiresIn: '1h' },
}),
// PassportModule, etc.
],
providers: [
// Optional: Make RolesGuard global (applies to all routes, skips if no @Roles)
{
provide: APP_GUARD,
useClass: RolesGuard,
},
],
})
export class AppModule {}
// src/users/users.controller.ts (example usage)
import { Controller, Get, UseGuards } from '@nestjs/common';
import { RolesGuard } from '../auth/guards/roles.guard';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { Roles } from '../auth/roles.decorator';
import { Role } from '../auth/roles.enum';
@Controller('users')
export class UsersController {
// Public route (no guards)
@Get('profile')
getProfile() {
return { message: 'Public profile' };
}
// Authenticated users only
@UseGuards(JwtAuthGuard)
@Get('my-profile')
getMyProfile() {
return { message: 'Authenticated user profile' };
}
// Users or Moderators
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.USER, Role.MODERATOR)
@Get('moderate')
moderate() {
return { message: 'User/Moderator action' };
}
// Admins only (roles checked on method or class level)
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMIN)
@Get('admin')
adminOnly() {
return { message: 'Admin action' };
}
}
Setup Instructions
-
Install dependencies:
npm i @nestjs/jwt @nestjs/passport passport passport-jwt @nestjs/core
npm i -D @types/passport-jwt
-
JWT Strategy (in auth/jwt.strategy.ts):
- Implement
PassportStrategy(Strategy) to validate JWT and return RequestUser with roles array from your DB/user service.
- Example payload:
{ sub: 'userId', username: 'john', roles: [Role.USER] }.
-
Usage Notes:
- Order matters:
JwtAuthGuard first (authenticates), then RolesGuard (authorizes).
- Class-level roles: Apply
@Roles(Role.ADMIN) on controller class for all methods.
- Public routes: Skip guards entirely.
- Multiple roles:
@Roles(Role.USER, Role.ADMIN) allows any match.
- Global guards: Optional for convenience; use
Reflect to skip if no metadata.
- Permissions: Extend to permissions (e.g.,
@Permissions('create:post')) by changing metadata to string arrays.
- Testing: Use tools like Postman with JWT tokens containing roles.
This is a production-ready, scalable RBAC implementation. Customize based on your user service (e.g., Prisma, TypeORM). For full JWT setup, see NestJS docs: Authentication.