</>
⌕
Mid #guard#rbac#reflector#decorator

Viết RBAC bằng Guard, Reflector và custom decorator như thế nào?

⚡ Trả lời nhanh

Tạo decorator @Roles() bằng SetMetadata, rồi guard implements CanActivate dùng Reflector.getAllAndOverride đọc metadata từ handler và class, so sánh với req.user.roles. Guard trả boolean; false thì Nest ném 403.

export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(ctx: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride<string[]>(
      ROLES_KEY, [ctx.getHandler(), ctx.getClass()]);
    if (!required) return true;
    const { user } = ctx.switchToHttp().getRequest();
    return required.some((r) => user?.roles?.includes(r));
  }
}
// @UseGuards(JwtAuthGuard, RolesGuard) @Roles('admin') @Delete(':id') ...
🃏 Ôn bằng flashcard