0
0
Expressframework~10 mins

Why authorization differs from authentication in Express - Test Your Understanding

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

Complete the code to check if a user is authenticated before accessing a route.

Express
app.get('/dashboard', (req, res) => {
  if (req.[1]()) {
    res.send('Welcome to your dashboard');
  } else {
    res.status(401).send('Please login first');
  }
});
Drag options to blanks, or click blank then click option'
AisAuthenticated
Buser
Cauth
Dsession
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'user' instead of 'isAuthenticated' will not return a boolean.
Using 'session' or 'auth' are not standard methods for authentication check.
2fill in blank
medium

Complete the code to authorize a user role before allowing access.

Express
app.get('/admin', (req, res) => {
  if (req.user && req.user.role === '[1]') {
    res.send('Welcome Admin');
  } else {
    res.status(403).send('Access denied');
  }
});
Drag options to blanks, or click blank then click option'
Aadmin
Bmember
Cguest
Duser
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'guest' or 'member' will deny access to admins.
Not checking if req.user exists can cause errors.
3fill in blank
hard

Fix the error in the middleware that authenticates users.

Express
function ensureAuthenticated(req, res, next) {
  if (req.[1]()) {
    return next();
  }
  res.redirect('/login');
}
Drag options to blanks, or click blank then click option'
AisAuthorized
BcheckAuth
CisAuthenticated
DhasAccess
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'isAuthorized' or 'hasAccess' which are not standard methods.
Forgetting the parentheses to call the method.
4fill in blank
hard

Fill both blanks to create a middleware that checks authentication and authorization.

Express
function checkAccess(req, res, next) {
  if (req.[1]() && req.user.role === '[2]') {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
}
Drag options to blanks, or click blank then click option'
AisAuthenticated
Badmin
Cguest
DisAuthorized
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'isAuthorized' which is not a standard method.
Checking role before authentication can cause errors.
5fill in blank
hard

Fill all three blanks to create an Express route that authenticates, authorizes, and sends a response.

Express
app.get('/settings', (req, res) => {
  if (req.[1]() && req.user.role === '[2]' && req.user.active === [3]) {
    res.send('Settings page');
  } else {
    res.status(403).send('Access denied');
  }
});
Drag options to blanks, or click blank then click option'
AisAuthenticated
Badmin
Ctrue
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'false' for active status denies access.
Not calling the authentication method as a function.