Consider this role-based guard in NestJS that allows access only to users with 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 checks if the user's roles array includes 'admin'. Since the user has only 'user' role, it returns false, denying access.
Given a RolesGuard class, which of the following code snippets correctly applies it to a controller method?
Check the correct decorator name and usage syntax.
The correct decorator is @UseGuards with the guard class passed without parentheses. Option A is correct.
Examine this RolesGuard code:
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;
if (!user) return false;
if (user.roles === 'admin') {
return true;
}
return false;
}
}Users have roles as an array of strings, e.g., ['admin']. Why does this guard deny access to admins?
Check how roles are compared.
The guard compares user.roles (an array) to the string 'admin' using ===, which is always false. It should check if the array includes 'admin'.
Given this guard snippet:
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const user = request.user;
const allowedRoles = ['admin', 'superuser'];
const hasAccess = user.roles.some(role => allowedRoles.includes(role));
return hasAccess;
}If user.roles = ['editor', 'admin'], what is the value of hasAccess?
Check if any user role matches allowedRoles.
The user has 'admin' role which is in allowedRoles, so some returns true.
Choose the most accurate description of role-based guards in NestJS.
Think about what guards do in NestJS.
Role-based guards check user roles to allow or deny access to routes. They do not assign roles, encrypt data, or replace authentication.