0
0
Expressframework~30 mins

Role-based access control in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Role-based access control
📖 Scenario: You are building a simple Express server 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 basic Express app that uses role-based access control (RBAC) middleware to allow or deny access to routes depending on the user's role.
📋 What You'll Learn
Create an Express app with a users data structure
Add a variable to hold the current user's role
Write middleware to check the user's role before allowing access
Protect routes so only users with the right role can access them
💡 Why This Matters
🌍 Real World
Role-based access control is used in web apps to restrict what users can do based on their roles, like admin or regular user.
💼 Career
Understanding RBAC is important for backend developers to secure APIs and protect sensitive data.
Progress0 / 4 steps
1
Set up users data
Create a constant called users that is an object with these exact entries: alice with role admin, bob with role user, and carol with role guest.
Express
Need a hint?

Use an object with keys as usernames and values as objects with a role property.

2
Set current user role
Create a variable called currentUserRole and set it to the role of user bob from the users object.
Express
Need a hint?

Access the role property of bob inside users.

3
Create role check middleware
Write a function called checkRole that takes a parameter role and returns a middleware function. This middleware should check if currentUserRole equals the role parameter. If yes, call next(). Otherwise, respond with status 403 and message 'Access denied'.
Express
Need a hint?

Return a middleware function that compares currentUserRole with the given role.

4
Protect routes with middleware
Create an Express app using express(). Add two routes: /admin protected by checkRole('admin') middleware that sends 'Welcome Admin', and /user protected by checkRole('user') middleware that sends 'Welcome User'.
Express
Need a hint?

Use app.get with the checkRole middleware and send the correct welcome messages.