Bird
0
0

Identify the error in this role-based guard implementation:

medium📝 Debug Q14 of 15
NestJS - Guards
Identify the error in this role-based guard implementation:
canActivate(context: ExecutionContext) {
  const roles = this.reflector.get('roles', context.getHandler());
  const request = context.switchToHttp().getRequest();
  const user = request.user;
  if (!roles) {
    return false;
  }
  return roles.includes(user.role);
}
AReturns false if no roles metadata, blocking all access
BMissing async keyword causes runtime error
CIncorrect use of context.getHandler()
DShould check user permissions instead of roles
Step-by-Step Solution
Solution:
  1. Step 1: Analyze roles metadata check

    If roles metadata is missing, the guard returns false blocking access.
  2. Step 2: Understand typical behavior for missing roles

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

    Returns false if no roles metadata, blocking all access -> Option A
  4. Quick Check:

    No roles metadata should allow access, not block [OK]
Quick Trick: Missing roles metadata should not block access by default [OK]
Common Mistakes:
  • Assuming missing roles means deny access
  • Forgetting to handle undefined roles gracefully
  • Confusing async necessity in this context

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes