Bird
Raised Fist0
Expressframework~20 mins

Role-based access control in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Express RBAC Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when a user with role 'guest' accesses the protected route?

Consider this Express middleware that checks user roles before allowing access to a route.

function checkRole(role) {
  return function(req, res, next) {
    if (req.user?.role === role) {
      next();
    } else {
      res.status(403).send('Access denied');
    }
  };
}

app.get('/admin', checkRole('admin'), (req, res) => {
  res.send('Welcome Admin');
});

// Assume req.user = { role: 'guest' }

What will the server respond with when a user with role 'guest' requests '/admin'?

AThe server responds with status 404 Not Found
BThe server responds with status 403 and 'Access denied'
CThe server crashes with a TypeError
DThe server responds with 'Welcome Admin'
Attempts:
2 left
💡 Hint

Think about what happens when the user's role does not match the required role.

📝 Syntax
intermediate
2:00remaining
Which option correctly implements role-based middleware allowing multiple roles?

You want to create middleware that allows access if the user's role is in a list of allowed roles.

function allowRoles(roles) {
  return function(req, res, next) {
    // Fill in the condition to check if req.user.role is in roles
    if (/* condition here */) {
      next();
    } else {
      res.status(403).send('Forbidden');
    }
  };
}

Which option correctly fills the condition?

Areq.user.role in roles
Broles.indexOf(req.user.role) === -1
Creq.user.role === roles
Droles.includes(req.user.role)
Attempts:
2 left
💡 Hint

Use the correct JavaScript method to check if an array contains a value.

🔧 Debug
advanced
2:00remaining
Why does this role-check middleware always grant access?

Review this Express middleware:

function checkRole(role) {
  return function(req, res, next) {
    if (req.user.role = role) {
      next();
    } else {
      res.status(403).send('Access denied');
    }
  };
}

Why does it always grant access even when the user has the wrong role?

ABecause req.user.role is undefined
BBecause next() is never called
CBecause '=' is used instead of '===' causing assignment instead of comparison
DBecause res.status is missing a status code
Attempts:
2 left
💡 Hint

Check the difference between '=' and '===' in JavaScript.

❓ state_output
advanced
2:00remaining
What is the value of req.user after this middleware runs?

Given this middleware that adds roles to the user object:

function addRoles(req, res, next) {
  req.user = { name: 'Alice' };
  req.user.roles = ['user', 'editor'];
  next();
}

app.use(addRoles);

app.get('/edit', (req, res) => {
  res.send(req.user.roles.includes('editor') ? 'Edit allowed' : 'Edit denied');
});

What is the value of req.user inside the '/edit' route handler?

A{ name: 'Alice', roles: ['user', 'editor'] }
B{ name: 'Alice' }
Cundefined
D{ roles: ['user', 'editor'] }
Attempts:
2 left
💡 Hint

Think about how properties are added to objects in JavaScript.

🧠 Conceptual
expert
2:00remaining
Which statement best describes role-based access control in Express?

Choose the most accurate description of how role-based access control (RBAC) is implemented in Express applications.

ARBAC is implemented by attaching user roles to the request object and using middleware to allow or deny access based on those roles.
BRBAC requires modifying the Express core to add role checks before every route handler.
CRBAC is automatically handled by Express without any middleware or code changes.
DRBAC is implemented by storing roles in cookies and checking them in the client-side JavaScript.
Attempts:
2 left
💡 Hint

Think about how Express middleware works and where user data is stored during a request.

Practice

(1/5)
1. What is the main purpose of role-based access control (RBAC) in an Express app?
easy
A. To speed up the server response time
B. To limit user actions based on their assigned roles
C. To store user passwords securely
D. To log all user activities automatically

Solution

  1. Step 1: Understand RBAC concept

    RBAC means controlling what users can do depending on their role, like admin or guest.
  2. Step 2: Identify main purpose in Express

    In Express, RBAC limits access to routes or actions based on user roles to keep the app safe.
  3. Final Answer:

    To limit user actions based on their assigned roles -> Option B
  4. Quick Check:

    RBAC controls user permissions = A [OK]
Hint: RBAC controls what users can do by role [OK]
Common Mistakes:
  • Confusing RBAC with performance optimization
  • Thinking RBAC stores passwords
  • Assuming RBAC logs activities automatically
2. Which of the following is the correct way to define a middleware function in Express to check if a user has the role 'admin'?
easy
A. function checkAdmin(req, res, next) { if(req.user.role === 'admin') next(); else res.status(403).send('Forbidden'); }
B. function checkAdmin(req, res) { if(req.user.role == 'admin') next(); else res.send('Forbidden'); }
C. function checkAdmin(req, res, next) { if(req.user.role = 'admin') next(); else res.status(403).send('Forbidden'); }
D. function checkAdmin(req, res, next) { if(req.user.role !== 'admin') next(); else res.status(403).send('Forbidden'); }

Solution

  1. Step 1: Check middleware signature

    Middleware must have three parameters: req, res, next.
  2. Step 2: Verify role check and response

    function checkAdmin(req, res, next) { if(req.user.role === 'admin') next(); else res.status(403).send('Forbidden'); } correctly compares role with 'admin' using === and calls next() if true; else sends 403 status.
  3. Final Answer:

    function checkAdmin(req, res, next) { if(req.user.role === 'admin') next(); else res.status(403).send('Forbidden'); } -> Option A
  4. Quick Check:

    Middleware with correct params and strict role check = D [OK]
Hint: Middleware needs (req, res, next) and strict role check [OK]
Common Mistakes:
  • Using assignment (=) instead of comparison (===)
  • Missing next() parameter or call
  • Wrong logic reversing role check
3. Given this Express route with role check middleware, what will be the response if a user with role 'user' tries to access it?
app.get('/admin', checkAdmin, (req, res) => { res.send('Welcome Admin'); });
function checkAdmin(req, res, next) {
if(req.user.role === 'admin') next();
else res.status(403).send('Forbidden');
}
medium
A. 403 Forbidden status with 'Forbidden' message
B. 'Welcome Admin'
C. 500 Internal Server Error
D. 404 Not Found

Solution

  1. Step 1: Analyze middleware behavior for role 'user'

    The middleware checks if role is 'admin'. Since role is 'user', condition fails.
  2. Step 2: Determine response when role check fails

    Middleware sends 403 status with 'Forbidden' message and does not call next(), so route handler is skipped.
  3. Final Answer:

    403 Forbidden status with 'Forbidden' message -> Option A
  4. Quick Check:

    Non-admin blocked with 403 Forbidden = B [OK]
Hint: Middleware blocks non-admin with 403, no next() call [OK]
Common Mistakes:
  • Assuming route handler runs for non-admin
  • Confusing 403 with 404 or 500 errors
  • Ignoring middleware role check logic
4. Identify the error in this Express middleware for role-based access control:
function checkRole(req, res, next) {
if(req.user.role = 'admin') {
next();
} else {
res.status(403).send('Access denied');
}
}
medium
A. Middleware missing req and res parameters
B. Missing next() call inside the else block
C. Incorrect status code for access denial
D. Using assignment (=) instead of comparison (===) in the if condition

Solution

  1. Step 1: Check the if condition syntax

    The condition uses single = which assigns 'admin' to req.user.role instead of comparing it.
  2. Step 2: Understand impact of assignment in condition

    Assignment always returns truthy, so else block never runs, causing wrong behavior.
  3. Final Answer:

    Using assignment (=) instead of comparison (===) in the if condition -> Option D
  4. Quick Check:

    Use === for comparison, not = [OK]
Hint: Use === for comparison, not = assignment [OK]
Common Mistakes:
  • Confusing assignment and comparison operators
  • Forgetting to call next() in middleware
  • Using wrong HTTP status codes
5. You want to protect multiple routes so only users with roles 'admin' or 'manager' can access them. Which middleware implementation correctly allows this in Express?
hard
A. function checkRoles(req, res, next) { if(req.user.role === 'admin' && req.user.role === 'manager') next(); else res.status(403).send('Forbidden'); }
B. function checkRoles(req, res, next) { if(req.user.role === 'admin' || 'manager') next(); else res.status(403).send('Forbidden'); }
C. function checkRoles(req, res, next) { if(['admin', 'manager'].includes(req.user.role)) next(); else res.status(403).send('Forbidden'); }
D. function checkRoles(req, res, next) { if(req.user.role == 'admin' || req.user.role == 'manager') next(); else res.status(404).send('Forbidden'); }

Solution

  1. Step 1: Check role inclusion logic

    function checkRoles(req, res, next) { if(['admin', 'manager'].includes(req.user.role)) next(); else res.status(403).send('Forbidden'); } uses array includes() to check if role is 'admin' or 'manager', which is correct and clean.
  2. Step 2: Verify status code and logic correctness

    Using && requires role to be both 'admin' and 'manager' simultaneously (impossible); condition like if(role === 'admin' || 'manager') has wrong syntax and always passes since 'manager' is truthy; using 404 instead of 403 for forbidden access is incorrect.
  3. Final Answer:

    function checkRoles(req, res, next) { if(['admin', 'manager'].includes(req.user.role)) next(); else res.status(403).send('Forbidden'); } -> Option C
  4. Quick Check:

    Use includes() for multiple roles and 403 status = C [OK]
Hint: Use array includes() to check multiple roles cleanly [OK]
Common Mistakes:
  • Using incorrect logical operators or syntax
  • Checking role equality incorrectly
  • Sending wrong HTTP status code for forbidden
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard