0
0
NestJSframework~10 mins

Role-based guards in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the necessary decorator for roles.

NestJS
import { [1] } from '@nestjs/common';
Drag options to blanks, or click blank then click option'
AController
BUseGuards
CRoles
DSetMetadata
Attempts:
3 left
💡 Hint
Common Mistakes
Using Roles decorator which does not exist by default.
Confusing UseGuards with metadata setting.
2fill in blank
medium

Complete the code to create a custom decorator named Roles.

NestJS
export const Roles = (...roles: string[]) => [1]('roles', roles);
Drag options to blanks, or click blank then click option'
ASetMetadata
BUseGuards
CController
DInjectable
Attempts:
3 left
💡 Hint
Common Mistakes
Using UseGuards instead of SetMetadata.
Trying to use Injectable which is for services.
3fill in blank
hard

Fix the error in the guard method to get roles metadata.

NestJS
const roles = this.reflector.get<string[]>([1], context.getHandler());
Drag options to blanks, or click blank then click option'
A'role'
B'roles'
C'permissions'
D'auth'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'role' instead of 'roles' causes undefined metadata.
Using unrelated keys like 'permissions' or 'auth'.
4fill in blank
hard

Fill in the blank to check if user roles include any required role.

NestJS
if (!roles) return true; // Allow access if no roles are set

return user.roles.some(role => roles.[1](role)); // Check if user has any required role
Drag options to blanks, or click blank then click option'
Aequals
Bexcludes
Cincludes
Dcontains
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'excludes' which is not a valid array method.
Returning false when no roles are set blocks access incorrectly.
5fill in blank
hard

Fill all three blanks to apply the Roles guard to a controller method.

NestJS
@[1](RolesGuard)
@[2]('admin')
@[3]('dashboard')
async getDashboard() {
  return 'Admin Dashboard';
}
Drag options to blanks, or click blank then click option'
AUseGuards
BRoles
CController
DGet
Attempts:
3 left
💡 Hint
Common Mistakes
Using Controller instead of Get for the route method.
Forgetting to apply UseGuards to activate the guard.