JWT Authentication Tutorial With Express & MongoDB | Rest API Project | Node.js for Beginners #10

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's going on guys welcome back to another video in a node.js for beginner series and in this video we will continue to build our contact manager app using Express and mongodb we will introduce the authentication and for that we will create the registration and the login endpoint we will also see how we can hash the raw password and we can provide the user with the JWT access token so if this sounds interesting then stick around also don't forget to subscribe the channel and press the Bell icon so that you don't miss the videos like this one so let's get started [Music] alright guys so I'm using the same application code which we built in a previous video so if you have missed that video then you can click on the card above and jump to it directly so now let's start with the authentication uh module and in the authentication what we will do is we are going to provide some endpoints which will help us a user to register themselves and then login and once they log in they can use a access token and then with the help of the access token they can manage their contacts so now let's start with the routing first so what I will do is I'm going to go to my server.js and inside the server.js I'm going to copy this and then I'm going to add here and this time our API URL will be the users as we are going to register the user and then we are going to have a login user so what I'm going to do is I'm going to change this to the user routes so let's have the user routes and now let's go and create the user routes file so I will go to my routes and inside the routes I'm going to create a new file which will be the user routes dot JS so now in the useroute.js let's first import the express so I'm going to have the constant I will have the express and this will be equals to the require and I will have the express and then I'm going to have the router so let's have the router and this router will be coming from the Express dot router methods so I'm going to call the router method now let's create the route so what I will have is I'm going to have the router.host and on this post I will have the register and when we have the register we are going to have the request response and then we can have the response dot Json and this response can't be I will have the message and I will have the register the user and then we can have a login endpoint so that will help our users to log in so I'm going to have the login and I will also create one more endpoint that will give the information of the current user so let's have a slash current all right I'm going to change this to login user so let me have the login user and I will change this to current user information so let's have the current user information and now let's give a try so I will go back here and here instead of this I'm going to have the user users slash register and I'm going to send so I see that we get an error so it should be a post request so now let's send it and we still see an error so probably let's see that our application is running or not so I'm going to open the terminal and here what we see is that we have an error and the error is expressed dot router is not a function all right so we made a mistake now let's go to the user route and this should be capital r now I will save it and we still have an error now let's go and fix that in the server.js on line number 13 we have an error so I will go to the server.js and online number 13 we have an error that there is no user route so we need to export the user route so let's go here and let's have the module dot export and I'm going to export the router all right so that it is now available in my server.js now everything works fine let's go and let's check so if I go to this URL or API uses register and if I'm make a send then we see that we have registered the user similarly let's go and check for the login and I see that we have the login and then let's have the current user so if I click then we see the current user but since the current user should be a get request and not post so let's go and let's make this change so it should be a get request all right so now the next thing we will do is we are going to create the controller for the users so let's go to the controller and let's create the usercontroller.js so I will go here I will have the user controller dot JS and then in the usercontroller.js what we can do is we can just do simply a copy paste of this and I'm going to have hit here and the first thing we are going to have is to register a user so let's have a register a user and we are going to have a post method this will be users slash register and this will be a public access so anyone can access the endpoint point and then register the user we will change this to register user whoops so this will become registered user and inside this this one we can now remove this and we can go to the user route and we can cut this and we can add that in the controller so let's go here and let's add in the controller I will save it and now let's go and Export it so I will have the module dot export and then we will export the registered user so I'm going to copy and I'm going to add it here now we will also need to import it in the user routes so we can import it so let's have the register user and you will see that it gets Auto imported so now we have to create the login user as well so let's go to our controller back and I'm going to copy this I will add it here and I will change this to login user so this will be login user I will have the login user this will be a post API and the endpoint will be the login it will will be a public endpoint and then we can change this so let's go here and I'm going to cut this and let's add that in our controller so I'm going to go here and I'm going to add it here and I'm going to export the login user as well now the third one is the current info of the user so what we will do is let's create one more method all right and this time this method will be a private method so only a logged in user can get the current information of a user so now this will change to the current user info the endpoint will now change to current it will be a private and here I'm going to have the current user let's cut this so I'm going to cut this and I will add it here so let me add that here and I will save it we are going to now export the current user so let's add the current user and let's import the current user here so I'm going to import the current user and I will also import the login user now let's copy the login user and provide the login user function here and for the current user I'm going to provide the current user here I will save it and we see that we get an error so let's go and see what the error is so in the user controller line number four so let's go to the user controller and on line number four uh we see that I don't see any error but what is the error it says a sync Handler is not defined and we need to import the async Handler so what we will do is I'm going to have the constant async Handler and this will be equals to the require and I will have the express async Handler all right I will save it so now everything should work fine we see that now we don't see the error and what I will do is I'm going to close this contact controller and also close the contact model and now let's give a try so if I run it then we'll still see that we get the correct response register the user so now we have created it now the next thing what we have to do is uh we need to make the functionality for register the user and for that first we have to create the user model so let's go and create the user model so I'm going to go here and I'm going to create a new file and let's name it as the user model dot JS and in the usermodel.js let's import the Mongoose this will be equals to the require and I'm going to add the Mongols here then I'm going to create a constant with user schema and this will be equals to the Mongoose dot schema and this will be an object and what values we will need in order to register a user the first property I need is the username so let's have the username and this username will be of type ring so I will have the username of type string then I will have the I misspell the type then I will have the required and yes this fill is required so I'm going to have it as true and I will have a message as please add the user name the second field is we need to have an email address of the user to register the user so for that I will have a type as string and then I will have the required field so let me have the required and the required will have the flag as true and then the message is please add the user email address I'm also going to add one more property which is the unique so that I need a unique email address every time when a user is registered so no duplicate user with the same email ID can register themselves so I will add a property called unique I will have the flag as true and then whenever someone tried to register themselves with the same email address what I will have a message that email address already taken so that we can prevent them to register twice with the same email address and we will also need the password so let's have the password fill I will have the type as string all right then I will have the required fill so let's have the required and it will have a flag as true and I will have the please add the user password all right I will save it and I will just change this to small L and then we will also need the timestamp so let's add the timestamp so I'm going to have the time stems and I will have it as true and then what we can do is now we can use the module export and we can export the schema so I will have the module exports and this will be equals to the Mongoose dot model and let's name the model as user so I will have the user and then I can have the user schema so now we have created the model as well the next thing what we can do is now let's write the functionality in order to register a user so I will go to my controller and whenever a user wants to register themselves they need to provide the username email address and the password in the request body so what we are going to do is uh let's restructure those info Mission so what I will do I will have a constant I will have the username the email address and the password of the user and all these three fills we will get it from the request dot body and once we have it we are going to make a check that if the username is not empty or the email is not empty or the password is not empty so I will have it and in that case what we will do is we are going to send a response status as 400 so the validation is failed and we will send a we will throw an error actually so I will have the throw new error so we will have an error object and then we will have all fields are mandatory so before creating a user what we will see is we are first going to check that whether with the particular email address do we already have an existing user in our database or not so what I will do is I'm going to have a constant user available and then I can make use of an await keyword and then we can use the user mode model in order to interact with our mongodb database so let's import the user model first so I will have the constant user and this will be equals to the require then I'm going to have the dot dot slash models slash user model and we can now have the update we can use the user model and then we can do a find one and this is going to help us to find a user which is already have in our database with the email address so let's use this email address and check so I'm going to add it here and now if we have the email address so we need to pass the email address in an object so let me have an email address as an object and now if we find this user available so let's go here and let's have a check on that so if we have a user then in that case we are going to throw an error which will again be a validation error and we will have a status as 400 and this time the message will be that user already registered and and then what we will do is if we don't find any user then in that case we are going to create a new user in our database so before creating a new user what we have to do is we are accepting the username email address and the password from the client but since the password is a raw password and we cannot store the raw password into our database so for that we need to Hash our password and in order to Hash the password we are going to make use of a library called Big Crypt so let's import the bcrip library so if we go to the packet Json we see that we don't have a bcrip library so I'm going to open a new terminal and then I'm going to install the B Crypt so let me have the npm install Big Crypt and I will hit enter so now we have the bcrip library and now let's go and use that so what I will do is I'm going to import the bcrypt so let me have a constant Big Crypt this will be equals to require and then I will have the Big crib and you will find the this bcrypt documentation on the npm official documentation but I'll show you how we can use it so it's very simple to use it and what we have to do first is we need to create the hash password so I will have the hash password and how we are going to create is I'm going to create a constant with an hashed password and this will be equals to so bcrip is also going to provide us a promise so that's why we are going to use an addressing a weight and I will have the bcrypt dot hash and then in this we first need to pass the raw password so our raw password is available in the password and then we can provide the solved rounds so this 10 is just the number of solved rounds that we want for the hashing of the password so you can use this and now if we do a console DOT log then we will be able to see the hashed password so let me have the hashed password all right and then I'm going to use the hash password I will save it and then what we are going to do is uh let's go and check first so if I go back here and we have the post register and in order to register a user what I will have is I will have the user name okay and let's have the username as the malvia then I will have the email address and we don't need a phone we will have a password and I'm going to give the password as one two three four five six now I'm going to click on send so we can see the logs and when I click on send you will see that we have the hashed password so this is the hash password we are going to store in the database so that we can prevent or we can have the security of the user password so now let's go back to the user controller and now we already have the hashed password and what we will do is now we can create a new user so I want to create a new user so let's have a constant of the user I will have the user model and that will give me an Access to create and whenever I want to create a user what I will have is I'm going to have the username I will have the email and then I'm gonna have the password so let's have the password and the value of the password will not be password we are going to use the hashed password I will save it and then what we can see is uh once a user is created so I will do a console log of the user so that we know that a user is created successfully so I will have the user created I'm going to have the dollar user and now we need to send the information to the user so whenever we need to send the information to the user I don't want to send the complete user because this will also contain my hash password so what I will do is now if we have a successful user created then in that case I want to have the response dot status as201 that is the resources created and then I'm going to pass the Json data and I want to pass the ID so I will have the user dot ID and then I will also pass the user email address so let me have the email address and this will be the use dot email address and if there is a problem then in that case what we will do is I'm going to throw an error so I will have here and I will have the response dot status as 400 all right and then let's throw an error so I will have the new error object and I will say that user data is not valid so that means the request was not valid so that's why we were not able to create the new user all right so now we have done this uh if we want to test it what we can do is we can go to our new request and here we can try to test it so I can go and send a request and you will see that when I send a request I get a response back as status 201 created so my resource which is a particular user is already created in the database and in response to that I get the ID of my user which is created and then the email address now if I try to submit it once again then in that case we are going to get an error and that is because the user already registered and we have made a check here so if you will see that if we have a user and if we find it one in with the help of the email address we throw an error that the user is already registered and now if we want to verify that in our database then we can go to our mongodb so let me go to the mongodb and this is our collection and inside the users if we go and then we will see that this is the user we just have created so this is what uh we have now the register user we now need to create an endpoint for the login so that whenever a user is login we get an access token and for that we are going to make use of a Json web token so let's go back in our Visual Studio code and here what we will do is before using the Json web token I want to go to the Json web token website and I want to show you something so I will go to the jsonweb token.io and then what we will do is uh whenever we have a Json web token so this is sample Json web token and you will see that it contains three parts the first part is actually the header algorithm of the token so it's have a algo type of hs256 and it's a type of web token now the next piece of information which is in the pink color uh that is actually the payload and that payload we are going to have the user information that we are going to add in our token so and third part you will see it's the signature verification so this is how a Json web token is and it consists of three different parts now let's go and let's add it in our application so what I will do is let's go and first install the Json web token so I'm going to have the npm install Json web token now if we go to the package Json we should be able to see the Json web token all right so now let's work on the login functionality or the login endpoint so if we go to the user controller and in the login endpoint what we want is whenever a client is sending the email address and the password in that case we need to match the password and then we provide the user back with a access token so what I will do is I'm going to have a constant and then I'm going to have the JWT and then I will have the require and this will have the Json web token and then I'm going to go to my login function so this is the login user function and whenever a user is trying to log in they send in the request body the email address and the password so let's fetch the email address and the password first so what I will do is I'm going to have a constant I will have the email and then I will have the password then this will be equals to the request dot body and then we will just make a check that if we don't have an email or we don't have a password I misspell the password then in that case we need to the response status as 400 that is a validation failure and then let's throw an error so I will have the new error and then we will have have all fields are mandatory but if we have a proper email address and the password then in that case first we need to find that whether there is a user in the database or not so what I will do is I'm going to have a constant user and then I will have the update we are going to use the user model and then we will use the find one then we are going to pass an email address and this will help us to identify that a user is already present in the database uh or not once we have the user then we need to compare the password which is stored in our database and the password which we have received from the client so what we will do is uh let's have the compare password with hashed password and what we can do is uh it's very easy to compare first we need a user and along with that we will also make a check on the password so in order to do that we can use the B Crypt method which is a compare so let's use that b Crypt dot compare and then we are comparing the password which we received from the client in the request body with the hashed password so that will be the user dot password and this user is the user that we are stored in our database and which we are retrieving here we have the user we can now compare the password with the user.password and if this matches in that case what we need to do is we need to provide an access token in the response so what we will do is uh we are going to have a response dot status and the status will be 200 and then we are going to have a Json and in the Json we are going to pass the access token so let's have the access token now we need to know what is this access token is now this is where we are going to use the Json web token so now let's have and create this access token so what we will do is let's create a constant with an access token and then we can can use the JWT which we have imported here JWT and it has a method of signing we need to sign a new token for our user so what I will do is I'm going to have the JWT DOT sign in and this JWT DOT sign in is going to take few parameters so it will be an object and we need to provide the payload so if we go back to our browser then you will see that we have a payload and inside this payload we can actually pass the information which we want in our token so let's go back and here what I want is my payload will be the user information which I want to embed but I don't want to embed the user password so what I will do is I will have a user object as my payload and then I will embed the username so this username will be equals to the user dot username I will also have the email address which will be equals to the user dot email and then I'm going to have the ID which will be equal to the user dot ID so this is my payload which I'm going to embed in my token now the next thing is uh we have to provide an access token secret so in order to get the access token secret what we can do is we can just Define a unique access token Secret in our environment variable file so let's go to the environment variable file and here what I will do is I can simply have the access token so I will have the access token secret and then you can define a unique secret key value here so for now what I will do is I'm going to Simply add the the page one two three as the secret but you should not do it when you do a production level code so what we'll do is I'm going to go to the user controller and here I can use the access token secret so in order to fetch a value from the environment variable we can make use of a process core module and then we are going to have an EnV we will have the access token secret so I'm going to just copy this all right let's add it yeah okay so now we have that and there is one more property which we need to pass and that is the expiration time of our token so we are generating a token but we need to also provide the expiration date of that token so that after this token is expired users should not be able to use the token in order to call the apis so what we will do is we are going to set the expiry time and let's set the expiry time as one minute so this is just for the testing purpose we are going to set the expiration time as one minute and once we have this we have the access token and let's pass the access token as a response and if there is a error then we will have an else and what we will do is we will have the response dot status of 401 and that will be uh that email or the password is not valid so the thing is that if this is not true that means we don't find a user or we don't match the user provided password with the stored password then in that case there is a problem with the credentials and we are going to pass 401 and let's throw an error so I'm going to throw in an error so let's have an error object and then I will have a message as email or password oops I made a mistake password is not valid all right I will save it and now I can just remove this so I'm going to remove this and I will save it now let's give a try so what we will do is uh I will go in the new request and here instead of the register I will have the login and I'm just going to remove this username and now let's send the request so if I click on the send then you will see that we have the access token so now we are able to get the access token now what we can do is uh we can use this access token and can access all our private routes if we go to the uh contact controller then you see that we have all the public routes and now we are going to make this as a private route so the next thing what we are going to do is we are going to make all our public routes as a private routes and we are going to enforce a validation on those public routes so only authenticated user can access those private routes so what we will do is first let's start with the user controller and in the user controller we will first go with the current user info now to access this endpoint the current user info we need an access token I mean the client has to pass an access token so that only authenticated user will be able to access this route so what we will do is let's go to the user routes and in the user routes what we have to do is but before we do anything in the user routes we need to make a middleware which is going to help us to validate the token which a client is sending in our request as a bearer token so what we will do is I will go here and I'm going to change this to current and then what a client will do I mean the user is going to have this token and they are going to pass the token in the bearer section and I will send it here and then when a user sent the request I have to validate this token I have to verify that the token is a correct token and it is associated with a correct user so for that what we will do is we are going to create a middleware so that where we can verify the token so I'm going to create a new file and then I will have the validate tokenhandler.js and in this what we will do is first let's import the async Handler so I will have the async Handler and this will be required I will have the express async Handler and then the next thing is we will also need the JWT Json web token so let's import that and I will have the require and then I will have the Json web token I'm going to create a constant validate token function so I will have the async Handler and inside inside the async Handler what I will do is I'm going to have the async and we are going to have the request response and then we will have the next so this is a middleware and you will see that we have a very similar middleware as error Handler also and in the error Handler also we have the request response and the next and we also have the error now what I will do is I'm going to create a token variable here and then what we will do is whenever a user is sending a request the token is actually passed in the header section with the auth field so either you can pass it here as a bearer token or you can have an authorization field here so you can also create a new value which will be an authorization and then in the value what you can do is you can use the bearer and then you can add the token here so either you do this way or if we pass it here in both the cases we should be able to manage to have a check on our backend so what I will do is uh let auth header and this will be equals to the request dot headers dot authorization so if we have this kind of an authorization so I will copy and I will add it here or if a user is having an authorization uh like this so I'm going to copy and then if a user have an authorization like this so in both the cases we will have the auth header and now what we'll do is that if we have this auth header then in that case we will also make a check that we have an auth header that starts from so I will have the starts with and our authorization header always starts with a bearer so we need to have the auth in a bearer token so what we will do is we are going to go and check for the bearer keywords so if we have Bearer then in those cases what we need to do is let's extract the token first so we are going to have the token variable and we need to extract from the auth header so what I will do is I'm going to make use of a split and then I will split with a space bar so if we go here and you will see that we have a bearer and then we have a space so let's split it with the space bar and then we are going to use the value of the first index so if we go here the first the zeroth index will contain the bearer and the first index will contain the token so that's where we use the first index we have the token and now what we need to do is we need to verify this tokens so to verify we will use the JWT dot verify and then we need to pass the token we also need to pass the access key so process dot EnV dot access token key so I'm going to go here I will copy and I will add it here and the third parameter will be a callback function so this will have an error and then we will have a decoded user or decoded information now if we have an error then in that case we will have a response status as four zero one and we are going to throw an error so let's throw an error so I'm going to have a a new keyword and then we are going to throw an error as user is not authorized so we are trying to verify the token but user is given a token which is not a valid token or he is using a token from some other users so in that case we are going to say that user is not authorized but if a user is using a erect token then we are going to get the user information so what we will do is let's have a console.log and I will log the decoded and I will save it now what we can do is in order to make use of this validate token we can go to the user routes so first let's uh export this so I will have the module dot export and this will be equal to the validate token so I'm going to have the validate token here all right I will save it and then what we will do is let's go to the user route and in the user route I can make use of a validate token because since only current user was the private route so I will have here the validate token it's Auto import it now let's go and let's give a try so I will have a API slash user slash current and when I send a request then we see that we have a 404 and that is because the endpoint for the user current has a get method so let's change this to get and I will also go here and let's send the request and since we send the request we see the user is not authorized that means the token is either an expired token or the token is not a valid token so we first need to fetch a new token so what I will do is I'm going to create a a new request so let's go to the client I will have a new request and I will just copy this all right I will add it here and I will just do a login of the user first so let's login the user all right I need to pass the body so whenever I need to log in I will have the email address as the page oops I don't remember the email address and then I will have the password as one two three four five six so let's go and check the email address so I will go here I will have the email address so I'm going to copy the email address and let's add the email address here and this will be the email this will be the password so we have the request body now uh let's go and let's send it and we get the access token now let's copy the access token and now let's use the current which is a protected route so I'm going to go to my oh I will just remove this I will go to the auth and I will add my token here and now I will send the request and you see that when I send the dick to best what we see is this is the decoded user we have so we have logged the decoded user but we also see that uh cannot set the headers after they are sent to the client so we are doing some mistake here and what we will do is uh let's go to our validate token so I'm going to go to my validate token uh here and we have the decoded user here so what we will do is uh in the decoded user we can have the decoded dot user which will give us the user information so this is the user so what I will do do is I will append this on my request dot user and then I will have this decoded dot user so what I have done here is that uh I have verified the token and I have extracted the information which was embedded in the token so the information which was embedded in the token was the this one the user information the expiry and the creation of the token and then I have taken the decoded dot user and this information I have attached this information to my request dot user property and then I'm going to have the next so this is a middleware so I'm just going to intercept the request I'm going to decode the token and then I'm going to append the user information on the request body not on the request body but on the request dot user property and now we will also make a check that if this we don't have a token then in that case that means the token is not provided or the token is or the user is not authorized so let's have a response Dot status as 401 and we will throw an error so I will have the throw new error and the error will be that user is not authorized or token is missing in the request I will save it all right now let's go and give a try so I will go back here and then I'm going to send that so I'm sending it and I see the token is expired so let's go and have a new token all right I'm going to copy this I'm going to add it here so in the bearer token let's add it and now I'm going to send and you see that the current user information since we are not fetching the information from our database but this is a protected route so if you don't have an access token you will not be able to access this route so now we have successfully verified the Json web token and we have also used it on a private route now what we need to do is whenever someone is requesting the current user information we need to go to the database in the mongodb and then we need to fetch the information and then provide it as a response so let's go to our user controller back and here what we will do is I'm going to go and I will remove this and here I'm going to have the request dot user and that will give me the user information because if we go to the validate token then we extract the user information and we put it as request dot user so when we have the request in that case we will just send the request.user so let's go and let's do so I'm going to send the request and since the token expired let's have a new token I'm going to copy this let's use the token in the auth and I'm going to send it and you see that this is the information of my current user the username is D malbia email address and then I have the ID all right so the next thing what we need to do is we need to protect all our contacts route so only a logged in user will be able to create delete update and read the context which they have created for themselves so what we will do is first we need to associate whenever you create a new contact we need to associate that contact with the user ID who is creating it so let's go in the contact model and in the contact model we need to update this model so what I will do is I'm going to add a new property and this new property will be the user ID and this ID will be for the user who is creating the contact and what we will do is we are going to have a type of this and the type of this ID will be the Mongoose dot schema dot types dot object ID because this ID is actually created in the mongodb and that's where we have the object ID and then we are going to use is as required so whenever you create a new contact we need to always have an i user ID so that's how it will be associated with the particular user so I'm going to have it as true and I need to provide the reference of the model so the model is user so we have made this first change and now what we have to do is the next thing we need to go to our contact controller and we need to make all the routes as private so I will go to the contact controller and let's change this to private I'm going to copy I'm going to add it here I will also add it here then I will also add it here and then I will also add it here all right we have it and now let's use the validate token as a middleware for all the routes which we have so if we go to the contact routes then in the contact routes what we will do is we are going to make use of a validate token so this validate token will be used for all the routes so we are not going to use here validate token for each of the method but what we will do is we will have the router dot use so we are going to use a validate token on all the routes and let's get Auto imported so this is also one of the way you can do it if you have all the routes as protected route and you need to validate the token on all the routes or if you have only some of the routes then in that case you can make use like this all right so now let's go to the contact controller and in the contact controller now let's make use of the user ID and then we do the current operations so the first we will start with that I need to find my contacts so I need to find all the contacts with the user who is logged in so we need to fetch all the contacts of a logged in user so for that what we will have is we are going to have the user ID and this will be equals to the request dot user dot ID and I will save it and this user ID is the one we have just added in our contact model so this is the user ID so now if we go and try but before trying it what I want to do is I don't want my token to get expired every time so I will increase the expiration time of my token so I will go to the user controller and in the user controller we are set as one minute so let's make it as 15 minutes and now I will go here and I will first log in with the token so I'm going to log in all right then I'm going to have my token and then what I will do is I'm going to have my contact and then I'm going to pass this token and now I'm going to fetch all the contacts which are created by the username the page malvia so I'm going to send it and we see that we get an empty arrays because right now there is no contact being created for this user which is the page now the user which is the page is going to create some contacts so if we want to create the contacts we are going to have a post request and in the post request what we will do is let's have a name and my contact is uh John so let me create a contact which is a John Day and the email address of John day is just uh John the gmail.com and then we have a phone so let me have a phone and I will have one two three oops I will have zero nine eight something something something so this is the contact which the page wants to create created so we also have a valid token and now if we send it we should be able to create it so let's go to our controller first and not in the user controller we need to go to our okay let's close the packet Json let's close the environment variable file let's close the contact model and we now only interested in the contact controller now in the contract controller whenever we want to create a new contact what we need is we need to have the name email and phone number but along with that we will also need to associate the user ID who is creating this so what I will do is I'm going to have the user ID and this user ID will be equals to the request.user.id since we are using this as a middleware whenever we have a request this middleware is going to decode the token and then it's going to add the request dot user property and in the request.user property we will find the ID and then we can now create this contact all right let's go and let's give a try I will save it and now I will go and create it so if I send the request now you will see that this is the user ID of the page and the page now have created a contact for with the name as John day and now what we can do is we can create multiple contacts for the page so uh in the next contact I'm going to create is nikesh G and then the email address is NYX and I'm going to change this phone number and then I'm going to send and you see that we have created a contact now if I want to see all the contacts which the page has created then I'm going to send request and you will see that we have two contacts which is created by the page now what I will do is I'm going to create a new user and then I'm going to see that the new user is able to get all this contacts or not so let's go back here and let's register a new user so I will have a new user so I will do the register and I'm going to pass the user name and the username this time will be let's have a user as Mark so Mark is is an another user so we will have the email address as Ma at the red gmail.com and then I'm going to send it and we see that now a new user is created which is Mark now let's login with Mark so I'm going to log in with Mark so I will change the url as login and I'm going to just remove this all right I will send the request and we get an access token so I'm going to copy the access token and now what I'm trying to do is so now this access token is for the user the page and if we send the request he has created two contacts but now I want to change this for token for a mark and now this token belongs to Mark and if I send a request then you will see that we don't have any contacts because Mark doesn't created any new contacts for himself so this is how we are preventing cross user uh trying to access the contacts from other users and that's where the authentication is done the next thing we need to do is we need to update and delete the contact for a user so let's go to the contact controller back and here what we will do is uh whenever we need to get a contact we can get the contact with the help of a request dot dot param.id but if we want to update the contact what we will do is first we are going to fetch the contact from our database with the help of the ID and then this contact will contain the user ID of a user who has created so what we will do is uh before updating the contact we will make a check and the check will be that if the contact which we have just fetched as dot user ID dot to string and if this not equals to the request dot user dot ID then in that case we will know that a different user is trying to update a contact of an another user so what we will do is we are going to throw an error so I will have the response dot status and the status will be 403 because a user is not authorized to update a contact of an another user and then I will throw an error so I will have the new error and then I will have the error as user don't have permission to update other user contacts so we have handled that case and if it matches so the contact.user ID matches with the request dot user ID then in that case we are going to Simply update the contact and we need to do a very similar thing for the delete also so I'm going to copy this in the delete also we first fetch the contact from the database we have the contact we checked that if the contact is found then in that case we remove it but before removing it we need to check that the contact which we found has a user ID and that user ID should match with the request.user.id and then we will have oops we made a mistake so user don't and this will also users don't so now we have protected all our crud operations of the contacts uh with the Json web token and now if we go and simply do a testing of it then we see that this token is for the mark and if we let's go and let's get the token for the page again so what I will do is I'm going to have page and I will send a request oops the email ID and the password is wrong so probably the email ID will be the page dot malvia all right now we have the token Now using this token I want to see that what all contacts this particular user has so this user has two contacts now a user want to update this contact so I'm going to copy this let's have a contact here if I go to the body then I will have an updated contact as nikesh gadekar and I will make it updated I will send it and you will see that we have a contact but we made a mistake because it's a get and we need to make a put in order to update it and now I will send it and as soon as I send it you will see that the contact is updated nikesh gadekar update now what I will do is I'm going to remove this then I'm going to make a get and we get the contacts back with an updated contact now I want to delete this contact so I'm going to copy this and let's have here and I'm going to delete so let me have this and I'm going to send the request and you will see that it's 200 and hopefully this contact is deleted now so if I go and try to do a get on it then I should not be able to found the contacts so we see that the contact not found now what we will do is uh let's go and let's fetch all the contacts back so we don't have any contact so there is a problem so what we have done is if we go here and if we see then what we are doing is we are doing the contact dot remove and that is removing all the contacts from our database but we only want to remove the contact for which the user is passing the ID so what we will do is uh we will have to make a change here and we are going to have a delete one and which ID we need to delete is we're going to have the underscore and then we are going to have the request dot param dot ID now let's give a try so what I will do is first I'm going to create some contacts so I will go here and I will send a post or write a contact is created let's create an another contact back so I will have the next contact as John day and then I'm going to have this as John and then I will send it so now if I go and fetch then we see that we have two contacts and now I want to delete this updated so I'm going to copy this I'm going to add it here and then I'm going to go and do delete and I will send it so we see that okay it's 200 and the contact is deleted so if we go and do a get we should have contact not found but if we want to fetch all the contacts we still should have the John Day so you see that we have the John Day so now we have fixed the problem uh with the contact dot remove so we should use the contact dot delete one so we have created all the crud API of the contacts so we can now make use of the contacts API and then we can manage the contact based on the user so we also have a register user login user and then once a user is logged in he can create update delete and read all the contacts which he has created and similar we can now have multiple users and they can they can manage their own contacts so that's all I have in this video I hope you liked the video a thumbs up is appreciated you can also connect with me my Facebook or Instagram you can follow me on Twitter for latest update and before you go don't forget to subscribe the channel and press the Bell icon so that you don't miss the videos like this one thank you thanks for watching
Info
Channel: Dipesh Malvia
Views: 17,013
Rating: undefined out of 5
Keywords: jwt, json web token, jwt authentication, jwt token, jwt security, node jwt tutorial, jwt auth, jwt authentication node js, jwt node js express, jwt express mongodb, dipesh malvia, json web token authentication node js, json web token authentication, express project tutorial, node js for beginners, jwt express, user authentication, express authentication, login authentication, express password hashing, node authentication jwt, node js project, node js express
Id: ICMnoKxlYYg
Channel Id: undefined
Length: 50min 17sec (3017 seconds)
Published: Thu Dec 15 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.