0
0
NestJSframework~10 mins

Role-based authorization 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 decorator used to define roles in NestJS.

NestJS
import { [1] } from '@nestjs/common';
Drag options to blanks, or click blank then click option'
ASetMetadata
BRoles
CUseGuards
DController
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Roles' decorator which is not built-in
Importing 'UseGuards' instead of 'SetMetadata'
2fill in blank
medium

Complete the code to create a custom decorator named Roles that sets roles metadata.

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 'Controller' decorator here
3fill in blank
hard

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

NestJS
const roles = this.reflector.[1]('roles', context.getHandler());
Drag options to blanks, or click blank then click option'
AgetAll
Bfind
Cfetch
Dget
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fetch' or 'find' which do not exist on Reflector
Using 'getAll' which is not a method here
4fill in blank
hard

Fill both blanks to check if the user has any of the required roles in the guard.

NestJS
return roles.some(role => user.roles.[1](role)) && user.isActive === [2];
Drag options to blanks, or click blank then click option'
Aincludes
BindexOf
ChasOwnProperty
Dtrue
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'indexOf' without checking for -1
Checking user.isActive against 'false'
5fill in blank
hard

Fill both blanks to apply the Roles decorator and guard to a controller route.

NestJS
@[1]('admin')
@UseGuards([2])
@Get('admin')
adminRoute() {
  return 'Admin content';
}
Drag options to blanks, or click blank then click option'
ARoles
BRolesGuard
CAuthGuard
DController
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Controller' decorator on a method
Using 'AuthGuard' instead of 'RolesGuard'