- [Instructor] In this video,
we'll implement the login endpoint.
I'll begin by copying the register endpoint
and pasting it below.
Then let's rename it.
We will no longer be getting register data,
but instead login data,
so I'll make that change to line 43,
and we will no longer need to push a new user,
so I'll take out line 45.
We will still need to get the user ID,
but we'll need a different method for getting that,
and what we'll do is simply search through our users list
to see if there's a username that matches
what we have in our login data.
After that, all we need to do
is check if the passwords match,
so I'll use users.findIndex,
since the index will give us the user ID.
And in here, we'll pass in an inline arrow function
that will provide our search.
So we'll use user arrow,
and then check user.userName.
If it matches, loginData.userName.
Since this is a bit complex,
let's test this out with a console.log.
Let's save this and give it a try.
So we could register a new user,
but to skip that step,
we can scroll to the top of our server,
and we see that we initialized our users list
with a default user of Jim and password 1,
so let's try that.
Let's see what we got.
And we get an index of zero,
and so it's working.
Let's just triple check by logging out
and registering a new user.
Then we'll log out again,
and let's log in with that new user.
And we have an index or an ID of one,
so we know it's working.
So now all we need to do is implement the password check.
I'll get rid of the console.log on line 46,
and then I'll check if users,
and I'll pass in the ID, which is the index,
dot password does not match loginData.password,
I'll return a response.status 401,
and then I'll send a message letting the users know
name or password is invalid.
Let's save that and give it a try.
So I'll use the username Jim,
and the password, I'll make sure that's wrong.
Let's try to log in,
and you can see we're getting a 401
with our message name or password is invalid.
Let's try to log in correctly with the right password,
and everything's working.
But now what happens if we try to log in
with a username that does not exist?
We're getting a 500 error,
meaning the server has crashed.
Let's check it out.
We're getting an error cannot read property,
password of undefined.
So what seems to be happening is there's no user,
and so we're not getting a user ID here,
and therefore we're not able to pull up a user
when we check for the password.
So we'll need another if condition.
Let's copy this one and paste it above.
If we hover over findIndex,
we can see it says it will return negative one
if it doesn't find anything.
So let's check if user ID is equal to negative one.
If it is, the name is invalid,
so we'll just leave the same error message.
Let's give that another try.
And we're getting a 401 unauthorized correctly.
And so we now have register
and login both working correctly.