Mastering Node.js: Role-Based Authentication API Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
now if we try to look inside our private property we can do this cool man this is private you are inside the private property but let's try to change it to admin and let's try to send this protected only for admin remember this even though I already have bunch of authentication video in this channel you want the another one and you want the role based authentication using nodejs and react native and if I try to create all those things in the single video it is going to take a lot of time so what I will do in this video we'll see how we can create authentication with the role based or role based authentication whatever you want to call it we'll create the apep part and in the next video I'll explain how we can connect that thing to our react n application so without any further Ado let's get started first of all you have to obviously open your terminal and my terminal is just filled with all these things so that's how your terminal will look at first and let me fill everything with this terminal now what I will do we'll simply go to our favorite folder maybe you have this somewhere I don't know I have this inside this desktop app and inside here I have bunch of these folders which I'm not going to show you at all so let's just create this new folder here and what we will call it so let's call it react native and bunch of time I'm going to see something like this because my keyboard is hiding behind this mic so I can see right there so Rea native what I was thinking okay Rea native o let's go back to our react native and I don't know what I'm doing cdrn Das o let's go to this rnas o and what we will do here and again inside this we are going to create two folders one is going to be subo and another is going to be the exact react native application but what I will do I'll open Chrome and then I'll go to the github.com and I will copy this node TS set up so this is the repo that I already have and here you can simply install it and this is going to give you the node and the typescript setup which you can use to create servers okay now if you want to follow the step-by-step guide I already have a video how you can do this I will leave a link in the description box below from there you can go and watch the video and try to create the setup on your own and the main thing is here you will also get the path allias so you can use something like this so I'm just going to clone the repo so I'm going to copy the URL and I'm going to just and you can hear the sound so I can't do anything about that get what the hell the one thing I can do is I can just stop talking so let's just do this G clone so that we can have that repo right here and I'm going to call it server and let's just wait everything is done let's move to our server folder and now we can simply open it inside our code editor now this is going to be your server what you will do first of all you will install everything npmi and it is going to install everything inside it so nothing that is just few the of these things like the typescript for nodejs and all these things to set up our environment so that we can have the Run build start all these commands now everything is there now if you want to find more about this just go and watch my previous video otherwise let's just open our terminal and what we need we need Express so I'm going to install Express if I can type and I also want the type for this Express so at types SL Express and what else we need we will need mongod DB so I'm going to also install mongos and also we'll need the type for this mongus so I'm going to use this types SL mongus or by the way mongus comes with the type maybe let's just press enter okay that's it now the very first thing that you will do you will come inside your index.ts and you will create your server right so let's import Express or maybe let me bump things a little bit so that you can see everything clearly so we are going to import Express if I can type from Express and the thing that you will do you will create this app with the express function like this and you are going to use this app. listen so that your app can listen and you have to have the port number so I'm going to create something called port and this call back function will fire so I'm going to use this back tick so that I can also use the port number here app is running on let's use this HTTP column double slash Local Host colum the port number so again I'm going to do like this okay let's create this port right here so this is going to be port and where this port will be this will be inside this process. env. port or because we are running this inside this local environment so there will be no port or there will be no process envirment Port you can obviously add this inside EnV file but I'm going to just see like this and add this 8,000 as our port number now that's it this is your Express server ladies and gentlemen if you do this npm run Dev you should have something okay you just run it inside this particular URL now if you control click on this one it is going to obviously give you this error and the reason for that is you have nothing called gate route so what you can do you can use this app.get on this Home Route and why this Home Route because if you come here this is going to give you the slash if you notice right here so this is going to give you the slash so if you have nothing after this this is your home route this is slash back slash whatever you want to call it okay now here you will have the request and the response and I hope you already know about these things if you don't go and watch the previous videos I'll again leave their Link in the description box below now here you can simply have the things that is coming from your front end inside your request that can be header that can be body or anything that you're sending but because this is the gate request there will be nothing called body but what we can do we can simply send the response back let's just send the Json response back okay true if I can type these true things okay now I'm going to Simply reload this and as you can see okay true so it means your server is running completely fine right now the next thing that we need is the I don't know what we need we need I think models I'm going to create this user. TS so that we can store new users inside our mongodb database and I'm using mongodb you can use anything that you like and I don't know how to do those things but I'm going to use DB with mongus so you can come down and at first I think we have to connect to our database right so let's see how we can connect to our database first so I'm going to create this new folder called DB and I'll create this index.ts so that I don't want to include this all the time because if there is index.ts that is going to consider as the entry file let's just import mongus from mongus and I'm going to hide this again I'm going to see it like this okay now I'm going to use this mongus do connect and you can see right here okay let me show you this with this mouse so this is UR that you need so how you are going to get your URI you are going to get your URI most of the time you will have this inside your environment variable like URI or whatever you are calling it but I'm going to store it inside this local variable and this is going to be mongod DB if you have installed mongodb inside your system okay mongodb col SL Local Host and most of the time this Local Host doesn't work for you then what you can do 1 to 70 . 0.1 column and the port number where this mongod is running and this is the universal port number 27017 so this is going to be your port number and here you can have your database name like my cool database or something like this now you are going to add this right here this is going to be your URI okay and after that because this connect is going to give you the promise you can use then and catch so catch is going to give you the error and you can simply log it to the console could not connect and you can have your error. message and next thing that we can do we can simply add this callback function right here inside this then if you are not like me okay as you can see I'm doing a lot of mistakes so you can simply log it to the console like DB is connected like this now if you open the terminal nothing will be there because you have to import this file inside your index.ts and because we have the index.ts inside our database what you can do you can simply import this folder called DB but for that obviously we have to use this SRC DB and how I can use this SRC instead of using those dot dot slash and those kind of a things I already have those things inside my ts config that's the magic okay and again if you want to know more about this I already have a video okay let's open our terminal and as you can see the database is connected but if you do something wrong in inside your connection so I'm going to change it to http this should give us error now as you can see could not connect and here you have the error why you got this error okay enough talking let's change it to mongodb and DB is connected that's fine now because you have the database what you can do now you can create new users and this is going to be your user schema first of all you need to have the schema the blueprint for your users which you can do with the user schema and inside here you need to add all those things that you want so let's just create interface because we are using typescript right so I'm going to call it user document and this is going to extend by what document and this document is going to come if I can type this is going to come again from inside mongus okay and here you are going to have name which is going to be string then you are going to have password and this is going to be a string and next thing that you need and the most important thing that you guys are asking for is the role right so here you can have your role and you are going to have user admin whatever that you want to create so it's up to you but I'm just going to show you the user and the admin and I think that's it you can have Avatar or whatever you like but this is the thing that I'm going to add for now and let's add the user document now because you have the user document you can only pass the thing that you have inside your interface now you have to define the type for this name and this is going to be a string and I think I forgot one more thing and that is going to be email and this is the most important thing okay we need to have the email and this name is going to be required prop without name we don't want to create anything so this is going to be true if I can type and again I'm going to use this little sanitization rule I'm going to trim the value before I save it if I can type these things next thing is going to be email and everything is going to be same so I'm going to Simply copy them like this and the main important thing will be for this email is all the email needs to be unique so this is going to be true now the next thing that we need is the password and password again is going to be the same exact thing but this time I'm not going to trim the password and I'm going to create the last but the most important thing for for you guys and that is going to be Ru and whenever you are going to create this kind of a rule and wherever you will have these different values what you can do you can create this thing called enum so inside this enum you can have the array and inside this array you can Define what are the things that you are going to accept like this is going to be user or this can be admin you're going to only accept these two rules as two rules for your users right and also you can have the default one so whatever are going to be user whenever we are going to create new users there are two rules and we are going to create user always so admins are the Special Rule which we can go to our database and manipulate things right so all the users are going to be users not admin but you can create admin I'll show you later how and let's just create this next thing and I'm going to add the time times and this is also going to record the time like the created ad and updated ad for all of your users so that's it now this is going to be our user schema there will be this name which is going to be string email same thing password same thing and Rule same thing so email is going to be a string but this needs to be unique for all the new users okay and the role is going to be different as well so there are going to be two different rule so default is going to be user and password is also requir this is going to be a string now at the end what you can do you can create your user model so I like to use these capital letters for them because they are also going to work as the Constructor so user model and this is going to by this is going to created by the model function so if you come up so here you can see you have model from the mongos okay now this model takes two things the name and the schema itself so name is going to be user I'm going to use this user as the name and the next thing is going to be the schema that we have created okay now we are going to use the export default keyword and we are going to export our user model but because we are using typescript and we want to leverage typescripts power so what we can do we can convert this type or we can cast the type to model and that same user document now again if you come up this is how you can grab model that's it now because we are not using the mongus thing I'm going to ROV it so that's it okay too much talking guys now we have the model what you can do you can simply create new routes so if you come inside of index.ts this is the entry file for our application where you are listening to this app. gate so the next thing that you can go do is you can simply create your sign up sign up route and here you can create your new user that's nice but if you want to follow the pattern called MVC pattern modern view controller and all those things you can create something else like routes in here I'm going to create this .ts so everything that you need for the authentication you can have them inside this routes file because here we use the express app okay and we use this Gate Post right here so whenever we are going to create the sign up we need to have the post so that we can accept name email and all those things so we can do it like this but inside this a route we have nothing called app so you cannot export it from here and import that there and this is going to be too much complicated and express is not going to give you that flexibility as well so what we can do we can simply paste that same thing right here but this time what I'm going to do I'm going to import this thing called router from Express like this and this is going to give you the router which I'm going to call Au router and you can simply use this router like this and now instead of this app you can use Au router and this is going to give you that same exact power now you are going to export this a router okay from here let's just save it so how you are going to get to this signup route now you have to set up this inside your entry file so how we are going to do this now I'm going to come up right here and I'm going to use this app. use because we want to use that router so we are going to use it as our Au router or what you can do you can simply use it like this Au router let's save this file and open your Postman now again if you don't know Postman I can do anything man you have to have post man so this is just the tool you don't even need to install it this is just going to come if you type out on the Google just say I want Postman and just grab the postman that's it now inside here you are going to get the same browser kind of a fileld here you can add your url like HTTP col slash Local Host col e okay/ sign up now if you notice here we have these types and we are going to change the method to post now let's just end this and now if you do this then you are going to get the okay through how and the reason for that is if you come here you are sending that same thing so you can send the sign up through if you want to if you just want to test this this is coming from here only that's it sign up true now if you want to have a little extra thing like if you want to prefix these routes with all these like o in between or in front of this then you can do it now if you try to send this request you are going to get the error because you are not listening to this route anymore now what you can do you can simply change this to all/ signup now if you seen this then you're going to get the signup through okay too much talking let's come here inside our Au router and what we are going to do we are going to Simply move this function and we are going to call it create user and we will add this Insider controller so inside this SRC I'm going to create this controller or controllers whatever you want to call it so this controller is only going to handle authentication so I'm going to have the .ts now let's just paste that function right here and I'm going to call it create user obviously now here we'll have the typescript problem and this typescript problem you can fix it with this request Handler okay so there is already this type inside Express which you can use like this and now there will be no problem and you can also export this function from here and now if you import it right here you're going to get that same exact thing which I will not show you because I'll directly show you how you can create new user now inside here you need to have your users email password name and all these things right so where you will have those things you'll have those things inside this request. body now let's just log it to the console and send the Json request back open your console and I'm going to just come inside this Postman go to the body and from this non you can select the Raw data and from this drop down you can select the Jon data so this is the same kind of a data that will also send from our react or react native application as well so this is going to be Jason so you need to have everything inside double quotation mark except you are not sending the Boolean or numbers okay so name is going to be this and I'm going to have the email so I'm again going to use all the same name password and I'm going to use the same thing now I'm going to send this and obviously you will get you will get this sign up true but if you come inside of terminal you will have undefined and the reason for that is Express doesn't know how to read these things by default you have to tell this that you want this or that okay so how you are going to do this you're just going to use this app. use method and you want to transpile all those things and I already have video again about the same thing how this works how you can create your own custom one and all those things I'll leave the link in the description box below if you want to know more about about this but long story short we are going to use the express if I can type express. Jon method and what it will do it will convert all of the things that is coming from inside our front end to Json data and it will add them inside our body right here so I'm going to open the terminal one more time and send the request and this time you will have name email and the password if you notice this email is not valid one right so you need to have at the email doc or something like this and again for that I already have a video how you can use validator but I will just show you how you can use the middleware the power of middleware to do all these things so in between this uh thing you can add the function which is going to run before this create user function but the main thing about this is that because this is in the middle it can also have the next function okay now if you don't call the next function this is not going to go to this create user means your request is going to hang in between the sign up and the create user it will never go to this if you don't call this next function so what you can do you can call this next function at the end but before that you are going to validate all the things that you want if you have those inside your request of body or not if not then you can simply send the error response like this is not valid just send the valid data okay so what I'm going to do I'm going to grab the email first from inside my request. body and I'm going to check for this email so how we are going to check this email is valid or not there are bunch of validators that you can use there are Express validator yep and all those kind of fancy things that you can do but this time what I will do I'll go and do a little cheating here I'm going to copy the email regular expression thing and you can have it inside you can just search for this just email validation regular expression and you will get the same EX exact thing okay so what this is going to do this is going to check for all those special characters at the rate and the dot and the ending values so this is going to check the pattern of email okay so what you can do you can simply use your email reg regular expression. test method and you can pass your email or the value that you want to check as the email and also if you hover over on this test then this is going to give you the type of value that this is going to return so this is going to give you a Boolean value so you can simply add this not operator right here if this is not valid email then this e block will run okay so if this is the case then first of all we just want to return we don't want to move further we just want to return right here we will not go to the create user function and we'll use this R.J function because we already have request response and then next inside this middle function and here you can simply send the error message so let's just send this error invalid email so this is going to be our error error response let's just come inside our Postman and let's send the request you will get the invalid email as the response back but if you notice right here it says everything is okay everything is fine you're cool not you are not cool you are fool because you are not changing the Status you can also change the status right here and again if you want to know more about these you can simply go and search for the HTTP status codes and they are many but I'm going to Simply use this 43 or you can just use this 4 22 which is going to be unprocessable entity we cannot process this request further because you're sending invalid data so I'm going to send this request and unprocessable entity this time you are sending the good response back okay now what next that you can do you can check for name you can check for password you can do all these fancy things right here but I'm not going to waste your time I just wanted to show you that there is this thing possible which you can do called validation so I'm going to to create this new user validator and I'll highly recommend you guys to go and use custom validators okay so I'm going to Simply create this middleware folder so inside here I'm going to create this validator dots and I'm going to paste that same exact thing and obviously there will be lot of these typescript error so let's call it new user validator and again if you have on them these are going to be any types so you have first of all satisfy the typescript so request Handler like this and now you can export this function that's it okay now you can come here and import it now you can come inside of sign up controller and what you can do because you know that you are using correct validator and again you have to use validator I'm not using the entire thing here I'm not validating name password this is your job okay my job is just to teach you how you can do things so I'm going to to destructure the email again if I can type name and the password okay and all these things are going to come from inside our request. body like this and what we are going to do we are going to use our user model remember the user model that we created inside our models folder which you can import like this and here I'm using this address symbol because I'm using typescript and I already have these things inside my ts config file and I already have a video about this how you can do this okay so don't ask me these things inside the comment or inside the social media or whatever that is so let's just use this user model. create and inside here you can have your email password and name so because we are using latest JavaScript thing if you have same name for key and value you can omit one of these you know that right so this create is going to give you the promise if if you come down this is going to give you promise and it is going to return the new user document so let's just all wait for its result and don't forget to wrap this function inside AC that's it now again if you want to see your user you can simply add this user right here and let's send the success to and also you can send your new user let's see what you will get okay let's come here and I'm going to send this request invalid email okay that's fine let me change this now as you can see we got the success true and also we got the new user even though we just send this name email and password we are getting back this role ID created at updated at and the version of this document so all these are coming from inside our mongodb database that is so nice the next thing that you have to fix is the password the password is in visible form and this is crying to have something like this okay let's just come inside our model and let's change things a little bit okay so inside here we already have the user schema we can use the user schema. pre method and we can attach these event listeners right here and we are going to listen to the save event before we are going to save we want to fire this function and don't try to be cool and use the error function here because inside this we are going to use this keyword so you have to have the old fashioned function keyboard okay now here you are going to check for if you are changing password or not because you don't want to change your password or you don't want to has the password always you are going to update your user will only do this if this is modifying password like this okay and also what you can do you can simply have the not operator right here and if this is the case you just are going to return and also if you come inside the function then here you will get the next so this is going to be the function again this is the middle kind of a thing okay so here you just have to call the next function you don't want to move further otherwise if this password is going to modify then you want to Hash the password so what is hashing let me show you this before that we have to come inside this and let's search for this bcrypt okay this is the package that you can use bcrypt and it will help you to has your password and it's a very popular package okay so let me show you how we can do this first of all we have to install it I'm going to open another terminal with control shift and five it's unique way okay now let's just do this npm install Express don't do this because we already have Express this time we need big RP BC r y PT and big RP doesn't come with typescript so again if you come to this one then you will see this tiny little DT it means you need to have the Declaration type file for this one okay which you can do with this atate types SLB G okay let me show you these things like this okay it looks something like this let me just press enter and it is going to install these things let's just wait okay that's fine let's just close all these things now I'm going to import something and that something is going to be has method from inside big grip okay and also this big GB holds multiple functions so we are going to use the has compare and also I'm going to use this generate salt so let's just come down and let's see how we can use all these function so very first thing that you can do is you can AIT for this hash method and what this is going to do this is going to Hash your data this is going to encrypt your data if you have something like ABC it is going to convert this to something else weird language which you will not understand I will not understand and it's a little bit of tricky thing you cannot unhash this without knowing the previous value that's so cool right so if you don't know the previous password you cannot unhash the hash thing that you previously hashed I hope you got the point so let's see what I mean so I'm going to use this do password because we want to has this password and here we also need to pass the salt round like how much secure that you want your password to be and how much round that you want to use all those kind of a fancy thing but here you can have your 10 8 or 12 as the value but also you can create your salt like this so I'm going to create it salt and don't just put your salt from the kitchen okay so I'm going to create this a a wait let's just a wait for this generate salt method and this is going to give you the salt and you have to pass the salt around here as well so I'm going to use this stain as the salt R this is going to give you the salt which you can pass here and this is going to give this is going to give you the salty password okay now what we need to do we need to have this this do password and we just want to assign this hashed password to our this do password this if you don't know what this means this is going to be the user that we are creating okay so this is going to consider as just think it as the all those new users will have this do password and we are going to has those passwords that's it now I'm going to save this and I'm going to change my email because email needs to be unique otherwise you are going to get error and uh just to test the same thing what you can do you can come inside your controller and I'm doing so much thing guys here I don't even need these things you can simply come up with your own idea so let's just use this user model do find one which you can do with adding this email right here and this is going to find all the users with the same email not all the users because we can have the single user with a single email ID and we are using this find one method you'll have single user so you are going to call it old user and if there is already this email ID for this user what you can do you can simply check for this old user if there is this thing let's just return don't move further just return right here and let's use this raise. J and send this error back the email is all ready in use so that's what you can do so as I already told you it's not the rocket science you can simply come up with your own things okay also let me change this status I don't know what the suitable thing will be so I'm not going to go to the Google things right now I'm going to just s this 403 which means unauthorized okay now if try to send the old email and try to create new user this email is already in use that's a cool thing okay now let's just change this to new email and send this now you have new user with new email ID but you will also have the new password which is going to be the hash password remember as I told you it is going to change this to the cryptic value or it is going to give you the hash value that's it now you have this value and you have this value compare these things okay and I don't know what I opened now the next next thing is that you also need to have the function which can compare this weird thing with this un weird thing so how you can do this you can have it right inside your user model so I'm going to come here and I'm going to create this user schema do uh what this is going to be methods so this is going to be the methods do compare password so this is again going to be old little function let's just have this async and inside here you are going to pass the password which is going to be a string obviously but you will not get that type right here you can Define this type inside this one but if you do this your your typescript is not going to give you suggestion whenever you want to write code inside your unknown the file so what you can do you can come up and create this new interface called Methods and inside here we can have our compare password okay this is going to be function which will take the password which is going to be all password that we want to compare and this is going to be stram and this is going to return promise and it will resolve with Boolean value that's it now you can come inside this schema thing and you can extend these types second thing you will pass this just empty object and methods will come at the third place now you can simply have the same type right here at the bottom if you want to have the correct type suggestions okay now as you can see this is going to give you the warning but now if you come inside this password is going to give you the type as a string so that is so nice now why this is giving you warning because you are not returning Boolean value so simply let's a wait for this compare method if you remember we already have this method compare like this okay and here what you can do you can pass the data that you want to compare okay and the encrypted string so here you are going to pass the password this is going to be your data that you want to compare it what you want to compare with the password that you already have right so this is going to be this do password and now this is going to give you the Boolean value which you can simply return and because here we are using this bunch of eing a I'll highly recommend you go and use those try catch blocks okay that's it that's my tip now what you can do you can create your signin method where you can simply compare the password you can find the user and you can generate the token and that's it voila everything is fine but I know you don't know how to do this let me show you that okay now I'm going to create another route and this is going to be sign in and because inside the sign in you will have email and password you can simply leave this like here or you can create separate validator if you want to but because I'm just validating the email I'm just going to leave it like this sign in so this method is going to handle sign in let's come inside our controller I'm going to duplicate this one this time let's just create the sign in and this time you will only have email and the password or you will just care about the email and the password now the next thing that you want to do you just want to find this user with this given email ID if we have this user inside a database or not so this time this is not going to be old user this is the user that we want to validate so this time we will not check for the if there is user or not we'll check for if there is no user only then we have problem okay if we don't have the user with this given email ID whenever our user wants to sign in that's a problem right so let's just come down and uh let's just send this error response user not found so I'm I'm going to change the request uh or response number to 404 and I'm going to send this user not found that's it okay and I'm going to come down and remove this little part here and once you are going to find the user because if you pass this if condition it means you're one step further so what you are going to do you are going to check for the password so is matched I'm going to create this thing called matched okay so let's just create this how you're going to get this EAS match thing so you will get if you a it for this user and if you press this Dot and try to create or just type out this compare then you will get the solution here you have to pass the previous password like this and this is going to give you the compared value and this will give you the Boolean value and whenever you are going to match you will check for this not operator right here if this is not matched what you want to do you just want to do the same thing but this time you will not send the user not found or password not match or something like this so this time I just want to send this 403 and we'll send the email/ password not match so email or password doesn't match we don't know what just figure that thing out on yourself because these are the security things and I don't want to give all the information to the malicious user man look okay now we have this I don't know what we need to do next now the next thing is if you have the user user and if this password is going to match you will just come right after this if condition here your password is matched and there is user user is there and password is cool matched okay so what you going to do you going to generate token and for that we are going to use Json wave token now again if you don't know about the Json W token Json W token just go and try to read about these things because you will need these things in future as well okay so again we have to install it so I'm going to copy this command and it's a very popular package as you can see I'm going to open another terminal and I'm going to do the NP install this uh Json web token and I'm also going to install the types for this one okay let's just press enter and it will install all of these things that's it now we can come inside our project and I'm going to import JWT from Json wave token so I'm using the shortcut name here okay now you can can come down and you can use this GWT doign method and you are going to sign this new token because whenever we are going to sign in our user what we will do we'll first of all ask their email and password and we are going to Simply verify that and we are going to send the request that you are valid user you can sign in inside this application but later whenever our user wants to access some private information also at that point of time we need to figure that out right this user is genine or not again you can ask for email and password if your user then freak out okay and in that case what you can do whenever we are going to match the email and the password we are going to generate a little token that can be signed inside uh signed from inside our application and also that can be verified only from inside our application if you can do this it means this is the valid user okay enough talking let's just try to sign the token and whenever you are going to sign the token if you however over on the sign in or sign method you can see you can pass the payload okay this can be string object buffer whatever that can be and the main thing is the secret key also you can have options and all these which I'm not going to cover in this video but the main thing is that we need to have payload so that later we can find the token or user for this token okay so I'm going to use the ID and these JW tokens Can Be view outside of your application as well so that is why do not put any sensitive information inside of payload so these are going to be some public information about your user so I'm going to use this user doore ID do2 string oh my God now after this I'm going to pass the secret key so this secret key again is going to be stored inside your environment variable okay but I'm going to put it right here so this can be any secret string that you can come up with okay now this is going to give you the token which you can simply send to your user instead of this user I'm going to send this token that's it now if I try to sign in now I'm going to Simply come here and sign in and again we are sending the post request that's fine we already have the email and password we can simply send the request if you do this then obviously you are going to get the error and the reason for that is we haven't imported the sign here and saved the route so I'm going to do this and let's just send the request and you will have this weird long looking this token which you can always go and de code inside the JWT website so don't put any sensitive information so let's see how you can create or how you can verify these things so for that I'm going to create this new thing called private now if you want to you can put it any way that you want but here I'm just going to show you the way so I'm going to just put it inside this Au route so this is going to be private route where we are not going to have any validator at this point of time and this is going to be private response so let's just create this private response right here so so I'm going to duplicate one of these function and from here I'm just going to send the Json response with the message cool man you are in the private property okay so this is the message that I want to send but now what we are going to do we also want to figure this thing out like this user is valid this user is authenticated or not if this user is already signed in or not inside our application so for that you can have this request response and the next yes I know what it calls it calls middleware function right so inside this middleware function you can validate your user so how you are going to do this the common way to do this thing is to look inside the request headers and inside this header you are going to look for the authorization token so let's just call it authorization token and let's just log it to the console I'm going to just open my terminal and let me show you one more time how it looks so this is the middleware function where we are looking for this request headers authorization token and this can be undefined or this is going to be a string so let's just come here and send the request and again you are going to be signed in that's fine now I'm going to change this to private let's just send the request and uh this needs to be get obviously let's just send it one more time and we are not getting anything back and the reason for that is we are not calling this next function remember I told you that if you don't call this this is not going to go to your private response and that's what we want now this time I'm just going to cancel this but now if I open my terminal this is going to be undefined means our authorization token is not there so how you can have your authorization token you can have it inside your header and how you can do this with react native I'll show you this in the next video but inside this post man you have to come inside this headers Tab and if you try to type out this authorization you'll get the suggestion where you have to add the be so this is the common token that we used whenever we want to sign in so BR token after this BR you can have your token okay let's just send this and now again I'm going to cancel the request but now if I open my terminal this time I'm going to have the be space token so we don't care about the B we only care about the token but we are looking for the BR token so what we can do we can simply grab this be space and we can split the value and this will give us the two different thing from inside the array and we are going to grab the token okay let's just look right here for that one authorization token and we are going to split this and as you can see this authorization token this can be undefined here so that's why here we have this question mark okay this is going to guard us so now this is going to use the split method that we want to use it okay so be space we just want to do this okay now let's call it token or this is going to give you the array let's just save it or log it to the console I'm going to send the request cancel it open the terminal and now you can see we have this empty string and the token so we just splited this little string but now here we don't want to send the token like this we want to send the actual token which is going to be the token that we signed when we sign in inside this application which you can do with the sign in endpoint so let's just change this to post and come inside your body because we already have the email and the password let's send this and now this is going to be your token just copy this come inside a header authorization and we are going to remove the previous token and I'm going to use new token here now we are going to change this endpoint to private and let's change this to gate and let's send this and this time you will have the exact token that you want so this is the token that we want now what we can do we can simply grab the second item which is going to give you the exact token but now if you hover over on this this can be undefined or this is going to be there as a string so let's just check if there is no token we just want to return and we just want to send the response back with the status code 403 which is going to be unauthorized let's send the Json error so I'm going to send this error message unauthorized access so now if you come inside your browser and if you just try to go to your private route let's just go to the / private you will get the error because you are not signed it inside our application right so let's just come here and what I'm going to do now is I'm going to verify this token because we just signed this using our JWT token we also want to find out if this is valid or not so for that we can use the sign or not sign the verify method so let's import JWT from Json we token come down and let's use this JWT do verify and we want to verify this token and you also need to pass the same exact private key that you used to sign this token so this is going to be in my case this is going to be secret now this is going to give you what this is going to give you the payload now if you hover over on this this can be a string or this is going to be jwp Lo now inside here we have this thing called ID and this is going to be a string right if you remember inside our sign in method that's what we did right here and this the same thing that you will get as a payload now if you have the ID then it means you have to have the correct user with this given ID so you can simply AIT for this user model. find by ID method you can use this and you can have your payload do ID that's it because we are using this a here we have to have the async right here now this is going to give you the user and again you're going to check the same thing right here if you don't have the user okay you're going to send the same exact error response back or if you want to debug your application later you can change these error messages so that you can debug easily now if you have the token and if you have the user with this payload ID it means this is the valid user so what you can do you can simply call the next function but before calling this next function what I like to do is I like to add this user right inside this request. user object now there is nothing called request. user and that's why typescript is giving you this warning if you use in JavaScript there will be no warning for this one so I'm going to just uh override the global theme so we can simply have the declare Global and we can use the Nam space keyword to change our Express type and inside here we want to overwrite this thing called request and this is going to override this request object okay now here there is going to be this user and inside this user we are going to have the key again if you want to you can have the same exact type of this user but uh I like to do it like this so there is going to be key string and the value can be anything now let's just save it and now you can see you can have user as well now if you just send the request from the route from where you are not logged in you will get the error response but if you come inside your post man because here you already have the authorization token and if you send this then this time cool man you are inside the private property that's what you will get so whatever that you want to do you can do after this middleware function so let me call it e o so this is the middleware function that will check if your user is authenticated or not and here you will get the error warning which you can fix with the type request Handler that's it now whever you want to prevent things from the non authenticated user then you can have this EO wherever you will have this you have to first of all log in inside your application I can't do anything um about this sound as I already told you okay there are lot of construction going on now I'm going to duplicate this one this time I'm going to show you the admin one okay but this time we'll check for the admin so here user needs to be authenticated that's fine now you can also have the ease admin so this is going to be the same thing but this is going to be another middleware function but this time you will have the admin response back so I'm going to change this to admin now let's just come inside our controller let me see my keyboard so I'm going to come down to this private response I'm going to duplicate this one and I'm going to change the name and this time we are going to welcome our boss so welcome boss you are our admin I know that okay so this is going to be the response that will send now let's just uh import this and again now if you remember because if you pass the e or middleware you will have your user inside your request. user thing right so you can simply duplicate this one now I'm going to check for the admin which we can do with this e admin middleware so I'm going to Simply remove all these from here to here and I'm going to just check for this request. user. Ru so if this is admin we just want to call the next function otherwise let's just use this else block here raise do status 403 unauthorized request doation error protected only for admin okay so this is the thing that I want to send back now remember here this user is already authenticated right now if we try to look inside our private property we can do this cool man this is private you are inside the private property but let's try to change it to admin and let's try to send this protected only for admin remember this okay now how you can change it open your database so I already have this thing called mongodb Compass inside my system you can install mongodb and you will have the same thing now I'm going to connect and here I have bunch of these database that I do all the time okay now this is my cool database that I created earlier and here we have that same two users now what I'm going to do this is the user that is logged in for now I'm going to change this role to admin so you have to come here and change this manually let's just update this now this user is user the role for this user is user and the role for this user is admin and now because the role we changed the role now if I send the request welcome boss I know you are admin that's so cool right now whoever sticks to the end I'll show you one more thing and this is very important now if you just try to temper these tokens you're going to get nasty error inside your back end Sero and you will not get any response back and why is that and the reason for that is your Jon token is invalid and this will show you this nasty error so for that what you can do inside this e o middleware where you are using this jw. verify to verify the token and if this token is not the good one if this is the tempered one you're going to get error so I'm going to Simply move everything inside the tri block and inside this catch we will check if error is instance of so that's how we can check for the error okay so if this is coming from the JWT web token error and that same thing is right here as you can see the type for this error is this okay now if this is the case it means the user is unauthorized right so we are simply going to send the same error response for that user like this otherwise you can simply remove this else from a return from here and you can have the else right here and inside this else I'm going to use this race. status and we don't know the reason why we failed so I'm going to change this status to 500 and let's just send the changee and response back and this is going to be error something went wrong that's it let's just save this now if try to send the request with the temper token your application will not crash you will get the same exact response that you want but now if I change the token back to the good one then I will be the boss I hope you like the video and I will see you in the next one when we are going to talk about the react nitive how we can connect this to the react nitive I think this video is already long enough oh my god oh my god let's just let's just cut this video right here
Info
Channel: Full Stack Niraj
Views: 1,994
Rating: undefined out of 5
Keywords: user roles, user roles nodejs
Id: kISCmNnGFj8
Channel Id: undefined
Length: 54min 48sec (3288 seconds)
Published: Mon Oct 30 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.