"CSS Basics (2014)" was retired on July 12, 2021. You are now viewing the recommended replacement.
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
Create a log out route to destroy a user's session and log them out of the authentication system.
The Log Out Route code
// GET /logout
router.get('/logout', function(req, res, next) {
if (req.session) {
// delete session object
req.session.destroy(function(err) {
if(err) {
return next(err);
} else {
return res.redirect('/');
}
});
}
});
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
In the authentication system we've
created, when a user logs in,
0:00
Express creates a session
containing a user ID.
0:04
Basically, the existence
of a session with a user ID
0:07
indicates if a visitor is logged in or
not.
0:10
So the simplest way to log a visitor out
is to remove or destroy that session.
0:13
Express lets us do that easily.
0:18
So let's add another route to our app.
0:20
I'll open the index.js file
in the route's directory, and
0:22
I'll add a get route to /logout.
0:27
Let's see, right about here.
0:30
All right.
First,
0:44
I'll check to see if a session exists.
0:45
And if it does, I'll just delete it.
0:51
The sessions destroy method
takes a callback function,
0:58
which indicates what the app should
do after it destroys the session.
1:01
In this case, let's check to
see if there were any errors.
1:08
This is a step we do with
most callbacks and note.
1:11
And if not,
1:14
we'll just redirect the user who's now
logged out to the site's homepage.
1:15
Pretty simple, right?
1:20
Let's see how it works.
1:21
I'll save this file.
1:22
I still have nodemon running
from the last video.
1:24
So my app is updating each
time I make a change to it.
1:27
I can just switch to my browser and
go to localhost:3000.
1:30
Let's see how this works.
1:35
I'll log in.
1:36
Now there's the logout button.
1:39
[SOUND] I'm back on the homepage, and
the sign up and login button appears,
1:43
letting me know I'm no longer logged in.
1:47
When I check out my profile,
I'm not authorized cuz I'm not logged in.
1:49
In the next videos, I'll talk
more about Express middleware and
1:54
show you how to write your
own custom middleware.
1:57
See you there.
1:59
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