Bummer! You have been redirected as the page you requested could not be found.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed User Authentication With Express and Mongo!
You have completed User Authentication With Express and Mongo!
Preview
Add a simple piece of middleware to password protect any page on a site.
The requiresLogin( ) middleware function
function requiresLogin(req, res, next) {
if (req.session && req.session.userId) {
return next();
} else {
var err = new Error('You must be logged in to view this page.');
err.status = 401;
return next(err);
}
}
Using the middleware in a route
router.get('/secret', mid.requiresLogin, function(req, res, next) {
return res.render('secret', { title: 'Top secret. Stay out!' });
});
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Remember, we created an index.js
file in the middleware directory.
0:00
I'll add a new function
called requiresLogin here.
0:00
I'll use a conditional statement
to check for a session and
0:11
a userId on that session.
0:16
And if they're both there,
then the user is logged in.
0:19
I'll exit the function by calling
the next piece of middleware.
0:22
If they aren't logged in,
we'll create an error that lets
0:26
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up