Bird
0
0

Given this guard code snippet, what will be the result if the user role is 'user' and the route requires 'admin' role?

medium📝 component behavior Q13 of 15
NestJS - Guards
Given this guard code snippet, what will be the result if the user role is 'user' and the route requires 'admin' role?
canActivate(context: ExecutionContext) {
  const roles = this.reflector.get('roles', context.getHandler());
  const request = context.switchToHttp().getRequest();
  const user = request.user;
  return roles.includes(user.role);
}
AAccess granted
BAccess denied
CRuntime error due to missing roles
DAlways returns true
Step-by-Step Solution
Solution:
  1. Step 1: Understand role check logic

    The guard checks if the user's role is included in the allowed roles array.
  2. Step 2: Apply given roles and user role

    User role is 'user', route requires 'admin', so roles.includes('user') is false.
  3. Final Answer:

    Access denied -> Option B
  4. Quick Check:

    User role not in allowed roles = deny access [OK]
Quick Trick: Check if user role is in allowed roles array [OK]
Common Mistakes:
  • Assuming access is granted if roles differ
  • Thinking roles includes user role always
  • Ignoring roles array presence

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes