roles.guard.ts
nest.js/02-intermediate/code/auth/guards/roles.guard.ts
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.get<string[]>(
ROLES_KEY,
context.getHandler(),
);
if (!requiredRoles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
if (!user) {
throw new ForbiddenException('User not authenticated');
}
const hasRole = requiredRoles.some((role) => user.roles?.includes(role));
if (!hasRole) {
throw new ForbiddenException('Insufficient permissions');
}
return true;
}
}
관련 글
app.controller.ts
app.controller.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.controller.ts).
글 읽기 →app.module.ts
app.module.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.module.ts).
글 읽기 →app.service.ts
app.service.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.service.ts).
글 읽기 →main.ts
main.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/main.ts).
글 읽기 →todos.controller.ts
todos.controller.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/todos/todos.controller.ts).
글 읽기 →todos.module.ts
todos.module.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/todos/todos.module.ts).
글 읽기 →