In this lesson, You will learn how to find record from MongoDB and compare the user password with plain text password. I will also teach you how to generate a json web token by using user payload object.
Instructor: 00:00 I have already created the login handler inside the user controller. I have a user model. I already created the route for the login.
00:10 Let's start implementing the login. First of all, we need to validate the schema. I need to call this method. I have already created the method, validate schema in the user service. I need to call this method, validate schema.
00:27 Here I need to provide the request body. If error comes, we need to send the bad request error. I can add the 400 status code. Let me send the error.
00:40 If everything is good, we need to find the user. I can apply await expression on user.findOne method. I need to find the user by email. I can use the local.email. If you check my user model -- let me show you -- I have a local object. Inside the local, I have an email.
01:07 If you check the user, I have already created the user in my database. You will see the email and password. Here, I need to provide the email, value.email, the email of the user.
01:24 If there is no user, I need to send the 401 error, or unauthorized. I can add the 401 status. 401, and let me send the message error, unauthorized.
01:38 Now, we need to compare the user password. I did not compare the user password. I also need to check the user password. I am going to call the decrypt.compare password. Compare sync. I need to provide the hash, which is the password, encrypted password. User.local.password.
02:02 The first variable is plain text, which is the password, using password in plain text. If password does not match, then we need to send the error. I can say that 400.send, or you can use JSON message or error, bad credentials.
02:33 If password has matched successfully, here we need to send the JSON web tokens. We need to import a package, JWT from JSON web token.
02:48 Now, I can use the issue method from the JWT package. JWT.issue or sign method. We need to specify the payload but properties. You want to add in payload. I would like to add the user ID.
03:05 The second value is secret key. I have defined the secret key inside the development.js file, def.secret. Here, we have secret key. Finally, I need to provide the expires and value, the token will be expired after one day.
03:25 We need to send the token in the response. I am going to use that. Success is true, and we need to send the token back, token. First of all, let's try to test the validation. I am going to send the login request. Cool, I've got the error. Email is required.
03:49 Now, I am going to provide the email and password. Let me provide the wrong password. Cool, bad credentials. I am going to provide the correct password. Cool, now I've got the token.