Consider this NestJS guard that checks if the user has the 'admin' role:
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class RolesGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const user = request.user;
return user?.roles?.includes('admin');
}
}If a request has user.roles = ['user'], what will the guard return?
Check if the roles array includes 'admin'.
The guard returns true only if the user's roles include 'admin'. Since the user has only 'user' role, it returns false.
Given a RolesGuard and a Roles decorator, which code snippet correctly protects the getAdminData route to only allow 'admin' role users?
Order of decorators matters: guards should be applied before roles.
In NestJS, @UseGuards should be placed before @Roles to ensure the guard runs with the roles metadata available.
Look at this RolesGuard code:
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const user = request.user;
const requiredRoles = this.reflector.get('roles', context.getHandler());
return requiredRoles.some(role => user.roles.includes(role));
} Even when the user has the 'admin' role and the route requires 'admin', access is denied. Why?
Check if this.reflector is properly set up.
If this.reflector is not injected via constructor, it will be undefined, causing requiredRoles to be undefined and the guard to fail.
Given this guard snippet:
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const user = request.user;
const roles = ['admin', 'editor'];
const isAuthorized = roles.some(role => user.roles?.includes(role));
return isAuthorized;
}If user.roles = ['viewer', 'editor'], what is the value of isAuthorized?
Check if any role in ['admin', 'editor'] is in user.roles.
The user has 'editor' role which matches one in the roles array, so isAuthorized is true.
In NestJS, the Reflector class is often used in guards for role-based authorization. What is its main purpose?
Think about how decorators store information in NestJS.
The Reflector reads metadata added by decorators like @Roles() to determine which roles are required for a route.