0
0
Expressframework~10 mins

Admin vs user route protection in Express - Interactive 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 a user is logged in.

Express
function isLoggedIn(req, res, next) {
  if (req.user) {
    [1]();
  } else {
    res.status(401).send('Unauthorized');
  }
}
Drag options to blanks, or click blank then click option'
Aend
Bsend
Cstatus
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to call next() causes the request to hang.
Using res.send() instead of next() inside middleware.
2fill in blank
medium

Complete the code to protect an admin route by checking the user's role.

Express
app.get('/admin', isLoggedIn, (req, res) => {
  if (req.user.role === [1]) {
    res.send('Welcome Admin');
  } else {
    res.status(403).send('Forbidden');
  }
});
Drag options to blanks, or click blank then click option'
A'admin'
B'user'
C'guest'
D'moderator'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'user' role instead of 'admin'.
Using assignment = instead of comparison ===.
3fill in blank
hard

Fix the error in the middleware to correctly check admin access.

Express
function isAdmin(req, res, next) {
  if (req.user && req.user.role [1] 'admin') {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
}
Drag options to blanks, or click blank then click option'
A==
B=
C===
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using single equals = causes assignment instead of comparison.
Using loose equality == can cause unexpected behavior.
4fill in blank
hard

Fill both blanks to create a middleware that allows only admins or users accessing their own profile.

Express
function canAccessProfile(req, res, next) {
  if (req.user.role === [1] || req.user.id === [2]) {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
}
Drag options to blanks, or click blank then click option'
A'admin'
Breq.params.userId
C'user'
Dreq.body.userId
Attempts:
3 left
💡 Hint
Common Mistakes
Checking req.body.userId instead of req.params.userId.
Using role 'user' instead of 'admin' for admin check.
5fill in blank
hard

Fill all three blanks to create a route that uses both middlewares for admin-only access and logs the access.

Express
app.post('/admin/data', [1], [2], (req, res) => {
  console.log('Admin access by:', [3]);
  res.send('Data updated');
});
Drag options to blanks, or click blank then click option'
AisLoggedIn
BisAdmin
Creq.user.username
DcanAccessProfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using canAccessProfile instead of isAdmin for admin-only route.
Logging req.user.id instead of req.user.username.