- [Instructor] To add passport to the project,
I have to install the npm module,
so I'm running npm install --save passport.
We should hold all authentication-related code
in a central location instead of spreading it out
in our server.js file.
Let's create a file, lib, auth.js for that.
And in there, first we will bring in passport,
const passport equals require passport.
And here I will simply export a few function
that passport needs to operate,
so I'm exporting an object
with one property initialize
which we'll simply call passport.initialize
and one property session
which points to passport.session.
Let's fix the indents here real quick.
Of course we now have to add this also
to our app.js file, so I'm opening app.js
and there I will add const auth equals require
/lib/auth.
Of course we now also have to bring
those two passport middleware functions
into our middleware chain
and here it's really important
that they're loaded after the session was initialized,
so if we have the session middleware on line 30,
we will add them right after that,
so I'm using app.use
and there I first add auth.initialize
and on the next line, I add app auth.session.
In my templates, I want to show different navigation options
depending on if the user is logged in or not.
So, let's create another middleware
that sets the user on res.locals
which is globally available in all templates.
See my course Building a Website with Express.js
if this is unfamiliar to you.
So, I will now head over back to auth.js
and there I add a new exported property setUser
and it takes request, response and next
and there I simply set res.locals.user equals request.user
because if a user is logged in,
passport will give us the current user
in request.user
and in the end we should never forger to call
and return next
because otherwise our application will get stuck.
So, now let's head over to app.js
and there we will simply bring in this additional middleware
after we initialized passport.
Now that we have passport in place,
we have to implement a strategy
that lets us authenticate users
against our database.
We will do that in the next video.