Bird
0
0

Why might this RolesGuard fail to restrict access properly?

medium📝 Debug Q7 of 15
NestJS - Authentication
Why might this RolesGuard fail to restrict access properly?
canActivate(context: ExecutionContext) {
  const roles = this.reflector.getAllAndOverride('roles', [context.getHandler(), context.getClass()]);
  const user = context.switchToHttp().getRequest().user;
  if (!roles) return false;
  return roles.some(role => user.roles.includes(role));
}
AUsing getAllAndOverride is incorrect here
Buser.roles is not checked for null or undefined
CThe some() method is used incorrectly
DReturning false when roles are missing blocks all access
Step-by-Step Solution
Solution:
  1. Step 1: Check handling of missing roles

    The guard returns false if roles metadata is missing, blocking access.
  2. Step 2: Understand typical behavior

    Usually missing roles means no restriction, so returning false is too strict.
  3. Final Answer:

    Returning false when roles are missing blocks all access -> Option D
  4. Quick Check:

    Missing roles should allow access, not block [OK]
Quick Trick: Return true if no roles metadata to allow access [OK]
Common Mistakes:
  • Blocking access when no roles set
  • Misusing reflector methods
  • Ignoring null checks on user roles

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes