Build Login/Register API Server w/ Authentication | JWT Express AUTH using Passport.JS and Sequelize

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone in this video we're going to create a full login and register system with authentication on node.js we're going to be using also the help of passport.js and sqlize to make sure that we create the database right with mysql and for the passport.js it's going to allow us to authenticate the users and use json web tokens or shorts of gwt so if you're familiar with gwt dwt is mainly used for authenticating users and making sure they get the right access to the right place on the server so for specific resources on the server you might have like roles for a specific admin only can access or just a normal user can access a customer or something and so on and so forth so using gwt it tells you exactly who is this type of user and if he does have pretty much the actual right to access this resource on the server and so on and so forth so i'm going to be using this passport.js and that password just is not only specifically made for gwts it just like has a lot of strategies you can use it for oauth which is mainly for like authenticating or creating accounts using the help of other google accounts like google facebook spotify apple whatever so each one has its own support and password.js can do that perfectly so yeah it's going to be used in here as closing here this is just a basic server i've created uh nothing too complicated just like returns in a basic api like i returns here as a json it returns message and just like having simple emojis in here just like for the sake of funny and uh yeah the perfect parts about this i'm going to be using for the code is actually this starter pack or express api starter so you can go to the github here and you can you can pretty much find it all the way around so this is going to be using this is what i just like i cloned and i tried to work with it has pretty much most of the things we need to install like nodemon eslints those probably won't be needed but something like dot emp and helmet and morgan all of these middlewares like they're already being set up for you and why we need to use this they basically out of the scope of this video tutorial but for like a production or just like always you have to keep make sure that you install these because they just like provide the security uh the needed hitters for making sure your application stands out and it just like works as perfectly as it could be and just like this one's make sure it does happen uh through your project so this is why i just like put this one i cloned it and currently working absolutely fine so if we jump in here as quickly this is actually the code and this is the repository going to be working on as i said before i cloned it and also just did go through it and created the database like i i already initialized the sqlize database connected it to my sql which is running the bank around there so you should already be familiar with this because we're not going to just cover my sequel in here how to create my sequel models and so on and so forth so if you wanted to learn more about my sequel and how to work with my 6.0.s just like an in-depth tutorial or course on sqlize and my sequel you can pretty much go to like the only description i've got a full video for you made by me and um yeah it's absolutely just like from scratch and just like a less than an hour you will master or sequalize and you can just get up and running with sqlite in no time so you can go ahead and just watch the video to know more about it um yeah so this is basically what we're gonna have and for the dependencies as we always start with it's pretty much those are the dependencies you're going to be astonished since i just like downloaded the starter pack what i did install afterwards so most of them came pre-installed but what i did install is actually my sequel too because this is actually the my sequel adapter and also install password so just like did uh npm install password i installed sqlize here i also installed the json web token so just for the gwt uh setup and it's just signing tokens and stuff like that and um yeah so this is basically all we're gonna need to be installing and this is all it's just like needed uh also we might need less like one more thing because you got like passports also you might need to like go ahead and install passwords dwt this is actually the adapter uh or more like a strategy for the passwords in order to tell us we're going to be working with dwt so it's going to provide us with just like helper functions that allows us to work with gwt out of the box so yeah this is basically what we need for now and this is pretty much all the dependencies have been installed and just ready to go so if we jump back in here this is actually this folder structure is pretty basic if we jump to the index.js um here we got just like starting up the application which is basically an express application and listing a port 5000 and here for the environment we've got just like i've got emv.sample which is basic file and this is pretty much where the configuration is going to live so for example the database name database user database password and so on and so forth um yeah so you have to make sure just like clone this one you can copy this and make sure it just like goes dot emv only not dot sample because i put all my configuration in there i want to expose other things with passwords but yeah so yeah just like change this with your password database and make sure just say development of production it's not not really that important and yeah so everything is set up right there so this is where it gets started and we got the object gs in here just like using some middlewares and most parts here which link into the api series in here we're using api forward slash v1 which means we are using some versioning to our api which is always a good idea to do another big projects a production ready products you want to just like ship out and deploy so always make sure to version your s4 apis because it's very important later on if you just like want to upgrade everything from the ground up and it's like i'm going to introduce a breaking changes to the api structure well basically it's going to help you a lot so you're just going to like appreciate it if you try to do so so yeah versioning is always important in apis and here just like mouse changes like particular middleware on express and using basically just doing response json and doing the job perfectly so yeah this is basically the full structure we've got it's pretty simple nothing too complicated and the last thing you need to cover is actually the models which is using a sqlize model i already created one i gone and created the user model which has a full name has an email and a password basically that's that's all and this one is going to allow us to create an user model so later on we can use it to manipulate the user uh in particular so for example you can register a user so we create or save the user data into the database into like the users table on later on if you want to just like log in so we check if the user with this particular password exists or not and so on and so forth so yeah this is basically what we're going to be needing for the user for nothing too complicated now yeah without further ado let's go ahead and get started and since always for like deal with wt's and uh like passport.js to work perfectly i'm just gonna get rid of these i already connected everything in here so i'm just gonna get started just gonna create it just here i'm gonna create another folder called auth and this one is gonna like represent or be responsible for the authentication of our like you know the whole application authentication from users if you've got like different entities you can put them there too but yeah i'm just going to create this folder just like for the sake of making the structure much more clear i'm just going to put it right there and here i'm going to create a file called passport yes so this file is going to just like represent or work as middleware and this is going to just like provide some configuration or how password dwt works at the first place and we just simply tell what is the difference strategy or what is the particular strategy you're going to be using for authenticating using password.js so we're going to leave this out for now just create it in just like for the sake of simplicity and knowing exactly what we're going to do throughout the video so this one's going to be just like meant for authentication now the first part like we're going to creating like a login for a slash register system where the user can just like submit his data throughout the api or if you're working with a front end well basically you're just going to send this data using an ajax using something like axios or you can use the fetch esx fetch version or new feature well probably how it works is just like you send it specify the particular url like forward slash api for slash v1 then forward slash register so this register wraps gonna allows us to register the user to the database and save his info so yeah we have to handle that particularly i'm going to be using express to pretty much just handle that tell you that oh if this like is posting or just like hitting the register route particularly just go ahead and run this function and register the user to the database and just like do all the things necessary to in order to make sure that the user is registered perfectly to the database so we can later on do the login and fetch the data and make sure we authenticate him the right way possible so yeah this is going to be doing throughout this one um what i'm going to be doing i'm just going to use it on the ap on so if you check out the api it's basically just on the index.jsx or javascripts i'm not using react here sorry so index.js what we have is basically we got router which is normal express router and the built-in router and i'm just doing like if it gets to the main homepage is gonna return return json api and for this one it is nested why because how apis works or how the router express works since this router is i'm exporting it right here of course so if you take a look what it is being called at first so if we jump into the index.js not here here we got the application so we jumped up js here we got the api and remember we're doing app.eus and bounding this one to the api which means now this one is going to be used as the home or the default forward slash relatively to the api right here so now the api one is just like referencing a forward slash it doesn't mean the whole or the root of the whole server now it does like only relatively to where it's being used or called so this one is just gonna mean like just put in a forward slash right here and this is exactly what we're doing so this is exactly how we are making it to happen um and this is how relative like or how the express router uh works behind the scenes and this is just like what i wanted to mention because some of you guys might just like go ahead and mix between this and just like um the main home page you just like go forward slash without any other uh parameters or the api version thingy happening there so yeah this is just like what i made sure to clarify before getting any further and uh yeah so here's actually the router is pretty simple as before i don't need this anymore uh so you can just like get rid of it for now and we got the router now we're going to create another one this one is going to like act as the main index of the entry point here for the api i'm going to create register dot js okay so this reduces javascript it's going to handle the api requests when he wants to register a new user so therefore i'm going to be doing the same thing here i'm just going to use the router again so i'm just going to do calls router express so make sure to require express first and just say roush you can pass him some options but not really that needed just like for the sake of if you want like an advanced access to a router you can do so but it's not really mandatory currently now we can just do a router and we can do uh eu's or we can use one of these like http available methods like git or post or something and for just student new user we're mainly going to be needing post requests you can use put but it's not mostly or not likely going to be used a lot and mainly a lot of people use posts in here because it's just like most famous http requests or http methods sorry so yeah you can pretty much use post for that particular case for the path name here we're going to be doing like just forward slash register and this one is going to be relative to all the other routers so for this router we're going to just like once we do router.eu's so it's going to be relative to it let me just explain this in a second so this one is going to be normal function it's going to have request and response as a normal uh like express js handler so just like a normal crest and response and now we just do module.export and export the actual router otherwise it won't work perfectly for us and it's just like gonna have some difficulty so make sure to export the router then later on on the main entry point for our api you can just go ahead and use it so we can do um it's gonna import it first so it's going to be relative so just like to router dot eu's and here i'm just using like use i'm not providing with the with no parameters like not providing with a particular path name if i would provide it with a path name here it was just like telling you for example like forward slash uh hello so later on to access the register api you have to go like forward slash hello forward slash register of course you have to go first like the most obvious ones go like api then for flash v1 then hello then register so this is actually the most obvious part but since right here i'm just not going to be using it because it just doesn't make any sense i'm just going to use directly the register api and this time it should work perfectly if we just go for the register and let's go and test make sure it works perfectly it's going to do response json message work okay so i'm just gonna save that let's go back right here and already run the server in here so it's running using nodemon or node monitor and it's running on port 5000 you can specify the port on the emv here as we have seen it before uh you can just do like ports and you can specify custom parts but it's not really important that much so yeah that's going to just take um take a look for that particular case um where is this okay i think all right so just go forward api okay let's see so api and v1 [Music] right um yeah it says not found because you're using a post request mainly so if i just like do this as a get go back refresh it and there you go so his currency works perfectly fine without any issues just like by using the cut request now we're going to be sending it a post request so we're not going to be using the browser to test it anymore what we're going to be using more precisely is postman so postman is curious and it's pretty awesome tool allows you to test your apis and just keep track of them do custom hitters do authorization you can sync your data sync your requests responses with your teams it's just like mental how a postman can handle all that and it's great ecosystem and an awesome tool there's all other tools like insomnia which i i used in a couple of other like my last video shows but i found postman it's more robust and reliable and the system of it is just huge so yeah we're going to be using that particular case so let's just go ahead and um i think we can just grab this one and we can just give it a test for postman and i think so i'm just going to register we're going to put in here post uh you can go and give it a name but not really right now and we can just going to send a post request to for a slight register as clearly you see we get the response hello world so the response works the request is being taken seriously and everything is being just like handled perfectly as we want it to be now let's go ahead and work on the registration of the actual user and make sure just like everything goes and being registered into the actual database so first things first we're going to be needing is actually the request and we have to handle or against the request body so remember once we just access postman here and from the body that was going to be sent in make sure to send it as just like a form data where you can send it x form url encoded data they are both almost the same but mainly just send it in an x www form you are encoded is much better because this one is mainly like um for transferring your files and raw data but this one is just more pretended for a json data so yeah you can go to passing the data in here i can say like for example uh full name and you can say i don't know alex i'm gonna need description and email alex at mail.com and password you can just like do one two three four five six seven eight just for testing uh if we go back in here let me just um let me just bring back that just for justin purposes i'm going to be doing is console.log the request dot body okay so if you go here we send it uh screws in here we got like request dot body uh is being empty and that's mainly because we haven't installed uh the body parts so yeah let's go and just do it so i'm pretty sure most of you have got this issue if you like works with express and try to do like a post request and access the body data so you just like all of a sudden find out oh it's an empty object while just look for this in here we're sending the properties like the key values or sending the data but it's not being received by express why well mainly because express is not like parsing it as json right it's not being put into the body in here because you need to use like a special body parcel library that hooks up or it's more like a middleware of express that hooks up in underneath express and just like parses all the data being like exposed throughout url encoded then just like puts it all inside of this like body of objects so what's gonna make for sure that happens right here it's going to do npm install body parser it's as simple as that and make sure you just like install it real quick then we can just go ahead and use it so let's go ahead and include this in um our express application make sure to use this middleware so i'm just gonna do use and let's go ahead and like require body parts from the top here just like acquire body parasite and uh there is this parser and make sure to use json middleware here because otherwise it won't perfectly work for you and the other thing we need to be using is actually url encoded so it's like body powerster is like more a combination of middlewares and each one represents a specific case of like how parsing the body works so we're going to be needing to parse it as json first and also we're going to be needing to parse it as url encoded so just do like you're encoded make sure to do extended otherwise you won't work for you perfectly so extended means like the whole url properties everything is encoded will be just like parsed correctly so i'm just going to extend it put it to true and make sure your encoder comes before the json because it first decodes the url then it just like converts it to json so this is probably uh the best way to put it so yeah make sure you just do a body parser and it should work perfectly for you uh the right way here so yeah afterwards here we got the register everything let's gonna try and test it out one more time so if you do send there you go so now we got the full name email and password being exposed to us throughout the body objects cool so now we can just get it started and start actually putting it into the actual user data and saving it to the database so it's going to import the user first so we're going to do a user equals require uh so i'm just going to go back into it's more like models i think so i'm not mistaken yeah so morals user and we've got the user in here should go into it it has basically like a full name email and password nothing more less so i'm gonna do it here new user um it's gonna be having like here and i'm going to be like initiating the user and first option in here or the first parameter it takes the values so values like full name email and password so we can just like simply put the request the body and make sure you just like you can put it this way or for secure reasons mostly what you need just like specified parameters because sometimes they send like um other kind of like if a prince resting tester or a hacker or something intend to say other attributes in here other like just like fields in here that are not allowed to be saved as an user and mainly they're not going to be parsed correctly or not going to be saved by sql eyes in the first place but sometimes there should like there's a vulnerability here here or there is a bug going on so yeah they could it could bring something so make sure always to double check your code to make sure just like to go with the easiest and this secure way possible in order to like put your data together and i'm going to do like use es6 destructuring so i'm going to do full name email password simply it's going to destruct it out of the body so this way it's more and more secure and i correctly know which part i'm putting together and which i'm not so i'm just going to provide the password that's simply where it is um for that now user we can just go and call save on this one and this one is clearly returns a promise so we have to wait for the promise to finish we can like we can do then or catch but we can use something real cool which is async aways which comes bundled from like uh the version of seven point sync of node.js which is i'm currently running like uh 12 or 13 of them gs so if that makes sense um yeah it could it could be better to use async awaiting here to make it more like synchronous code instead of like van and call backs and everything it's going to be waiting here to make sure to save i'm also going to be using cache so if an error happens along the way i'm just going to catch it out and all i'm going to be doing is console.log error there and we can just do like um um now i'm just gonna test it for now and see how things should be going on also what i need to do is pretty much double check before saving a user if the user already exists with its like current name with the full name so if the full name all the email already exists we're just not going to simply just throw an error and say oh you can't register again because the user is already registered so let's gonna put this here um we're gonna do i'm just gonna const already exists users going to do weights again i'm going to use user to find one i'm just going to provide it with where it's going to provide it with full name or email so if it finds this uh with the full name or with the email we can just lock it at it past but for now i'm just going to use it email i'm not going to put both just like for the sake of simplicity because we're not focusing on this part a lot of sqlize part you can do it in many ways possible so yeah you can handle it the way you want it computer console.log error error now if you already exist so if already exists all i'm going to be doing just like return and just like return a response okay i'm just going to do return response dots json i'm going to say message the user the email already exists okay so that should be pretty self-explanatory now for the error right here what we can do is pretty much pretty simple we can just like go and do response dot json message or you can just do like error better than a message uh cannot register user at the moment okay and the sake of like how express works and how the whole asynchronous mechanism and paradigm works so you have to double check you can't just like send this json if an error occurs so the catch here is going to like be cold asynchronously so which means this one is going to work or this one is going to be executed and that one is also going to be executed afterwards so we have to make sure like double check if this one if an error happens we don't need to like send uh this this particular message right here which gonna be like uh thanks for registering so what we can do we can go in here here save user now if you do like if save the user you've got this otherwise you can do else if there's no safe user we can just send this one or maybe just remove it because if an error happens it's just going to send this one so yeah we don't need to like make it a little bit more complicated than it already is and yeah so this one should be pretty simple pretty easy to be put together let's go ahead and try to send a request of a particular user so alex email.com and we got all the provision data in here so it's going to do like send so cannot register user at the moment and uh let's see so sql statements uh there was actually an issue so table doesn't exist uh mainly because we haven't created the table already so yeah that is that is exactly why this is not working so we can just simply use the feature of sqlize of synchronization of models so which means automatically crease the table for you uh depending or looking at the entity of gods or the models so for the user model just gonna pick it up and say oh there's a user model so it's gonna be creating the actual table for it on the database automatically so it's just like huge improvements and it just makes things goes much much easier so to do so i'm just going to do like sqlize dot sync and this one is going to just like synchronize all the fine models to the database so this is all we need just by saving is greasing here we've got like a brand new log line in here which is like create table of not exist users table and blah blah blah so on and so forth so here's creating the actual user for us automatically from the model and um yeah we got everything working that's fine so let's go back and let's try using postman again so let's just send it and boom so we got things for registering and it's cruising here if you take a look this one is just more like a debugging or a fair boss uh sequence does which is pretty great just gives you like what is being executed in terms of like sql statements and it's like being like doing a first select it checks if the user with this mail exists no if it doesn't so it's going to insert users and it just has all the data of this being considered to the database so how cool is that pretty awesome actually and we got everything as we want it to be now let's go and try to like register again with the same name and email and seriously we got user with email already exists so we can't use the same email over and over again like that way so yeah pretty cool so the first step of our like system or authentication system has been done which is registering your user to the database and making sure that everything works exactly as we want it to be let's create the most important parts in in all this system is actually authenticating the user and logging in him what i mean by login is actually like checking or validating the user info for example providing an email and a password so you make sure that the email password matches ones in the database so if it does match everything in the database we can just go ahead and sign in up a dwt token so this token later on it can be used on like authentication and i'm doing all the requests so this sequence is going to be returned through on the response to the user it can be put on like a cookies or a session storage or a local storage more likely and the best way possible so you can put it and there and we can like whenever we want to send a request for example we get like a change of password for user it requires the gwt for securities because only that user authenticated he can change his password of course so he sends it to him and he gets the right authenticity to change the password and do whatever he wants so this is exactly how authentication works just in the simple terms we're going to see more in depth and once we create that authentication parts so let's go ahead and do this here since the api it's going to name this login.js or login.javascript and for that particular case i'm going to create the same as it did with the register here so just going to copy all the things and i want to just like put it over and over again i'm going to be using browser i'm going to be pushing or using post and for this one i'm going to do login use async put question response again and here we got all of that so here's actually the request and response and everything i'm going to be needing let's go ahead and link it up first to make sure it goes the right way so you can do router dropping use and login api so we got login on the top right there we can just use it as a middleware and you should make sure everything goes the right way and that error is coming out because we haven't exported this we're going to do like warrior exports just export the voucher and it should be fine so yeah pretty cool now we got the actual login and being set up in here so for logging here the actual user what i should enter is pretty much his email and password so on we can take it and validate it with the ones that already exist on the database so if the email does already exist in database we're going to check the password if the password exists the database boom so we can just like authenticate him prepare the gwt token which is the most important part for authentication later on and just like send it back through the response so let's go and do that and for requesting here we're just going to have the body again express all of this so you're going to have email and password and both is going to be extracted from request.body now we got the email and password first things first we have to check the email if it does exist then we can proceed with a password so i'm going to just do user with email so i'm going to do user dot find one and only one i'm going to use where close and i'm going to put email okay so it's going to find this one using email of course if the error happens i'm just going to do console.log okay and there you go so here we got user email and if they check so if not a user with email which means email doesn't exist the user doesn't even exist there so what we can do is just like check that out oh it doesn't exist we can just simply return response.json say error i'm just going to simply say message because it's not more like an error just like a message oh you can't log in because email is not valid of course so we can do um email or password does not match and the reasoning here i'm just saying email or password because for security reasons you don't want to specify oh email doesn't exist then if you just like email exist that password doesn't match you say oh password is wrong you don't want to give this specificity or this like kind of info to anybody because logging can be used by anyone and security here matters a lot so just make sure to always just always try to make as less info as you could just to make it much more secure and doesn't let people know exactly what you're doing behind the scenes there on the server so this is the first part there now if the email exists and everything goes fine we can go in and then check out the password so if you check the password we can do um so if user with email the password so we can just simply that to access the password equals i'm just going to say not equals because i'm just going to do error first kind of approach so if it doesn't equal i'm just going to throw up an errors to him say you can't log in so if it doesn't equal the actual password provided what we can do just like again return response json message and say the same exact message email password does not match simple enough so nothing too complicated nothing too hard on that part so this one should check out the password as well it should check out the email and make sure everything goes the right way now basketball thinks what we need to do just like return and sign up the actual data so as we talked before about dwt is actually creating and assigning that particular kind of data so let me just show you that in a second for that particular case this is actually how json web tokens works or usually look like for gw2.io we can see this is basically what a gwc looks like it is like base64 encoded and and it has like a sha 255 encryption so yeah you got that it's all being encrypted using 255 bit secret key because you're going to be including this 255 secret creature like make sure nobody can decode the dnr and here like he uses hs256 and this is actually the payload you're going to find and this payload so whenever this kind of dwt is going to be sent out to you to the server you can decode it using your secret key then you can get this p load so you can you can get access to all this data and for example you can store the id or store like email never store passwords by the way it's pretty bad to do so just store like normal info like email id you can then later on use it to retrieve the particular user from the database so this is basically how it works and let's go and try to work with it right now i'm going to be using the help of json web tokens for like creating and make sure like we generate the exact data we want so what's gonna do uh for signing the data i'm gonna just import that first so i'm gonna do like dwt equals acquire web token okay now for dwt we can use the sign method and the sign method in here you give it a payload and you give it a secret and it just like returns to you a valid gwt token so redeem it like uh ewt [Music] token equals the sign here and let's check so the sign here is not like a promise it's a synchronous function so synchronously assign the given payload into a json web token string payload okay that is actually pretty great and the first parameter let me check this is actually a payload and it is the secret the second one so we can have the payload i'm simply going to be using payload using the id of the user and we're going to be using something like an email i'm going to be putting both of them you can just put the id but i'm just going to put both of them just the sake of simplicity for that i'm going to say id user with email id and email email so this one should do the job what most of the people and how most of the systems work if they put like an ext which is expiration and later on once they receive the gw token and validate it they check if the expiration uh you know has passed out the time or the time interval so this is more like for limiting the gwt the lifetime of the gwt token like you can give it like a week or two days or something and this is pretty perfect but for now i'm not going to be using it because it's kind of more like an advanced approach and we're just going through basic stuff for currently and yeah so there you go this is what we need and for the secret here what we can have i can can put something on the emv here or something uh or you can put like a normal file and you can store it but i rather put it inside of the amv because it's it's much better to do so so i put something inside of like the emva he named it like gwt underscore secret and it's it looks like something like this like you know pretty robust um pretty complicated to decode so you want something as complicated as possible because you don't want all the sudden hackers getting into your like server for just like a simple dwt token obviously so yeah make sure to do so the perfect way and here i'm going to use process.emv and i'm gonna use dwt secret and that should do the job now after signing up we're gonna get the gw token and lastly i can do response json message i can say welcome back because he has authenticated and i can say here um let's let's name it token okay we're gonna be passing dwt token so yeah let's go ahead and test that out just gonna hit the login with the email and password and postman so i'm gonna create a new request uh let's copy all of that again i'm gonna go for slash login body i'm going to go form url encoded i'm going to have your email to alex mail.com password i believe we put it on one which is takes four six seven eight i think let's check yeah it is that way and make sure to put this one as post so if we send it there you go so we got we'll come back and we got the dwc token being coded for us with the data we provided so the payload now has the email the id later on we can decode and retrieve the id and we can double check the user and so on and so forth and this is exactly how authentication works in like uh simple manners just getting that thing here and there and and it's pretty basic so let's see if we just like put the password the wrong way or the wrong password submits and get email password doesn't match so you're working perfectly fine without any issues so you can put password back again and we got the email and being authenticated so this one this gwt token later on can be taken and put like in local storage or something then it can be used for like authorizing this particular user and telling the server that this user is authenticated and can access the resources available on the server so for example he can change his password he can view his profile for example if you're in a forum he can access the forum post and he can read the content and go through the download page and so on and so forth so this is basically what identifies a particular client or a particular user if he is whether logged in or not so yeah this is this is how it looks like now let's go ahead and just make sure and create like a simple basic secret resource and see how using passport.js we can authenticate either the user depending on the gwc token or not so we're going to go back into the first file we created throughout this video which is auth and passport.js so this one is going to like prepare passport2ds to use the passport.js dwt strategy we tell you that we're going to be parsing or expecting to receive dwt tokens and how to parse them properly and how to tell the users if you're like logged in or accessing resources or not and so on and so forth so let's go ahead and do this right here i'm going to first need a password so we're going to require a password right here now i'm going to do passport.use and this is going to be more like a middleware so password on itself is a middleware and it uses some other middleware so here for eu's we tell you what which strategy we're going to be using throughout this one and how we are going to be using it perfectly so for the strategy we're going to always be using uh passwords gwt so i'm going to just like require passport gwt and for this one how we're going to be using this actually you're going to use passport gwt to extract the actual gwt password so i'm going to here i'm just going to do something passport gwt i'm going to tell it how to use it you're going to use a strategy of course so this is exactly how i am going to be telling you to use that particular strategy we also like has another object which is extracted wc you tell it how it gonna be extracted either from header or header as a bearer token or with a scheme or a field or extractor query parameter whatever you wanted we're gonna be mainly as the standard of like authorization from you know the web standards and how things gonna be used in a standardized way you need to be using it from hitter as a bureau token we're gonna discuss this in a second but it's going to just refactor the code to make it look a little bit more understandable cleaner so i can have this one extracts dwt so equals password dwc they can do extract and for this one i can do like strategy dwt equals passport yeah and strategy okay now here we can do we can actually initiate this we can do strategy new because this is more like a class you have to create an instance off so here say dwt from request and like you specify from exactly where i'm gonna now use extra dwt and do from off heater as a bureau token pretty basic and the second parameter we have to provide our like secret we use later on or black before once we did the login remember this seeker we use it to sign our gwt token there and make sure that it is encoded correctly and it can be decrypted so this is going to be used for encryption and later on you can use it for decryption or decode it again so here for the sql you can do it secret or key and you can provide that and since we use it from the environment you can just provide process emv and dwc secret so pretty simple here pretty simple there um nothing too complicated now the second one it takes in here after the eu's it first takes which strategy gonna be use it and he provided with a callback function this callback is gonna tell you exactly how it's gonna be manipulating or using this strategy to find the actual user so therefore for this particular one i'm going to be using this function the function what it takes it takes actually a gwt payload so the payload we're currently expecting because how this one works this password dot use once we like receive a request and this request is actually needs authentication for example you need to access a forum and you need to access like a post inside of that forum but this forum needs you to be created an account and logged in first before you can view the content so therefore to access it like you create an account you log in you got the gwc inside of like local storage in your browser or something then you only try to use or access the post you send the dwt throughout the hitters and this function in here this one is going to take care of like validating the gwt it checks the vl gwt it sees it like valid and has the proper data and it like matches the proper dwt secret key there if it does it lets you pass if it doesn't just like gonna block you and say oh you're not authorized you don't have the right access to pretty much get into this resource so this is basically how it works throughout this one so first the parameter is going to be the gwt payload we're going to receive from a request and afterwards we're going to have got it done so done this is just basically a callback we call it once we verify that the wt payload is valid 100 valid and we can proceed and let him pass throughout the gate so this is basically this is what we've got um for this one what we can have is pretty basic now nothing too complicated what i can do i can return and we're going to be using the user here okay so it's going to be user equals required we can go models and access usual now why we're going to be using the user because the gwt is concerned about the user remember that we encoded already the app the id and the email of the user so we can grab this id we can check if it does exist on the database if it does it is actually a valid dwt then we can just like put this or take this user instance and we can save it or pass it to the done here so later on throughout the request it can be like accessed easily on the request like whenever we want it to be accessed the actual user that is currently authenticated it's like it's not mandatory to do so but it's much better to put it this way because just like makes things easier to work around and whenever you want to access the currently authenticated user you get it right from this particular body or from that request dot user okay so it's going to do this i can do like a user and find one and this one you can just tell it how to find it i can do where and dwc payload you can access the id so the same way you put it there you've got it this way so the gwt here is going to have like the same thing uh like whenever we're logged in here remember we put it on the id field so once it's being decoded we're going to get it the same way we did it right there so just like id put it as an id and then do then since this one returns a promise so we can just do then they can double check with it if this one does exist and everything so this one again immediately just like provide us with the actual user going to be using so therefore we can do like video return done and done callback in hero text first parameter is null for now i'm gonna not gonna be passing any options to done and i'm gonna be passing it to the user otherwise catch like an issue happened or anything goes around way so what we can have it to be is actually since we got an error here so we can do return done with the actual air so since this one doesn't have an error and just like passing air so remember always node.js uh callbacks like from the standard like perspective it always has the error as the first parameter if no error happens each passing null just to ignore the error there and yeah so this is how it should work perfectly in that way now we can just like validate it does exist we just like to take the user and pass it through that and it should work perfectly in that particular manner now this is actually the most important part of like validating and making sure the dwt tokens are working perfectly the way we want it to be now let's gonna make sure to use this properly and i can just gonna do require so you can go to i think it's like go off and go passport and this one or the middleware would be like read correctly and executed so we don't have to do any further kind of things around the corner now let's just test that out um what is going on here oh yeah because yeah this one the process emv hasn't been populated yet because we are calling this before we call like require.emv so make sure you just like put this pack on the top and yeah it should work perfectly in that manner so he requires a verified callback i should have put this inside of like this strategy not outside i'm sorry so [Music] we can just have all this let me just copy this put it down here and we can have a comma separation there it should do the job yeah perfect now yeah we got everything happening the same way we want it to be uh we got the secret got everything working that's fine now let's go and test that out again and let's try to create some like resource uh that we need to access to so let's go to the api and i'm going to create something like i don't know uh let's call it payments okay it's pretty robust thing you're gonna name it payment i'm gonna use the router thingy so let's copy it again i wanna just like put it all the way same time again so you're going to use the router now the router here is actually going to use something like gets so we want to access some gets and get like what is this payment or how much do i have inside like my payment account or whatever so i can just go on payments and here you can have like a request response this way so for a particular ordinary way anybody can access this one because there is no authentication nothing no layer of security prevents anybody from accessing this one on a particular criteria so if you just do it this way you can do like we're not going to be using this one that's going to use normal text so just go to text send you have a total of 2 400 dollars okay let's test it out let's put this inside of the index.js so cost use payment api okay um yeah because i'm not exporting this as always and there you go so let's use postman again we're going to do the same thing here payments along the way i have gets so if we send it we immediately get like the response we want like we have a total of two four hundred dollars which is not really good because this one this piece of information can only be accessed by a particular user who is authenticated and has the right access to it so not everyone can just like access the website and see this particular information because it is is kind of confidential thing that not not everyone is allowed to look at and see so yeah for this one that's where all the whole paint of this video tour is actually authenticated and make sure not everybody have the right access to pretty much all the dna about the website now this is where the magic of passport authentication comes in handy so we can use passport.js in here i can do like passport require passport and here passport js is all built around like the express ecosystem which means it uses a lot of middlewares that allows experts to hook up instead of like like passwords very easily and very nicely so that way we can we can do it this perfect way like the password and uh you can go ahead and use authenticate so this one allows us to authenticate a particular user the first one here takes what strategy you're going to be using i'm going to be using gwc so we have to specify that and later on it gives you like an object up not for particular options is it sessions so you want to provide it through our session no i'm not because currently it's using a single time dwt so we're not caring much about session just put it false because by default becomes true and that should do the job now if we just go ahead and like put it this way uh if we go to postman if you send what we get is an authorized because we're really not authorized to view that because you've got no piece of information no piece of data that tells us or tells the server that we all we have got the right access to this piece of information how we do so is actually by logging in we grab the gwt token then we can check it out so here's actually the gwto like we logged in before with so i'm just going to copy all of this token make sure to copy every single piece of character of it just took it all go to authorizations closing here this authorization no auth there's api key bureau token and everything but you can also put inside of headers which is i would like to do much and it can put authorization header which is how or the standard header being used you can use a custom header through a password.js configuration but this is the standard header that always being used by you know servers and people around the world working on that so just put that one put it up here but make sure just not put it there only just always for a beer token because remember as we talked about it uh a bit before like when we did like from off hitter as a mirror token so you have to include or prepend mirror to it just like for secure reasons before it works so you have to do a mirror then leave out a space firstly i did leave a space it's it's right here and then you can just like did i leave a space yeah so leave a space then you got your gwt token so if we do send it check that out and something is wrong so i totally forgot about calling this function it is a function on a variable so i talked like forgot about the parentheses there and yeah it was just like a dummy idiot thingy to do so yeah anyway so just like putting that in here would solve it just like for getting the beer token and just like parsing it and get everything there try to just like do some debugging and it should work so i'm just going to jump back into postman and try it again just do beer and there you go so now it works you have a total of like two four hundred dollars if i remove this authorization header do send exclusive tells us unauthorized so if someone doesn't log in and it doesn't have a token so no right to access so he gets like unauthorized but for number anybody else who's like creating accounts then logged in got the token and he uses a token here which is done behind the scenes by any like foreign application for you and facebook twitter youtube whatever so all of these are being done once it sends it there is like it being authorized so you've got to access your data you've got your access your profile your information edit information upload whatever you want to do so this is basically how if like authentication works especially it's much easier using something like passport.js especially provides a lot of strategies you can use a lot of them and so many are available there on npm you can use them right out of the box so yeah so that's what i was just going to do today just putting a full system like login register plus authentication with password or password.js and using a little bit like sqlite so we've got to learn everything uh just like a tee tiny from every bits and parts just to put a full system of login register uh from express into middlewares into using passwords with like strategies i used in post one as well which is pretty helpful sending http requests we also got the chance to learn more about the sqlize and how to put database together to connect it synchronize everything and get everything working together with express and node.js so hope you guys enjoyed this tutorial as i did enjoyed like making every single minute of it so if you did guys enjoy it make sure just put that like button i really appreciate just pushing that like button it just like helps me a lot put more efforts and create more creative uh kind of video stories like this one and just like stay up to date and always subscribe because i see a lot of you guys watching videos and just like not subscribing so make sure you just like subscribe that would really appreciate it and yeah so without further ado guys hope you guys enjoyed that as always as you all hopefully in the next ones [Music] [Music] [Music] you
Info
Channel: CoderOne
Views: 11,393
Rating: undefined out of 5
Keywords: Node.js, Nodejs, Express.js, Expressjs, Passportjs, JWT, Jsonwebtoken, json web token, JWT auth, JWT Authentication, authenticating JWT node.js, RESTFUL API JWT, Express RESTFUL API, Nodejs RESTFUL API, Login API, Register API, login node.js api, register node.js api, Node.js API, Nodejs Server, Server API, Login Server, Register Login Server, Account management Node.js, Node.js Express API, Passport.js API, Passport.js JWT, Passport.js Node.js, Passport js, Passport js Express
Id: VWEJ-GhjU4U
Channel Id: undefined
Length: 64min 1sec (3841 seconds)
Published: Sun Jan 10 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.