Bird
0
0

Identify the error in this NestJS guard code for role checking:

medium📝 Debug Q14 of 15
NestJS - Authentication
Identify the error in this NestJS guard code for role checking:
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  const user = request.user;
  const roles = this.reflector.get('roles', context.getHandler());
  if (!roles) {
    return true;
  }
  return roles.includes(user.role);
}
AMissing async keyword on canActivate
BReturning true when roles are not defined
CUsing getHandler() instead of getClass() for roles
DNot checking if user exists before accessing user.role
Step-by-Step Solution
Solution:
  1. Step 1: Review user role access

    The code accesses user.role without verifying if user is defined.
  2. Step 2: Identify potential runtime error

    If user is undefined, accessing user.role causes an error.
  3. Final Answer:

    Not checking if user exists before accessing user.role -> Option D
  4. Quick Check:

    Always check user before role access [OK]
Quick Trick: Check user object exists before role check [OK]
Common Mistakes:
  • Assuming user is always present
  • Confusing getHandler() and getClass() usage
  • Thinking async is required for synchronous guard

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes