you would come here because the req.session.user is already not null,
so which means that the user has already been authenticated,
so which means when you reach this point,
then the user has already logged in earlier,
so you don't need to verify.
So you will simply say,
"You're already authenticated," and then finish off at this point.
Okay. So now, the last method that we will implement is for logging out the user.
So, we'll do a router.get on /logout.
You must be wondering why do we do a get on
the logout rather than a post which we did on login?
On login, you need to submit the username and password.
For logout you're simply logging out yourself from the system,
so you don't need to supply any further information because
the server already is tracking you based upon
your session ID and inside that session cookie here.
So, that's why we are not
explicitly needing to send any further information in the body of the message.
So we'll say if req.session so which means that the session must exist,
otherwise, you're trying to log out a user that has not logged in.
So it doesn't make sense.
Now, the session itself provides this method
called destroy and when you call the destroy method,
the session is destroyed and the information is removed
from the server side pertaining to this session.
So, which means that if the client tries to again send
the session information which is stored in the form
of a signed cookie on the client side,
that will be invalid.
So we need a method of deleting the cookie that is stored on the client side.
Now, this operation will remove
the session information from the server side so that the session is no longer valid.
So, at this point,
we'll say req.session.destroy and then we'll say, res.clearCookie.
So the clearCookie is a way of asking the client to
remove the cookie and the cookie name is the session ID.
So, in the previous exercise,
we saw that the cookie was stored with the name of session ID on the client side.
So we are asking the client to delete this cookie from
the client side in the reply message and then we'll say,
res.redirect and we'll redirect it to the homepage here.
So, this is a way of redirecting the user to enter their standard page,
so for example, the homepage of your application.
So, this is the way you would handle the logout of the system.
If the req.session doesn't exist,
then that means that you're not logged in,
so we will have to generate an error.
So we'll say var err,
new Error, "You are not logged in",