- [Instructor] Now that we know a little bit about
the theory of password encryption,
let's implement it real quick in our model.
So I open server models,
UserModel.js, and first of all,
I want to install bcrypt,
so I run NPM install
dash dash save
bcrypt.
Of course I also have to require it, so add const
bcrypt
equals
require
bcrypt.
You also want to add a constant
that holds the number of salt rounds,
so add salt underscore rounds
equals 12.
Next, after the schema was defined,
I will now implement a so-called presave hook
for Mongoose, so I add UserSchema
dot pre
save,
so this is a function that will run every save
for document,
and there I add async function.
We cannot use fat arrow syntax here
because we have to use this in the function
then and this refers then to the actual object.
I give the function name, preSave,
and this gets next callback,
and in there I will now
add const user
equals, and this is now the usage of this,
so user refers now to the actual to be saved object.
And I don't want to do anything
with the password if it was modified,
so I add if not user
dot isModified
it's a property that Mongoose gives us,
and I want to put a password here,
and if there was no change to the password,
I will simply
bale out of the function by calling next.
In any other case, I add a try catch block,
and in there I add const hash
equals await
bcrypt
and the hash function on delivery,
and we use user dot password.
So that's the password on the user object
that is to be saved, and a second argument.
I add the salt rounds.
Now we await the creation of the hash.
When it was created, I add user dot password
equals
this hash.
And don't forget again to call
to return with the next callback,
otherwise this function will get stuck,
and on the catch block,
we will return next
with the error.
Now we also want to implement the compare function
we talked about before,
and this compare function is rather CPU-heavy,
and there is a sync and async version.
We will use the async version because
the sync one would block the input considerably
when there are many logins,
and this can really impact the performance
of an application.
So I will now add, and here I'm utilizing now
Mongoose way to create
instance method,
so I add UserSchema
dot methods.
So this is then a method that will be available
on every document that comes from the database.
comparePassword
equals async function
comparePassword.
Again, no fat arrow syntax here for us
because we need this in there,
and this argument, comparePassword,
gets the candidate password,
and it will return
bcrypt
dot compare,
the candidate with the password
that is on the user object
right now.
Okay, let's try this out.
So I'm running NPX
mocha
test
server
models
UserModel test.
Now I'm using UserModel dot test dot password dot JS.
Let's run that.
And we see that all our tests are passed,
so we have now a working password
encryption and comparison function implemented
in our model.