Bird
0
0

Why does this role-based guard fail to restrict access?

medium📝 Debug Q7 of 15
NestJS - Guards
Why does this role-based guard fail to restrict access?
canActivate(context: ExecutionContext) { const roles = this.reflector.get('roles', context.getHandler()); const user = context.switchToHttp().getRequest().user; return roles.includes(user.roles); }
Auser.roles is an array but includes expects a string
Broles is undefined due to missing metadata
CUsing includes on roles array is incorrect
DNo error, guard works correctly
Step-by-Step Solution
Solution:
  1. Step 1: Analyze user.roles type

    user.roles is likely an array of roles, but includes expects a single string.
  2. Step 2: Understand includes method

    includes checks if a single element exists, not an array inside an array.
  3. Final Answer:

    user.roles is an array but includes expects a string -> Option A
  4. Quick Check:

    includes expects single value, not array [OK]
Quick Trick: Check types: includes needs single value, not array [OK]
Common Mistakes:
  • Passing array to includes instead of single role
  • Assuming roles metadata is always present
  • Confusing includes with some

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions