- [Narrator] Eventually we want to authenticate users
against our MongoDB Database.
For that, we already created a user model.
Now we want to implement all flows and methods
related to authentication.
Let's open the auth.js.
And as we know, passport gives us
a set of different authentication strategies.
To authenticate against the local database
we need the local strategy.
It's not bundled with passport.
So we need to install the respective model.
For that I'll run npm install,
dash dash save, passport dash local.
And now in auth.js I can add const, local strategy,
equals require passport local, dot strategy.
Next we have to add the strategy to passport.
And for that we have a similar mechanism
as express middle verse.
So I add passport dot use.
And here we'll now pass in the new local strategy.
And by default this strategy
will look for username and password in the body.
But we want to use the email address here.
So we have to set a configuration option for that.
And to do that, add username field should be email.
So it will now look inside the body for a property email,
and will use that instead of a username field.
Next, we have to implement
the actual authentication function, so I add async.
And this function gets now the username,
the password, and the done callback.
And inside, we will add a try catch block.
If there is an error,
we want to return done, done error.
And in the try block,
we will now implement the actual authentication logic.
And for that of course,
we also need the user model in place.
So we will require that,
const user model, equals require models, usermodel.
Now we can try to load the user
by adding const user, equals await user model, find one.
And here we want to look for the email address,
which is given us by password in the username variable.
We add exec so that we get a real promise back.
And next we will now check if there is a user or not.
So if there is no user,
we will return done.
First argument is an error.
This is not an error search.
But we also have no user object
so we will pass in false as second argument.
And the third argument we can provide a message
that could be something like invalid username or password.
If there is a user, we now want to validate their password.
So add const password okay, equals await user.
And this is now the compare function
that we implemented in the model.
User compare password.
And we will compare it with the password we got
as function argument from passport.
If password is not okay,
we will return again with the message and no user,
which is again, invalid username or password.
And in the other case,
we can now return done, null error here.
But a valid user with a valid password.
With this strategy in place,
we can now authenticate users against the database.
Next, we have to implement
the serialization and de-serialization functions
to save and retrieve users from a session.