Authentication in NodeJS - REST API with NodeJS and MySQL (2020)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys it's code rossum here and today we will learn how to implement authentication in our api in the last videos we learned how to connect to database how to implement card and data validation so today we will add user registration and use a login with token based authentication so let's get started [Music] honestly i was planning to complete the comments module in this video but i realized that it's almost the same as the post module we did a couple of videos ago so you can do it alone but i'll include the project files in the description down below so today we will learn how to create users and how they can log into the system with token based authentication unlike traditional web applications we don't use sessions to lock the user into the system instead we are using something called token based authentication it's because these apis are stateless so they don't keep any data about the users instead they generate a token users can get that token and include that in their request so the api can understand that this is a valid token and this user is authenticated so in this video we will learn user registration and user login all right so first of all let's install some packages i'm gonna install i'm gonna open up the terminal and npm install that's that save well first package i'm gonna install is bcrypt.js well this package is for hash in the password obviously we cannot store the password in plain text in the database so we need to hash the passwords so this is uh the package we are using for that and i'm gonna need another package for generating tokens we cannot use sessions in our api because apis are stateless they don't store any kind of information about the clients so instead they use uh something called token based authentication so we need to generate tokens for generating tokens i'm going to use the package called json web token and finally i need another package called node mode well this is not regarding authentication this is for automatically restarting the node.js application when we made the changes currently we have to restart the server manually each time we make a change so once this is installed we don't have to do that all right let's install these packages alright so all the packages are installed now let's implement our authentication module i'm gonna create a new controller i'm gonna name that user.controller and here first i'm gonna import the models all right then the package one of the packages we installed decrypt and the other package we installed json web token all right now i'm gonna create a new function i'm gonna name that function sign up so this is the function for creating users all right just like we did before request and response parameters all right first let's um create our user object so this is the object we're gonna save in the table the attributes of this object are name then we get that name from the request body request dot body dot we will put that as name and email oops let me correct this finally we need the password we never store the password in plain text in the database we are hashing the password so we here we need to include the hash password but for now i'm just gonna include the plain text password i'll implement the hashing mechanism in a minute password all right so just like before just like we did in our post controller let's insert this object to our table for that i'm going to access the user model and we can now call the inbuilt function of equalize which is create alright create and we can now pass this object to this and this returns a promise so we can you have to use this then keyword and this catch keyword well if you are not familiar with these promises uh i recommend you to watch uh this 10 minutes video so that you can get a clear understanding about javascript promises all right so this um if this returns a successful response we can get that and we can call this arrow function if it is successful and if it fails we can pass another error function um to run when when that promise is failed all right if the promise is successful we can return the success response to the user just like we did in our post controller here we passed a success response so i'm gonna just copy one of these messages and i'm gonna paste down here i'm just gonna remove some of the response body instead of user instead of post i'm gonna include use all right using created successfully or a similar message may be registration successful all right and for the error 500 data something went wrong all right i'm not done with this yet uh but in order to test this let's uh export this function and let's test this i'm gonna export this module dot export just like this and i'm gonna create a new route file too uh user.js here i'm gonna import express oops then the user controller and router then i can define my endpoint which is a post endpoint and the url segment is sign up then the controller method user control dot the method name is sign up just like this all right then let's export the module all right all right so let's import this route file to our app.js file i'm gonna open up the app.js file and here i'm gonna create a new constant with our user out routes use all right and we need to uh include this prefix we want all our user routes to start from user prefix just like we did with our post route um here user like this so that all our user routes will start with this prefix all right so this looks complete let's open up the terminal and let's start our node.js application npm start looks like we don't have any errors i'm gonna open our api testing line and create a new request i'm gonna name that sign up and it is a post request with the json body and the url should be like http localhost and port 3000 user prefix then sign up all right for the request body i'm gonna include name demo user and the email demo at demo.com let's just add some dummy content and finally the password demo demo alright so that's the request body we include in our sign up request let's hit this endpoint and let's see what happens okay we get a success response um let's check our database to sustainable and of course we have created a new user well like i said i'm not done with this signup function i need to uh i need to hash the password before saving to database let's implement that right now bcrypt has this inbuilt function called hash and as the first argument we need to provide the plain text password and as the second argument we need to provide something called salt the idea behind salt is that it adds some random string to the end of your plain text password so that your password is much harder to guest or be available on a dictionary table dictionary table is something kind of a database that contains the combination of some generic passwords and its hashed versions so if someone got access to your database he has all the hashed passwords he cannot use them to login but he can check on those dictionary tables using the hash password in your database if he found a match he can get the plain text password using that so that's a risk by adding a salt you add a random string to the end of your plain text password so that the chances are less that it can be found in the dictionary table so that's the idea behind adding a salt when hashing a password as the third argument we need to pass a callback function well this is because this function is an asynchronous function and here we as the parameters we need to pass error and the result the result is hash this function generates all right and so that's the function for hash in the password and we need another function for generating this salt well bcrypt has another inbuilt function called gensort and here we need to provide an integer as the number of rounds and as the second parameter we need to pass another callback function and here we need to include the parameters error and the result which is solved all right if you are not familiar with these callback functions this is this is regarding uh asynchronous programming of javascript well i suggest you to watch this 10 minutes video that explains everything about callback functions all right so this second function should be inside the callback function of this gensold function and all of our other code should be inside this second callback function just like this and now we can use our hash password instead of the plain text password all right so i think we are good to go let's open up the terminal and start our node.js application npm start and let's test this with our api testing client i'm gonna hit this endpoint okay we get this success message looks like we don't have any errors let's check the database and let's see yes our second user has been created with the hash password see all right so we have successfully implemented hashing mechanism of our system i'm gonna hit this endpoint again and wait a minute well there's something wrong with this payload here we use the same email for creating both users as you can see in the database we have multiple users with same email well that can happen so we need to check whether the email is already exist in the table all right let's do that right now so for that i'm going to use one of the inbuilt function in sqlize models user then the function is find one with this function we can check if the email already exists in the table for this i'm going to pass an object with vr clause and like this the column name and then the user entered email just like this and this function also return a promise then we can use this then and catch keywords if it returns a successful result we can get that with this function and if it doesn't we can get that error with this function all right so if it returns a successful result we can check if it is true if it is true which means there is a user with that email so we can simply pass an error message like this uh for the status code i'm gonna use four note 9 conflict and the message should be like email already exist and if it is not true then we can um run the rest of our code here so first we check if the email already exist in the table if it does we simply return an error message and if it doesn't we can run the rest of the code generating salt and hash and finally inserting user to the database all right so this looks fine and let me test this opening the terminal npm start looks like we don't have any errors let's open our api testing client and i'm gonna send the request and i get the error message for this email i use the same email as i used in the previous request email already exist and let me change this email a little bit and hit the endpoint hit the send button again now the user created successfully i can hit this button again and email already so this is working as expected we have successfully implemented signup functionality of our api oops let's add this error message to this catch block too all right so that's the sign up function of our api so what's next next let's implement the login functionality for the login functionality i'm gonna write a new function login just like before request and response here we have two steps when the user enters the email and the password first we need to identify if there is a record with that email which means if there is a user registered with that email so if it does if there is a user then we need to check if the passwords are matched if they match which means he is an authenticated user so that we can generate a token and access token for that user so that's the functionality with this uh logging function all right so let's implement that i'm gonna use the user model oops models dot user then we have an inbuilt function called find one and here i'm gonna pass an object with vr clause the column name is email and the value is the email field in the request body just like this and this method returns a promise then we can use this then keyword and this catch keyword then just like before if it returns a successful result which means a user we can run a function and if it returns an error we can run another function all right so if this object is null if that object is null which means there is no user with this email so we can simply return an error response status code is 4.1 unauthorized we can add the message with something like invalid credentials all right and if it is not null then we can check the password we can compare the password with the user entered password and the password in the database for comparing passwords precrypt has an inbuilt function called compare in this method that's the first argument we have to pass the plain text pass which is entered by the user and as the second argument we need to pass the hashed password which is in this user object all right and then as the third argument we have to pass a callback function like this and we can add parameters error and result okay so if the result is true which means passwords match the result is true which means the passwords match then we can generate a token an access token for the user all right let's first create a new constant token for generating the token we use that json web token package we imported to our controller jwt it has a method called sign all right um we need to pass an object with the details we want to include in our token i want to i want to include email and user id all right and as the second parameter of this sine function we need to add a secret i'm just gonna add uh i'm just gonna hard code this uh secret string here but it's not a good practice normally you would want to include this secret in an as an environment variable i'll get to that at the end of this tutorial for now i'm just hard coding this here and as the third argument just a callback function like i said if you are not if you are not familiar with these callback functions which is really easy uh just watch this short tutorial i created it explained everything about callback functions all right so as the parameters so you need to pass error and the token the result is the token all right so in the body of this callback function we can return a success message like this the status quo should be 200 and the message should be authentication successful and then the token just like that and we can include some message over here as well something went wrong in case in case of some internal server and i forgot to add the else clause of this if statement uh if this is not true which means the authentication failed so we can send the same response here as well all right this is looking good let's uh export that here login all right and we can open the route file of the user we can create a new route it is a post request login and the user controller function name is login all right so let's restart the server and test this with our api testing client all right we don't have any errors i'm gonna create a new request request name is login and it is supposed request with the json body for the json body email and the password url should be http localhost port 3000 user then login and before sending this request let me clear the database usage table because there are some uses with plain text password so this is an inconsistent data structure so that let's clear the database and we don't have any uses let's create a user first so let me the demo user demo at demo.com password this demo demo all right hit the endpoint user created successfully then the login endpoint email is demo at demo.com password this demo demo let's hit this request and let's see what happens oops um i have a typo here all right yes we successfully generate the token with this authentication successful message so we entered the email and the password correct let me change the password to a wrong password and hit that endpoint again then we get the response of invalid credentials what if the email is incorrect then we again we get the same invalid credential response so this is looking good this is working as expected so we have successfully implemented the authentication functionality of api so as a homework you can add um data validation to these two functions just like we did in our pos controller we implemented this um validation so just like we did here you can add that validation to sign up method and login method to make sure the email and password are not empty or they are valid emails or not just like that so do it as a homework so that this module is complete before winding up this video let's just add one more thing which is not mon for now uh currently we have to restart the server each time we make a change to our code but with nodemon we don't have to manually restart the server because it automatically uh does that for that we installed the package nodemon initially now i'm going to open up this package.json file and here in the script array i just want to add new field called start here as the command i just type nodemon and script which is the server.js all right so hit save and open up the terminal now run npm start this will start the server with node mode now i'm gonna open my one of my controllers and i make a slight change i'll add comment just like this then i hit save then then as you can see uh northbound restart the application automatically so that we don't have to manually restart the server each time we make a change so this is really easy when we are doing the development keep in mind that this is a development dependency we don't want to do that in the production environment just a development dependency all right so that's been it that's how we can add the authentication to our api in the next video we will learn how to add a middleware and protect some routes so that only the authenticated users can access those resources alright so stay tuned subscribe if you haven't already and i'll see you guys very soon in the next video
Info
Channel: coder awesome
Views: 19,323
Rating: undefined out of 5
Keywords: node js authentication, Authentication in Nodejs, express rest api, node js express tutorial, nodejs and express with mysql, Authentication in NodeJS - REST API with NodeJS and MySQL (2020), generate access token, token based authentication in nodejs, hash password in nodejs, user registration in nodejs, user login in node js, nodejs rest api, setting up authentication in nodejs, user signup in nodejs, create users in nodejs, jsonwebtoken nodejs example, jsonwebtoken express
Id: OfC8BrlEdtA
Channel Id: undefined
Length: 37min 2sec (2222 seconds)
Published: Sat Oct 24 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.