- [Instructor] Okay, so let's go ahead and create
the controllers for our user model.
So in the controllers folder, go ahead and click new file,
and we're going to call this usercontrollers.js,
and then we're going to import a few things.
So first, we're going to import mongoose
from
mongoose.
And then we'll import
bcrypt from
bcrypt.
We'll also import JWT, which we'll need soon
from jsonwebtoken, which we've installed previously.
And then we'll also import the user's key mod
that we just created.
Again, the tip that I gave you earlier
will work in this case, so let's go ahead and do from
models, and usermodel,
and then, if I go ahead and start typing
what are the exports available for me,
like userschema, it's going to suggest that,
which is a neat trick inside of VS Code.
All right, so let's go ahead and create a variable
that we'll call User, and I want to do capital U.
We're going to create a model from mongoose,
like so.
Which we'll call user
and pass the user's key mod.
So it's expecting what we've created in the schema.
So if we go back to userschema, it's expecting this data
that we have created inside of the user schema.
So when we pass this, this part of the model
we're creating inside of mongoose,
it's going to expect the values that we send
from our request to the API.
All right, so let's create our first function,
which is the login required.
And this function will take a few arguments,
so I'll put in request, then response, and then next,
so we can pass to the next function.
So let's go ahead and do an if statement.
So if
in the request
there's a user
that is basically a logged in user,
then go to the next function.
So when we'll use the login required inside of our routes,
it's going to go through that process.
So if we have a logged in user,
go ahead to the next function, which will be
the function to get the data, or post data,
or delete data, and so on, so forth.
Otherwise, and this is where we're going to do else,
return
a response status
of 401.
And we'll add a message to that, which is a json message.
And the message will be
unauthorized user.
So basically, if there's not a logged in user,
we're going to tell through a message that this guy
is not authorized to add or pull data from the database.
And that's basically it for that function.
So right now, what we've done is create a function
that will check if the user is logged in.
We'll keep working on the other functions
in the following videos.