0
0
Expressframework~10 mins

Role-based access control in Express - Interactive Code Practice

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

Complete the code to create a middleware that checks if the user role is 'admin'.

Express
function checkAdmin(req, res, next) {
  if (req.user.role === '[1]') {
    next();
  } else {
    res.status(403).send('Access denied');
  }
}
Drag options to blanks, or click blank then click option'
Aadmin
Buser
Cguest
Dmoderator
Attempts:
3 left
💡 Hint
Common Mistakes
Using a role other than 'admin' will deny access incorrectly.
Forgetting to call next() when the role matches.
2fill in blank
medium

Complete the code to apply the role check middleware to the '/dashboard' route.

Express
app.get('/dashboard', [1], (req, res) => {
  res.send('Welcome to dashboard');
});
Drag options to blanks, or click blank then click option'
AcheckUser
BroleCheck
CauthMiddleware
DcheckAdmin
Attempts:
3 left
💡 Hint
Common Mistakes
Using a middleware that does not check roles.
Forgetting to add middleware before the route handler.
3fill in blank
hard

Fix the error in the middleware to correctly check if the user role is in allowed roles array.

Express
function authorize(allowedRoles) {
  return (req, res, next) => {
    if (allowedRoles.includes(req.user.[1])) {
      next();
    } else {
      res.status(403).send('Forbidden');
    }
  };
}
Drag options to blanks, or click blank then click option'
Arole
Broles
CuserRole
Dpermission
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong property name like 'roles' or 'permission'.
Not checking inclusion properly.
4fill in blank
hard

Fill both blanks to create a middleware that authorizes roles 'editor' and 'admin'.

Express
const authorize = (roles) => {
  return (req, res, next) => {
    if (roles.[1](req.user.role)) {
      next();
    } else {
      res.status(403).send('[2]');
    }
  };
};
Drag options to blanks, or click blank then click option'
Aincludes
BForbidden
Cfind
Dfilter
Attempts:
3 left
💡 Hint
Common Mistakes
Using array methods that return arrays instead of booleans.
Sending wrong or unclear denial messages.
5fill in blank
hard

Fill all three blanks to create a route that uses the authorize middleware for 'admin' and 'editor' roles.

Express
app.post('/edit', [1](['[2]', '[3]']), (req, res) => {
  res.send('Edit page');
});
Drag options to blanks, or click blank then click option'
Aauthorize
Badmin
Ceditor
DcheckAdmin
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong middleware function name.
Passing roles as separate arguments instead of an array.