Build A Node.js API Authentication With JWT Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
summer is coming and that's why I'm wearing glasses because summer is probably one of the most exciting parts of the year I'll just put it up here like this no but for real summer is super exciting that's when everybody goes down to the beaches they go swimming and we're sitting here coding oh god what's up my gorgeous friends on the Internet in this episode we're gonna create a REST API with identification this has been a huge request from you guys so this is me giving some love back to you for all you have done for me on this channel so we're gonna cover a lot of things we're gonna look at how to store users in the database hashing passwords JSON web tokens private routes and how am I gonna cover this in the half hour video I have no idea let me go get some redbull okay so get yourself ready unfortunately I don't have a magic trick for you guys today because I have a weird cough going on but the cards hey everybody okay let's get going so I just have an open empty folder here we're starting absolutely from scratch the first thing you need to have is node install so if you don't have just go to no G as that org and install that sucker and you should be good okay so first of all we need open up a terminal up here and we just say MPM in it you can do this like this with y if you want and that's just gonna create it or optionally just you can just hit enter like me because I'm a masochist okay so we have a package.json here and all this does is it holds all of our packages so the things we install off the internet and the way we're gonna do this is when we have an issue that's when we're gonna install a package we're not gonna go here and say 10,000 packages because it's gonna be confusing and we're not gonna understand what's actually happening here okay well the first one we're gonna install is Express and that's just gonna handle our routes for us so NPM install Express hit enter and actually another one that we're gonna do is node Mon which is just gonna restart our server so we're gonna do NPM install and I'm gonna do - - save dev for this one node Mon so it's not actually included in the main packages that are actually going to be sent to a server so there we go we are still waiting for this one which is fine and until that we can just go up here create a new file index dot J s hit enter this is gonna create us a new file perfect so once this is installed we can initiate our first server so we can say Const we can get that express by setting it equal to require express alright then we say Const app and set that equal to the Express and we invoke this function okay so then to actually start up the server what we can do is we can say app dot listen and we can give it a ports now we're gonna customize this a bit later and the second option you can give here is if you add a comma you can just say console.log up and running just a string I mean I guess we should say the server here so we know what so this is just a callback function once the server actually starts then we are running this thing perfect very nice okay so let's create our routes now the way we're gonna do it is we're not gonna create everything in here because it's gonna be crazy and it's not gonna look nice so highly recommend you to go up here and create a new folder called routes ok and we add it in here we're gonna create a new file up here and let me close this we don't need you now new file it's gonna be called off da da s ok these are gonna be our identification routes perfect so let's open that up and the first thing I want to do is create a router and set that equal to require Express dot outer and this is just kind of the same thing that we're doing here with app so you can do apt-get or things like that but rather than doing that work that we're doing there router dog yet so when we export it and when we exported here module dot exports we can set it equal to this router ok and we can kind of separate our routes from here and just import the actual middleware in here that sounds confusing don't worry it's gonna make sense in a bit so for now let's just create a empty router here let's do router dot post and this is gonna be when we go to register ok and we do a request response here and for now all I'm gonna do is say response dot sense so we can send back a message and this is gonna be register ok actually doesn't do anything so now we can have multiple routes in here and at the end we can just import everything in here so let's import I'm gonna actually add a comment here import routes ok and in here I'm just gonna create a route and just import this ok so we're gonna say require and all I'm gonna do is say dot slash navigate to the folder and get this file perfect so now we can actually create some route middlewares so to do that we can just go down here and we can say route middlewares and here all I have to do is say have dot use and when we navigate to API slash user then I want to run this off route so all this means is that this is always gonna have this prefix so everything in the ALF off route is gonna have this prefix so what this actually means here when we do a post request to slash register here it actually means that we have to go to a bi user slash register okay and we're gonna see that in action so if we do another router here dot post and we navigate to login well this is actually when we make a post request this is actually going to be to localhost like whatever this is like that and then it's gonna be slash API slash user slash login okay but everything is prefixed in here are ready so we don't have to add it in here alright so we're gonna have a login here but we're gonna take care of this later so I'm just gonna export this and make sure everything works alright let's open this up and before we actually start this up we're gonna go to package JSON delete delete everything in here and just add a start so when we start up we can run node mod and just say index dot JSP so by adding NPM start this code is gonna run in here so let's try NPM start hope for the best all right there we go as a pop and service for server is up and running all right so what we can do is we can open a postman there we go you can download it if you want off the internet just search postman and you should get this all right this is gonna take a bit to load up which is fine let's close this I don't know what that is close close everything okay so when we go to API she user here slash register alright so make sure this is correct and when you put the post because we're doing post in here alright so when we do that and when we hit Send we should get register alright so it works we're getting back this message alright so this works not and we can minimize this and we can take care of it later so let's connect to a database because we cannot register or do anything because yeah we need a database so to connect to a database we are gonna go to M lab now M lab actually they changed and they connected with this so it's MongoDB Atlas so let's go to cloud MongoDB Atlas here you can register up an account and once you register you can create a new cluster so let's build a new cluster and this is gonna be free so don't worry and we can do AWS here I'm sure in North America and make sure this is the free so wheel when the cluster tier up we have the base price which is free forever which is perfect cluster name we're gonna leave it like that that's fine and we're gonna create a cluster here I said cluster too many times all right this is gonna take a bit of time but until then what you can do is you can go here to the security because we need to do a few things all right so who can access this database I'm gonna delete this you can go here and you can add a new user you're probably gonna have the user I believe the default one is the one that you're signing up with M lab but if you want to add another one you can just add a new user and here we can delete everything and let's say the new user is gonna be Rhino 11 okay and the password let's add the password Rhino 11 and this is gonna be dev head alright so make sure to remember this one and let's add in and we can also add privileges here we and rights to any database is gonna be fine and we're gonna add a new user perfect so we have it and here davit the second thing you want to do is go to IP whitelist and you're gonna add IP address address here and you're gonna click allow access from anywhere either that or you can add your own IP address which I have here so I'm not sure I think there was a button here but I already added it all right actually the ping is not finished so let's wait a bit yeah the cluster is still seven to ten minutes all right that's fine but I had a problem where it didn't load up so what you had to do is you have to include your your IP address here so you can make requests yeah I think it shows up here so let's take a look at this when this actually loads up and we'll figure it out together so let's go back here and the thing we need to do is we need to create a model so a model of how our data is gonna look like so how our user is gonna look like which basically is gonna be like a user name an email and a password ok you can add more but we're gonna keep it simple so to create a model and to actually make also very easy to use and connect to it and everything we're gonna install a package called Mongoose so let's close up the server you can hit control C and is it close enough there we go and we can NPM install Mongoose here hit enter and now we wait again it's so much sometimes sometimes you just have to wait for things let's take a look back here if this is deployed over view and it is so there we go it's deployed let's take a look at the security again IP whitelist all right so my my IP address is here apparently let's take a look here and yeah I think if I remove this then that's trying to remove this all right they're deploying the changes let's add the refresh ok let's add an IP again and there we go add current IP address confirm because I was confused I was bamboozled why that wasn't showing up there so there we go that's all you have to do and to connect to it all you have to do is go here to connect all right and we're gonna say connect to your application and you're gonna get this string all right we're gonna leave this open let's go back to our PS code since we have our Mongoose installed we can NPM start we can start of this server again and let's connect to it so up here we're gonna import that Mongoose package so cause Mongoose equals require Mongoose why I don't get autocomplete is beyond me all right there we go and to connect let's go up here I'm gonna add connect to dB and all we have to do is say Mongoose dot connect thanks so and here we can pass and at URL so let's go back here we can copy it paste it in here we actually need to add it as a string and the problem here is that we need to replace this password and we have David which is fine and in here I think my password I put was Rhino 11 all right and we're gonna change this we're not gonna leave this here because that's that's not a good practice here to leave your password and everything show up so don't worry and the second argument is gonna be just an arrow function so let me bring this down here just an arrow function and we're just gonna console.log connected to D be alright it's safe and this is actually gonna cross not an error but a warning that they started using this new URL parser here so you can just copy this object from down here don't worry too much about this and just paste it here right after your string and write them between the herro function okay hit save let's see that we get the connect and yep we have to connect it to dB okay now let's actually not let's not keep this in here because we want to move it so our password is protected and everything so how can we do that well we can install a package that is gonna do exactly what I told you so let's close this up and we can install the package called NPM install dot EMV if I'm not mistaken let me take a look let me make sure yes dot EMV and what this does is we can create an environment variable and we can store the password in there and when we push up the code to github or something our our our thing is not gonna say our password there and when you push up to things like Roku well you can inject that environment and variable environment variable in Roku so Roku will give you like a dashboard and you can add it in there okay so once we have it installed all we have to do is just create a new file on the root so we're gonna call this dot E and V and then here we can add ADB connect and that's equal to and I'm just gonna copy everything from here and the string cut it out and paste it in here okay let's save and now we cannot use that anymore in here so let's import that dot V constant V is equal to you require dot E and V perfect and now to initiate it and to make everything work all you have to do is right up here to say dot E and V dot config like so oh my goodness I don't know why my autocomplete is not working hit save and now since we have this dot env come fact here to access everything in this dot e AV file all we have to do is say process dot e MV dot and then we give it the name that we give in here so DB connect DB connect okay that's it hit enter and that's it yes we are we should be up and going we can NPM start this we can start up our server perfect you can minimize it and let's create our model that we've been talking about so we can make a new folder you can call it model hit enter and we can create a user model so user dot Jas I'm doing it with an uppercase u here okay so we can create we can import mongoose now require mongoose how to complete this back welcome and then we can create a schema that basically just represents the model of our user so we can say const user schema we can say that equals u new mongoose dot schema and this is gonna be an object so like that and here we can just define the properties that we won't have so i want to have a name and this is gonna be an object and in here i can define more properties so this is gonna be a type string is it going to be required it's gonna be true and also you can add that it should have a minimum of six characters okay we can add a comma here we can add an email and this kind of pretty much repeats itself here so type is gonna be spraying required this is gonna be true and the max we can also have the max can be 255 okay so the maximum amount of strings or we can just add a minimum as well minimum can be six I'm not sure what the minimum is on the email we can add a max here too because your name is probably not 255 characters long and the password is gonna be of type string as well and here required is also gonna be true alright and the max here I'm gonna actually add a bigger number something like a thousand 24 because we're gonna hash this password and at the top of my head I'm not sure how long that but just to make sure we're gonna keep this fairly long okay and the minimum is gonna be at least six so that's it let's let's also add a date here and the way you can do that is just type this is going to be type date not string and you can also add the default with date dot now okay perfect and here at the end we can just say module dot exports and set this equal to a mongoose model perfect and here he can give a team name so this is gonna be our user and what schema should it use well it should use this user schema that we just created so we can just add that and there perfect and now we can use this to add and register users okay so remember these are the properties that we need to fill out password email and name so we can go back here and we can actually try this out so we're not using it in here but we are gonna use it in the routes here so let's import this model that we made let's go back here to user perfect and let's do const user model is equal to require dot slash and this is dot dot slash because we're navigating out one folder we're gonna go to model slash user alright so we have access to the user perfect and now let's try to make a request here so rather than sending this back we're gonna delete everything in there and the thing i'm gonna post is let's keep this simple for now the thing I'm gonna do is I'm gonna create a user here alright and this is gonna be equal to a new user so we're gonna use that model that we made alright new user and in here you would pass and be beta you want to submit so we have a name alright this is gonna be coming from the request body here request body name and we have an email request body email if you have trouble with this I have a REST API video and so you know the an old video that you can check out if this is a bit confusing for you but I'm trying to quickly get through this lets password request body dot password so condition what this basically means what the request body is when you send in here and when you send a JSON object in here well this is actually coming from the request body so in here if I have let me get rid of this so if we sent a post request and I have a JSON here with a name of add alright so this would be accessible on the request body name alright alright so this is everything we do but the problem is we won't be able to read it from here when we post so we actually have to use something called a body part sir so let's go back to indexed a genius and add that body part sir so here we are actually connecting to our database here we do our our config so let's actually do after we connect our database we import the routes here let's move this up kinda to clear everything up here so we have our routes we have our config our DB and down here we can have our middlewares middleware okay and here we're gonna say AB dot use and we're gonna use Express dot JSON that's it and now we can send post requests get perfect hit save and perfect now we have our route middlewares here as well so everything is kind of cleared up and organized in here so we can actually kind of try this out so we have we just create a new user here and after we create that new user we can save it so the way we can save it is we can add an async all here because we need some time until we actually submit things to the database and down here what we can do is we can add a try-catch so try we're gonna try to submit a user and then we can catch some errors just in case so in case we catch an error we can respond with a status code of 400 and we can send our error back all right and here and our try we can try to save the user so let's say Const saved user it's gonna be equal to a wait user dot saved all right so we're taking this user from up here and we just call the save that's it that's everything that's literally it and we can even send it response or res dot send our saved user here so we can see it on the screen so let's let's let's give this a shot let's see how this works so let's go back to postman here so when we navigate to API user register make sure ya post here selected make sure to also have let me remove these because we're gonna do this a bit later make sure your content type is application JSON or you can select it here so on this drop-down so raw and application dot JSON application JSON here okay and now we need to have a name here so we can do name this is gonna be dev ed for example we can have an email that's gonna be Eddie a Rhino at yahoo.com unless for what I have with rhinos today and the password for now is just gonna be something extremely password like 1 2 3 4 5 6 ok and when we hit Send well we get back this data here so take a look it generates a debate the ID and everything and let's actually take a look if this actually submitted to the database so let's close this up hit refresh here and our atlas and MongoDB and let's take a look at our server we can go to the collections and let's pray for the gods and there we go look at that we have users and we have one user with David and everything is super cool however we have problems here well the first one we shouldn't store passwords in here because that's not a good idea the second problem would be that we are not doing any validation for now like let's say the user has only 5 characters in the passwords or that's not an actual email all right and so we need to also add that so let's get a validation out of the way first and then we're gonna take a look at how we can hash passwords all right let me go scroll out here we can leave this here for now or we can actually delete it by clicking that and perfect so the package we are gonna use to validate our information that we're getting from a user is something called joy and it's actually very fun to use so we are gonna say npm install at happy and then slash joy like that with the with an i ok hit enter and while this is installing actually let's just wait how have you been everything's going good ok ok let's let's restart the server npm start close up the terminal we don't need that now and let me kind of show you how it works in here and then we're actually gonna separate it in another file but for now validation i'm gonna put it up here and the first thing you want to do is just import joy so I'm gonna just import it here for now because again we're gonna kind of separate this into another file and say Collins joy equals require happy joy whoo awesome ok so what we need to do is you know the way we kind of created a schema with what kind of information we have in our user well we kind of can create a schema here with validation ok so this is just gonna be a schema I'm just gonna name it account schema that's fine and this is gonna be an object here and then you can just do name again and then pass for it and then and all those wonderful things so we can say name and we can say this we can give it a value of choice so we're gonna use library dot and you have a lot of different cool methods here to validate so one would be string and you can vogue it like that and then you add dot and you can add multiple things on top of it so maybe be a minimum character can be six on this one and it should also be dot required required like so okay that's it you can add a comma we can do email we can say enjoy that string so this is a string as well the minimum should be six and dot this is required as well make sure to spell that correctly and you can also add a dot email so it makes sure it makes sure that this is also an email that we're working with perfect let's also add the passwords which is gonna be joy dot string okay and the minimum is gonna be six again and it's gonna be required as well perfect so that's it you just create a schema like so and in here what you do before you actually submit everything you can validate the response that you're getting from the user so and here let's validate the data before we make a user okay and the way we do that is we just say joy dot validate validate thanks so and the data that we're gonna give it is the request body okay because that's where we pull all the information from so request the body and the second argument is gonna be so if we add a comma here it's gonna be the schema that we just made and that's it that's all we need perfect and what this is gonna actually throw us back is an object so we can store this in an object here let's just say validation is equal to joy that I validate okay and I'm gonna just console.log this out a bit now cancel exists acts this out so we don't actually submit a new new user just so I can show you what this does if I just say rest arts and validation just out of curiosity hit save and let's take a look here and postman so now I'm just gonna keep the same information that's fine and when I hit Send so this is what it actually sends us back it's gonna send us back an object with an error and it's gonna send us back a value with all the information however if we do have a problem with validation here this is gonna be this error is gonna show us multiple information so for example look I'm just gonna delete everything here just gonna leave one two in the password but we know that it it should be at least six characters long so if we hit Send now you're gonna see that whoo look at that we get this big object back and we have an error and it's gonna say here in the details it's gonna say message password length must be at least six characters long so there we go look it does it for us automatically how cool is that we can't add this back and look if this is not an email so if I delete at yahoo.com and hit Send it's gonna say email must be a valid email so as you can see it works perfectly and that's what we need all right so but I actually don't need this value and everything else in here I just need this error okay that's that's the thing I want to pull out so what we can do is we can actually be constructor this we can delete validation and just add curly braces and say error and that's just gonna pull out the error and we can access that message if we want via validation so this is gonna be error now error details and it's the first array and it was message I believe hit enter let's take a look so it was error dot details details and it's the first object here and the array and dot message okay I'm just pulling that information out to this one and now when we hit Send I mess something up probably and oh no all right cannot read properly property details of no so all right it's my spelling 100% details error details let's take a look at this again oh my goodness hit enter all right so let's let's remove this how we have something going on here all right so it's error dot details so that's correct let's try to pull this out hit enter let's take a look again all right so the first one's gonna be message so it's gonna be the first object in the array so I'm just gonna add the zero dot message all right let's hit there we go okay so we pulled it out we have password Lang must not must be at least six characters long so there we go that's our response perfect let's add this back and once it's okay we're not gonna get anything because we haven't responded to this okay well that's cool so now we can just add this back delete this and what we can do is say if there is an error well then I don't want to post this anymore I don't want to get all the way down here right if if we have an error there's no reason to make a new user so what we can do is we can say if I have an error all right from this joy error if we have an error then what we can do is we can just return and send a response but they status are 400 which just means all this is by the way res dot state is 400 it just means that it's a bad request and it's just not good okay and you can add this at the beginning of the response so response 400 and then we can just send back a message and what message should we send back well the one we did back there so it's gonna be error details down message so this one and that's it alright so in case we have an error this code down here is not gonna run anymore so we can uncomment this like so we're gonna keep this and that's fine all right everything should still work the same let's go take a look here let's just make this a not valid email hit send and yep email must be valid so let's add another one here I'll see you test boy that's valid and we're gonna change the passwords here and the name it's gonna be John so a John Snow with Traverse e-media and that sounds fun I would watch that it's sand and as you can see them accessing you user and we can see that going on here and atlas so hit refresh let's take a look well it's loading here we have users and we should have both now so John actually we deleted the other one but here we go we have this one and it's fine so the validation is working and yep I'm happy with this done however what if I want to do a log in because we're gonna eventually have a log in post here down here and I don't want to make another schema here and the file is just gonna become super crazy so what we can do is we can kind of separate the schema and the joy from here and kind of add it to its own file so to do that we can just go to the root for now and just create a validation todd che yes okay just like that so super simple and all we can do is we can kind of just copy thanks from here so the imports is gonna go here so the joy we can also get the schema here and paste it in here so that's fine and we can just kind of wrap it in a function because we're gonna we might have multiple schemas depending on what we want to do so this one is probably gonna be a validation a register validation validation okay so we can just create a new function here so register validation and we can set this equal to an arrow function here and we can just add the schema and here perfect and at the end what I want to do is in here see we don't have this anymore this joy that validate and we want this requested body which we cannot get and the thing we were gonna do is we were actually going to pass a parameter in here and then we're going to import everything in here and we're is going to use this register validation and just pass in the requested body okay so what we can do here is we can actually get rid of everything okay get rid of everything and we're gonna validate this and the function here so let's just do tile validate validate it's like so and the first argument is gonna be the request up body but since we have everything separated here we cannot add it so I'm just gonna have a parameter of data that we're gonna get so data and the second one is gonna be the schema that we're using here and that's it and the thing I want to make sure is that I return this function here this validation all right heads safe and that's it we can just export this so we can go down here and we can do module dot exports dot register validation and set this equal to register validation the reason why I'm doing it like so is because we might have another one so we might have another one which I'm gonna actually do now so we're gonna do a login validation too and it's kind of gonna look like the same so that's why I'm kind of setting it up now login validation alright and this is gonna have just the email and password okay we're not gonna be needing the email and the and the username so that's it I'm just gonna keep everything the same way all right and I can copy this and paste it in here and just change this to login validation all right login validation and login validation hit save so now we have both of them okay and how to use them it's actually super simple we can go up here we deleted everything I I'm gonna keep this one this error with the response that's fine however this is not gonna work anymore we're gonna delete this here we're gonna import the validation that we're going to use so go up here and to import it all we have to do is say cost I'm gonna so it's require d-file the adult slash and I don't think I'm getting autocomplete but we can import it like so register the holiday shin let me just make sure I'm doing misspelled ad require yeah for some reason I'm just there we go and we can import that validation file so if I want to import another one I can just add a comma here and then I can add the login validation or whatever I need for now I'll just import the register validation so to use it remember all we do is we just separated everything in here and this function and we just need to pass in that data that requests body and that's gonna do everything for us and it's automatically gonna return the validation so in here now to just validate this how we have to do is just do the same thing cost error that we did and set this equal to register validation and just had that request body and that's it everything should still work the same so we can actually take a look at this and make sure everything is ok and here let's delete some of the password and hit Send and yep there we go everything still works it's the same so we have validation and we also added it to the login and we separated everything so everything looks nice so perfect now let's go to the other issue which is gonna be that we need to make sure that when we register we don't register again with the same email because we don't want to have two matching identify add identical emails in our database so to do that that's very simple so here we do the validation here we create a new user alright and here's where we save here is where we catch the error okay so after we validate the data that we're getting from the user here we are checking if the user is already in the database okay and the way we can check that is fairly easy we can create a cost email exists and set that equal to a weight and we're gonna check our database to see if our user are our email already is there so we can go to the user model alright so the model and we can add a find one alright and this is gonna take an object and we can just kind of filter out and check if the email is equal is equal to our request body email alright this is just gonna do a check in our database to make sure that we don't have that and if we do have that then what we can do is say if our email exists right email exists if our email exists then we can just return a response with a status of 400 and send we can send back a message we can do email already exists and again since we added a return and a response and send this is not gonna run anymore so it's gonna check through this first if everything is okay we don't have any errors it's gonna go check our database if we don't have any errors then it's gonna go down here and create the new user hit save and let's take a look now if we try to submit this with the same email so with test boy and let's hit send and hopefully yeah there we got we have email already exists so we cannot create a new user if we hit do test boy-toy then hit send that still create us a new user there we go perfect so we got that working now the the problem that we still have is that our password is blank like this and we it's not hashed so we should hash the password always okay we shouldn't store passwords in plain text that's that's a big big no-no so we can close up the server here and the package that we're gonna use is something called decrypt j/s and it's gonna do exactly that it's going to take our password it's gonna throw in an algorithm and it's gonna change it and add different characters to it and it's gonna make it a mess so we cannot tell what our password is and the only thing the only person that knows what the password is is bcrypt so if we're gonna do a comparison with it to kind of to match it when we're gonna do the login but let me not confuse you too much here and let's just install it and we're gonna see how it kind of works so let's do npm install bcrypt j/s and hit enter all right so there we go now we're gonna wait a bit and the the thing we're gonna do with the what the hashing is gonna be up here okay so right after we check our database as well hash the password so the thing we need to do is we're gonna generate a salt and I know that sounds kind of complicated but don't worry it's not that complicated all we have to do is say create a cost and create a salt and set that equal to we're gonna say wait bcrypt dot chen salt we're gonna add ten here I'm gonna explain what this kind of does let's also import B Crips here because I forgot Const bcrypt it's gonna be equal to require bcrypt dot B group Jas okay and all this does is this salt that we creating is kind of a a mess of a string here and this when we generate the salt with ten it's kind of the complexity of of the string that gets generated and we add this then which is the default I believe and yeah let me just show you alright because that's a bit more simple so we did this salt here and then we create a hash so we can say cost hash password you can set that equal to a weight so again we're doing this away because this may take some time be crypt dot hash all right and here in here you would add the password so request that body that password alright and then the salt alright so the salt basically combines with your passwords and it's gonna create a mumble and the mess of a text and that only be crypt can decrypted ha all right so after we do this so we just generate a salt and then we hash the password with the salt I should have said it like that it's just way more simple but now we don't add the password here from the request up body we just add that hashed password let me add hashed password in here okay and paste that in there head safe and let's try to create another user so in here let's go up here this is gonna be named it's gonna be Johnny boy I have something with Johnny today email is gonna be mumbo-jumbo at yahoo.com and the password is gonna be this is going to no it's gonna be the password is gonna be add cannot explain bcrypt okay hit Send and after we had sent as you can see down here we got Johnny boy mumbo-jumbo and here we have our hashed password so actually the first few characters here would be these salt so as you can see we also have that 10 in there and then it hashes your password so it's actually two parts here going on these salt is one part of the string in here I think this part and the hash password is gonna be this one okay it kind of takes everything puts them together and makes it very hard for you to decode this okay so we have two password we save the user and everything seems to be better now so they have to make everything safe let's go back here refresh and delete our users that don't have the hash password so back here let's take a look all right so this one is hashed so let's get rid of these elite and elite perfect and I believe this one as well okay all right so we have one with hashed password and I'm actually gonna create another user so we can try the logging in and I'm gonna keep the staff ad we're gonna do the email every year I know at yahoo.com and the password is gonna be just super simple Rhino 11 okay hit Send we're creating the you user there we go perfect and here maybe it's not a good idea to even send back this hash password even though my theoretically and like it's very hard to to break or for people to figure it out but just to be safe what you can do is rather than have the whole body here with the response maybe you can just respond with the ID or something so let's go back to our code and when we create a new user here let's go back here so rather than sending the whole saved user what you can do is you can just add an object here and just say user and then you can add that user dot ID in there okay hit save let's just make sure this works and create another one but we're gonna use this one so Eddie right now with right now and just to do a quick example here let's delete that just Eddie just something random sent and now we're just sending back a user with the ID okay perfect so let's go back here with this one and let's try to create a login so here we have our post let me hide this to make more space so we're doing the register and down here we're gonna do the log in so this is gonna be the login this is gonna be router dot pose so it's gonna still be a post slash login all right we're gonna do request response again like so okay and let's kind of think of what we're gonna need well we're gonna need that validation so we made it here all right and so we just need the email and the password so we can pull that in in our alpha J yes login validation okay and we can kind of just copy things from here up here I'm gonna copy everything from here and paste it down here and the login and I'm not gonna do register validation I'm just gonna do login validation all right so everything should still work fine here that's number one hit save alright the next thing that we are gonna need to check is if the email already exists in our database and if it's valid so I think we can also copy that one let's take a look up here alright we can just get this one again and just copy it paste it down here alright checking if the user is already in the image so here I'm checking if the email exists okay and let me make sure everything is ok so we're gonna do a wait user find one again email request body okay so if and we can actually rename this to not email exists let me rename this to I mean I guess we can keep it like this if email exists then well here we want to check not if the email exists we want to check if the email doesn't exist I'm gonna add that exclamation point so if it doesn't exist then hey send back a message here and say that email or password is just not okay email or password is wrong you can do email doesn't exist if you want email doesn't exist so you can either do that or email or password is wrong if you want to do this this is a bit more vague but I mean it's kind of a choice like I've seen some people some people do this just so so likes if someone tries to hack into your account they don't know like the email or the password is wrong so you just get back a vague message but that kind of depends on what you want to do okay so hit save so we are checking if the password email is is there or not and after that we need to check if password is correct all right and the way we can do that is well I the thing is here that I actually need to get the D password from this user all right so we're finding one user here so I'm gonna rename this to user because we're getting back the whole user and I'm just saying if the user all right like that so we're correcting it because I want to access user dot passwords eventually to compare it with the hash password okay so here what we can do is we can just say Const valid pass all right we can check the valid password and what we can do is say oh wait and we're gonna use that bcrypt again we can say bcrypt and we can use something called compare we can compare the information that our user sends in alright so when they log in from the request body and we can check that hash password from our database so all we have to do is and here is to pass in the request body dot password so the one we're sending when we're logging again comma and the user dot password alright the hashed one from the database okay and once we we get this back if the password is not valid so we can just do if this is not valid so if not valid pass then we can return a rest with the status of 400 and send a message with invalid password or I guess we can do email or password is wrong so we can't do that again but for now just for debugging and checking out and in postman we can just do it here like so just so we know everything works email is not found hit save all right so we are checking everything and once everything is checked I guess we can just send back a res dots and I'm just gonna send back a string for now and say success or logged in okay perfect all right let's take a look if this works app crashed No all right what's wrong well a wait it says that that a wait is wrong here and the reason why that is is because we didn't add a sync up here okay it's safe now this should work okay it works so let's take a look here now we need to navigate to the login so not register anymore and let's go to log n okay we don't need the email the name anymore only the email and the password we can check also if our validation works let's delete this dot-com hits send email must be valid all right so our our thing works let's also make sure this works send password must be at least six characters long so that works as well okay now let's try to mess up our email so I'm just gonna say Eddie like that send email is not found so let's try tries to look apart in our database it's not gonna find it and it's gonna send this error back okay let's add this back right now and I'm gonna mess up the password this time so I'm just gonna say something random hits send it's gonna say invalid password so our password works as well now if I add this correctly so the email and the password had sent we are getting back locked in whoa there we go all right but we're not done yet but I want you to be proud of yourself if you got to this part and I want you to grab your water take a break one minute break life is wonderful when things work okay now what is the last step we need to do well the last step would be to add a JWT token and all that is is right now when we make requests so let's say we log in and then when I want to make another request let's say I want to post something a a blog post or I want to post a message let's say we have a route with posting different posts okay well once I make that post it doesn't know I logged in so that's why we use JSON web tokens it's kind of like when you log in you're gonna get a a token okay and with that token every time you make a request you can show that token and once it's shown it knows that you're logged in okay so it's kind of like a a little a little token that remembers that you're logged in okay so let's take a look on how we can add that so that would be added in here so right after we validate our passwords and we log in here we would add that token so what we can do is close this up and we can just npm install and this is called let me make sure I get the package name correctly JSON so a JSON web token like so hit enter wait for this to install we can go back up here and we can just import it until this installs we can say cost JWT I'm gonna use a shortcut here and require JSON web token okay down here and let's say let's see alright so in our login down here let me close this up as well just to make some space let's go back to our aunt here and what we can do is we can just create that token create and assign a token okay we can just say Kant's token set this equal to j ee t dot sign and what we need to do here is we can send along some information in that JWT token so for now let's just add I'm gonna add the ID like so put the user ID make sure it's underscore there as well so what you can do here is you can just pass in kind of some data alright and I'm just sending the user ID so in your front-end in your code you would be you can when you log in you have access to this ID and you know that your user is logged in so this is the thing kind of we are sending here and the second argument that it takes is a random kind of a password to thank a secret and this secret kind of lives in your dot environment so here we can discrete a token secret so we can say token secret and you're gonna have that anything in here I'm just gonna add something random like so so we can access that on process that environment dot token secret all right is that correct token secret okay so we are creating this token and then we can add it to our header so we can say res dot header and in here we can add any name we want so this is kind of an identifier I'm just gonna say off token and the second argument is gonna be D token that we just made and we can just kind of take this at the end and delete it I'm gonna send back that token to the screen so we can see all right so this kind of looks weird as hell I know I'm sorry but let's kind of go over this again so let's just what try to log in and see what happens okay so rather than sending back that success let's hit Send and now our code blocks so let's take a look we need to start this thing up NPM started oh my goodness alright up and running perfect let's try this again so hit Send and right now you are getting back this long string alright and we can copy this and if you go to GWT GWT token not just JWT and go into the first website dot IO you can paste in your GWT token in here so hit paste and this is what you're gonna get here you're gonna get a payload and look at that we are saving our user ID in here so again you can send this to your front-end code then you can check that your user is logged in and with that now since you have that log that that token on your front-end you can make multiple requests and one since you have that token it's gonna remember that it's you okay and even if you have private routes which we're gonna take a look at in a bit you can verify that token okay you can go to maybe if you try the post or something and it's like hey you're gonna post unless you're logged in well I have this token okay well what does that though can say well that that we can say that it's user five see blah blah blah blah okay cool user five see can post perfect and you can post under that user with this token so that's kind of the thing that it does but you might be thinking okay well since we're saving this and we can access it what if somebody just kind of messes around with this and they change it so maybe they change the ID and they get access to my account well not really because there's two things here if you if I try to change this ID look at that this this code is also gonna change so it's not gonna be valid anymore and there's also a secret remember we added a secret and here the secret in here so this the only art are they bass only our our back end is gonna know about this secret so if people try to mess around with that well it's not gonna work anymore oh and also we have this I 80 in here which is pretty much saying when this when this was created okay the date and we can also make this J that we Tito can expire if we want so we can only keep it for like an hour or something and then you would have to log back in but for now let's just keep it like that we assign it and we add it to our header and we send it so now take a look in our headers now we have that off token FLE available here all right now let's take a look on how we can create private routes with this well I would create a new folder here so I'm just gonna create a new folder actually a new file I apologize I'm gonna call this verify token or you can call it private routes or something let's rename this dodgy yes I forgot the extension alright I'm just gonna bring an JWT here I'm gonna say require JSON web token alright I'm gonna create a function here and this is actually going to be a middleware function and we can add it to routes that we want to be protected so I'm going to say request response and next all right this how you can create a middleware and in here let's name this off or verify or something and in here we can just get that token from our header so we can same columns token equals two requests so it's gonna be in our request request thought header and we can check that off token all right this is all it does it checks if when we're sending a request if it has that token and if it does or if it doesn't so I'm gonna check if a dozen now then we can return a rest out status 401 here and we can say sent access denied all right that's all 401 is is that a resource that we cannot access okay after we do that after we check we can do a try and a catch here catch error and in here what we can do in our try we can say cost fair v is equal to GWT and we can verify that token so JWT by verify d token this one okay it's a comma and we can do that process we need to pass this secret in here process dot environment dot what was the name of it it's token secret copy that paste it in here perfect and if we're verifying it and if it's verified and everything is okay we can add that to our user so request dot user and it's verified and all it does here so let's kind of take a look at what's happening here and also here let me just kind of send back a response status 400 dots and and valid token here all right so the kind of what's happening here is we create a middleware function and we can add this middleware function to any route we want so any route we want to be protected or private we don't want them to access it without having this token okay so we created this function that checks if that user has that token and remember we assign that token when the user logs in so when you log in we said that token in the response header here so res dot header off token with that token that gets generated when the user logs in okay so now every private route that we're trying to access we're gonna add this function before it to check if this token is available so what we're doing here is we say constituents that is equal to request header auth token so we're checking the name right so request header because the name of that token lives on this auth token all right this is just a name we gave in here all right we could have named this anything we wanted but we named it like this and we gave it the value so here what we do is we check so we get the token after you request the header and if this doesn't exist well it's gonna throw us back an error saying that hey you don't have a token well you don't have access so access denied screw you leave me alone but if it has a token well then we can verify it so that's when that's what we're trying to do here we're gonna try to verify it so we're gonna create a variable here verified and we're gonna set that equal to JWT that verify which is to say a methods that GWT has and you need to pass in the token so the token that's coming from our request on header and the secret all right that we created and once it's verified well what this verify is gonna throw us back is that I be all right that ID that we had in here so if I show you where basically this one all right so that's what we're setting it equal to so we get this payload back all right so request that user verified perfect and actually we have access to this as well as far as I know okay so once we do that and here if it's not verified well we just send back an invalid token all right that's it and now the cool thing is we're gonna have access to that request dot user here in all of our code okay so let's try to make a a route private now we only have these two here so the log in and the the register but all right that's fine let's just try to create a new one really quickly here it's a new file I'm gonna create a what is this is gonna be like let's say posts dodged a yes here I'm gonna copy multiple things from here let's do router let's get the router paste it in here and I'm gonna module exports the router I'll just create a route here okay just something super simple router dot get slash just lash okay and request/response and here I'm just gonna send back here as dot JSON with posts to the title of I haven't now my first post and just maybe a description or something like that description just some random data random data you shouldn't access without being logged in access I can't spell anymore or there we go I'm just gonna send back a response to right now we did this so post and we can import it in here so we're gonna say Const post route is equal to require all right we're just gonna navigate again routes and posts and here down here where we have route middleware we can just say AB dot use when our users navigate to slash API slash post posts like that then we can use this post route okay let's save and let's take a look so now when we just never get to posts API slash posts we should get that post API slash posts alright and we go to get perfect and just hit Send let's go to the body here and take a look at that we get back this information alright so the way you can make this private is actually very simple we can go here to our verify token and we can export this I'm just gonna remove this off from here and just say the same module dot exports and set it equal to this function alright and I'm exporting okay so this is what we're exporting and we can bring it back anywhere we want so if I want to make this route this post route private all I can do is just bring it in here cons verify is equal to require dot slash verify token okay like that and now all I can do is just add it right after this slash so in here we can actually add in middleware so I can just add verify and that's it that's all we need to do let's take a look hit Send again access denied very cool doesn't work anymore however let's take a look on how we can make it work we can go to API login let's go back to user login alright and this is gonna be a post with this information hit Send alright now we get this code so our token I'm gonna copy this and now if I go to the get again and go back to user slash API slash posts alright so this doesn't work again but if I add that token in our header in here so it's gonna be off token and just give it the value of the logged in user and hit Send well let's take a look it doesn't seem to work cuz we need to add next to continue to the next middleware and everything so all you have to do is just go back here to the verify token and after this you just call next alright and then everything should work just fine so in here let's take a look if we don't have the auth token it's sent we have access denied once we have the auth token there we go we get back all of our posts so whoo there we go and the cool thing here is that we can search that individual users information or anything or posts if we want in here because with this now what we can do is we have remember we set that token with the ID of the user so now we have access so let's take a look here see request user as with this token so we have access to that user now we can say res dot send request dot user all right and this should as long as we provide this token we should get that so let's send and take a look at that we have the ID and the experiment and the data was created D token so take a look at that now with every request we have access to that user so if we want to find a user based on that token we can just say we can get that user dot find by one or something and we can just pass in the ID that's equal to the request thought user and that's gonna pull out and from information based on the individual users all right so that's very cool and that's that's pretty much it that's JSON web token and that's how you can create private routes just create a middleware and you can just pass it to the routes you want to be protected so oh my god I'm sorry if I mumbled around too much my voice hurts a bit but that's kind of generally the whole idea all right there we go I know you covered a lot of topics in this video if you have like if you're very new to note I have like two videos on my channel one with note and one with creating a REST API for beginners so take a look at those maybe and then jump back to this one and see if you understand it a bit better but hey that's that's it for me hope you enjoyed this episode I will be coming back later because I'm drinking so much energy drinks that I'm probably gonna start pumping out three videos a week so oh my goodness alright everybody drop drop subs drop the bell hit the bell I don't but deep what do you do with the Bell I have no idea okay see you next time at you
Info
Channel: Dev Ed
Views: 545,450
Rating: 4.9636054 out of 5
Keywords: rest api, json web token, web development, node js, restful api, node authentication, node authentication tutorial, node jwt, node jwt tutorial, nodejs api, node js authentication, node js express, node js express mongodb tutorial, express js, node js api, hashing passwords, express routes, jsonwebtoken, jsonwebtoken nodejs, dev ed, connect to database node js, node private routes, express validation
Id: 2jqok-WgelI
Channel Id: undefined
Length: 75min 41sec (4541 seconds)
Published: Sun May 19 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.