0
0
NestJSframework~30 mins

Role-based authorization in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Role-based authorization
📖 Scenario: You are building a simple NestJS backend for a company. Different users have different roles like admin and user. You want to control access to certain routes based on these roles.
🎯 Goal: Create a role-based authorization system in NestJS that allows only users with the admin role to access a protected route.
📋 What You'll Learn
Create a roles array to define user roles
Create a variable to hold the current user's role
Use a guard or function to check if the user role matches the required role
Protect a route so only admin role users can access it
💡 Why This Matters
🌍 Real World
Role-based authorization is used in real apps to control who can see or do what, like only managers can approve requests.
💼 Career
Understanding role-based access control is important for backend developers to secure APIs and protect sensitive data.
Progress0 / 4 steps
1
Define user roles array
Create a constant array called roles with the exact strings 'admin' and 'user'.
NestJS
Need a hint?

Use const roles = ['admin', 'user']; to define the roles array.

2
Set current user role
Create a variable called currentUserRole and set it to the string 'user'.
NestJS
Need a hint?

Use let currentUserRole = 'user'; to set the current user role.

3
Create role check function
Write a function called canAccessAdmin that returns true if currentUserRole is exactly 'admin', otherwise returns false.
NestJS
Need a hint?

Use a simple function that compares currentUserRole to 'admin' and returns the result.

4
Protect route with role check
Create a NestJS controller method called getAdminData that returns the string 'Secret admin data' only if canAccessAdmin() returns true. Otherwise, throw an UnauthorizedException. Import UnauthorizedException from @nestjs/common.
NestJS
Need a hint?

Use an if statement to check canAccessAdmin(). Throw UnauthorizedException if false, else return the secret string.