NextJS fullstack course | Signup and login

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right hey there everyone hitesh here and welcome to another video or another part of the video in case you're watching in sequence and it's a next year's complete full stack course that you're watching on YouTube of course so in this video I'll walk you through with the next step now this video is almost a part two so in case you have in case you haven't watched the part one go try that or in case you are jumping directly on this portion please don't it's not a good idea so we have seen that how we can handle the front end part a little bit more like a file structure we haven't learned how we can make a web request from the front end to our backend because our backend was not ready in this particular section we are going to learn that how we can create models which can talk to a database we have already configured our database we have already injected our environment variables learned that how we can have a database connection file which can which needs to be called in every single API call because edge cases not edge cases Edge functions which actually run so they don't have a constant database Connection in this we'll start by creating a simple model and that model will be a structure of our database and there's a lot of ways how you can design it I'll walk you through with some of the quirky things and interesting things about it you will definitely enjoy that part and then we'll directly jump into the sign up portion so that we can write a simple apis which can or basically controllers for API which can do the logical part take all the data and send it to the database that's our first goal then we'll figure out what to do next up so that is how we'll be going now let me take you on my screen first so this is our screen that's where we have been enjoying so notice here the models is right now totally empty we have almost nothing in our model so it's a good idea good time to create a new file into it and feel free to call it whatever you like and why is it not listening to me why is it not listening to me so just give me a second probably my keyboard is not working yeah should be working now yep and we'll be calling it as user model M should be capital or not I'll keep it capital user model dot again this would be a simple JS you can make it TS as well I'll make it JS usermodel.js because there is nothing too much sensitive going into this one first question who can talk to my database obviously Mongoose so go ahead import Mongoose that will be coming up from Mongoose now how do we create it simple const let's call this one as user schema and that is going to be simply new Mongoose dot schema and there we go basic just like this now before we go ahead and work about rest of the things let me tell you something really interesting now there is a special way of how you export your models from a mongoose in case of nexjs because there are chances that the model might already be created in the database so in most of the cases in the express and all that the model file doesn't run again and again automatically but here we need to actually import this file quite a lot of time and we need to take care of the cases if it is already created then use that if it is not created just create that so there's a lot of ways how we do that one of the very common user built syntax is just go ahead and take a user and simply go ahead and say Mongoose dot models and then create this users because remember in the mongodb even if you call this in the Mongoose or the model file as user with a capital u everything is lowercased and is pluralized that's a mongodb thing it does it for everything so that is the first thing if it is already created use that otherwise we are going to create our own model so we're going to go ahead and say Mongoose a DOT model demo model and then we will be creating this is going to be a simple model which takes two parameter what do you want to call it in the database and how does it look now usually you'll see that something look like this and again that's totally fine and you can go ahead and call it like this as well there is absolutely no problem in that case why is it giving it like that there we go why is it bothering me this much there we go or if you wish you can go ahead and call it as lowercase users that is also totally fine anyhow end of the day it is going to get created as users lowercase and once you are done with this then you can go ahead and Export it as a default so export default user that's what I prefer that whenever I'm taking this user I always call it as uppercase because it has a lot of superpower it's not any ordinary variable it's coming from from Mongoose so dot save method find one there's a lot of features that comes up as a built-in now apart from this I'll not talk too much about the Mongoose superpower because Mongoose definitely itself deserves a course but I'll just go with the basics for example I'll just go ahead and say hey I'll be having a username and that will be of type string and we're going to go ahead and required it true and provide a customized message of hey and we'll also keep this you username as unique so that will be nice and easy we probably can have a trim but I'm not interested in that already too much and then we'll be having email will be having a type of string and required true please provide an email and let's keep emails as unique as well that is it this much is already more than enough all right now next up we'll be having the password which will be a type of string and require true please provide a password that's it don't want to do any further into the password category now apart from this you'll see that in these kinds of model there are common fields which are there for example uh usually I go with the role because I bring my roles from an enum file constant file from where I can bring the enums like is admin manager student teacher there's a lot of roles with that in this case I'll drill it little bit down so that it doesn't create that much of confusion all the introduction grade application I usually keep it as a role but I'm going to go ahead and use this one here first of all is verified so is the user verified by default no it is not type Boolean of course default is false so my user is by default not verified I will send him an email in which all he'll click a link and once you click the link then only he'll get verified similarly as I was talking about the role I'll just go ahead and call this one as is admin and is admin will be like type Boolean default will be false and probably that's it now again as I mentioned I usually don't go with the is admin I usually go with the role because that's a better approach but again will not go about the better approach or data modeling in this case that's uh very basic now comes up the interesting part now what a lot of people does is they try to keep their tokens as a separate model itself I don't do that usually I try to keep them all separate because I think somehow that they are part of user itself and mongodb is a document database so I think this is a better approach again I could be wrong you could be right so there's a lot of debate about it so the way how I do it is I keep a couple of string like forgot password token and this forgot password token is usually a type of string and I keep on updating the values now along with the forgot password I keep the forgot password token expiry so forgot password pass word token expire nah not happy with expire I go with expiry expiry which is a type of date similar to that I do have a verify token as well very no no suggestions please give me a suggestion there verify token that is also a type of string and similar to that verify token expiry now how does this token works there's a lot of mechanics into that and I would love to share this but this is the whole our model is now complete now let me take you back on our excally draw and show you that how actually the token part and everything works so for this we need to understand what are the three parts of our application so the three part of our application uh the first one being the first one is the user wherever or it would be better to write browser or I'll just write user slash browser so whatever makes sense to you so this is our user and browser so this is first part of it the second part of the application is our controllers or you can say our apis uh I think API would be a greater name but obviously I would love to call it as controller but I think in this case API is also fine and the third part is actually our database where all of these things are stored so if I go back all this data about is admin forgot password token and all these things are actually kept up there now how does this forgot password token or verify token works that is also a very interesting use case so I'll just walk you through so this thing known as your verify token this is nothing it's just a field which holds some string values now obviously these string values are encrypted that's why we brought in the B crypt.js and we love to store the complex things the way how it works is in your API call if somebody makes a call to your let's just say user slash verify so you simply generate this verify token and this verify token is going to be long gibberish string something like this this is how it usually goes so this is let's just say a long gibberish thing now this is generated by API now there are two portions of it now this only alone is not generated this thing is actually one portion of it is updated into the user's database now our this model has something inside us right now it is empty but as soon as somebody hits that API call that long generated string is actually copied and is saved into database of that users now one portion of this is actually sent to the user as well all right now API doesn't keep anything it's just a business logic it doesn't have the capability to save anything it just simply goes ahead and sent one copy to the database one copy to the user now what next now what next is once somebody actually verifies that this token actually comes back to you now how it comes back that's we'll study in this lecture but this might come up into a URL you can extract it from a URL we know how to do it it might come up into a request body as well that's okay we can also handle that part but the whole idea is this token actually comes back to you now once this token comes back to you in the database we have to find that where this token is just like we can find a user based on email just like we can find a user based on ID we can also find the user based on this token yep we can do that now once that particular user is actually being found and let's just say you have found this and there is this user now this user information comes to your API based on this token now once this is actually being done you actually invoke the API Logics and simply go ahead and certain Fields into it for example we are talking about verify you go ahead and update verify as true so now this is a verified user so this is how the basic logic of how verification works somebody clicked on it you know the request is coming up from that token now apart from this you might have noticed that I also keep the verify expiry as well because I want to give the user only a certain time duration when this verification can happen I don't want it the verification that I send an email today it happens 30 days after that so I'll definitely don't want that that's why I keep that expiration I always bring back the user only basis on that the token should match and the time should be certain limit in under certain limits I'll walk you through with that as well so this is the base case of it now with a similar way your forgot password token also work I'll walk you through with that scenario as well because I can understand this can be complex so I'll again reiterate that part it will be a revision as well so I'll just go ahead and remove this this this and we'll just get back to this one all right so what happens in this forgot password token we can now remove this part okay so we have a forgot password token again what is the forgot password token nothing it just encrypted a long string a hashed value that's it so this hasht value looks something like this this can be something like this with few numbers really long strings something like that and what's the job of the API is to send the copies simply it takes one copy send it to the database I'm going out there we go and this one copy is sent to the user browser it doesn't keep anything for itself it just removes it API cannot hold it so now user had this has this token of forgot password and the DB also has this token on the forgot password again this is sent to the user or the browser or you can say to the email that is also a good word to have here so now this is being sent to the email now what next obviously we have to search it so now this token will come to you from the user side so user will hit a route maybe forgot password whatever the route is it will give you that a particular long token again I repeat this token might come up into the URL in the request body it doesn't really matter in this case we are talking about this forgot password so obviously with forgot password I need this token and I also need what is the password that you want to update so that I can add this into my field with my logic so that is there the logic is same for verify and the forgot password now what I have to do next I have to take this long string and I have to search it here in the database just like I can search for email I can also search with the token and this will return you an user entire user who is having this token when this user actually comes to the API the API is perfectly capable after matching the token and the expiry that hey the token is valid the expiry is also valid then it simply go ahead and update one field so I can simply go ahead and say hey update user dot password that gets a new value whatever the new encrypted value user has given you a value you encrypt that and you update that so you simply go ahead and simply say updated password password if I can write that updated password so that that is all you have to do that's it you have updated your password so this is behind the scene logic of how the verify password Works how the forgot password work or any other token based mechanism that you are used to this is how all of them works quite a lot of theory isn't it uh yeah but I hope that you are enjoying this I hope that I'm able to explain this so much Basics to you and you are enjoying that all right so now that my models are all done now it's time to open another file my models are there my database connection is there notice here the database connection I can just call this connect and connect to any time with the database now what's interesting is go into the app and inside the API we have users and inside that we have the sign up and we have this route now this route is actually empty right now in this case but you might be wondering can I create only just one file in the sign up yep there is no other file you can create and this might be bringing to your question another question so I'll bring this up a lot of notes Here that I also handle a lot of things so for example if it is slash API slash users slash sign up if this is the case then I have a lot of things that I handle here for example uh on the same route how do I handle the get request or the post request or the put request or the delete request so how do I handle all of these cases now there is a nice way of how you handle this the standardization of the apis I'll not talk about too much of the standardization of API that again requires a separate course in itself but the ideal is that you handle all these things via the request method a lot of time when we actually teach the tutorial it's okay then we go ahead and simply ask them to Simply create routes with a different controllers like for example create user or maybe something like we asked to create update user but the whole idea is this is not a standardization approach it's okay for tutorial part there is no harm in that but if I go ahead and say simply user then if it is a get request I should be getting a user if it is a post request I should be adding a user if it is a request I should be updating a user delete request then I should be deleting a user so this is a standardized approach and this exactly is being followed in the next JS as well a lot of behind the scene details so all we got to do is simply write the functions for the Post method get method and all of that now the syntax is a little bit you have to first get it and understand it once you get one syntax all of them are exactly same so first we're going to go ahead and simply bring the connect that's the most important thing so connect and the first time you'll be seeing the default import statement so yeah this is the first time you'll be seeing it from if I can write that from and this will be coming up notice here you can write at the rate yep that's your root directory and then you can simply go ahead and say Hey I want to go where should I go what's the name dbconfig okay DB config and inside the DB config there is this DB config file okay this is dbconfig.js I guess let me just check this uh dbconfig.ts although you don't need to import the TS but sometimes I have seen that there are some issues in bug because I didn't mention a DOT TS a very rare very rare sometimes it even gives you problems but it has happened to me a couple of times okay the first thing that you have to do is simply go ahead and connect that's it that is it don't need to do anything no then catch it just needs to connect but we need couple of more things as well the first obvious thing is user we need model so that we can add things into the database and that will be coming up import user and that will be coming up from at the rate app models and users make sure you double check this because I had noticed this this actually creates a lot of problem just now you have seen because our model is not coming up from App model user our model is sitting somewhere else and that's totally allowed you can keep it here as well there's no problem in the app models and user that is also one way but we're keeping it all totally outside so in the models and then we are getting in notice here this is still going to give you a problem the reason for that is you need to give the file name so inside the model we are calling it as user model so make sure you are cautious about that user model that should be happy okay now the next thing is you need to grab request and response so in case you have worked with Express or anything of a backend you notice everything actually is dependent on request and the response you need to take something send something in the next JS you actually work with it little bit different we go ahead and First grab next request yeah come on suggest me here there we go next request and we also get next response so these are the two things which actually helps you to do all of this they all comes from the next server just like this we'll be encrypting some of the passwords so let's go ahead and import decrypt Js and that's coming up from B crypt.js and what else I guess that's it uh this one we don't need JWT because we are just talking about sign up so that's not required as declared but never used we'll use that no problem there all right so now this connection and everything is done so I'll just keep it there outside so all the connection everything is done now the way how you define a syntax of handling a post request because data is coming to us so we'll first say export and then we'll be using a sync because obviously talking to database database is another continent it takes time and then simply write the function and then what request you want to handle is it a post request is it a get request is it a delete request so whatever that is you just handle that in my case post makes sense so I'll just use that then you simply go ahead and say that hey I will be handling a request you can handle both request and response but there is no need of handling everything here in the first parameter you can just say I'll handle the request and then say hey I'll get the next request just like this and there we go that's it that is how you handle and if you want more things to be handled just create another function which is post which is get you get the idea you get the idea now in here the simplest part is to handle the try catch via the try catch so I'll just go ahead and have the try catch and the error is going to be of type error type any by the way not ideal case of handling everything with any now how we're going to return a response that's also super easy you simply go ahead and say next response and we will not be handling the errors like this although you can there is no hard and fast rule but I prefer to send a Json response with the error message and status code I think that's that's a better approach so that's the first part of it how we'll be handling now the next question is how we're going to grab data from the body in case you have worked with Express or something request.body was our friend which actually does that it is almost similar to that but in here you actually have to await a little bit so await a request it's not body.json don't go with these suggestions it's Json just like this and we can hold this into a variable let's call this one as request body just like this and a lot of example you will see calling it as request.body I also picked it up from the dark so yeah all right notice here it's request.json just like how it works now further down this you can actually extract all the variables that are coming in so we'll be doing a little bit of the destructuring so from request body we need to extract some stuff and what we'll be extracting is const let's grab some stuff from request.body I know that from front-end side I'll be getting a user name I'll also get an email and I also get a password because this is the first time I'm registering a user now again it makes sense that you first go ahead and do all the kinds of check if email is not there if username is not there if password is not there then go ahead and throw this response although we have handled a lot of these error cases required and all of that in the Mongoose itself so in the error response they'll be getting a good message and all thanks to the custom messages that we have written here so it is handled a lot but not entirely so I highly recommend you do on your own validation I'll just move on to the basic validation but before that I'll also do a console log of uh entire request body so that we can see that what is happening not ideal for the production grade so remove these console logs but I'll just keep it to check things now I'll go ahead and first check check if user already exists very simple basic check all I have to do is use the superpower of this user remember this user is coming up from the Mongoose so this has a lot of superpower and can find a lot of things for us so for example it will say find one and what do I want to find I want to find an email so I'll just go ahead and say email and that's it I want to find most important thing is this will return you a query if you don't put up in a weight so this is a common mistake that a lot of people are doing these days posting them on every single platform so put up in a weight because it's a database call and we'll just say simply user now if this returns me something that means user already exists so all I have to do is if user is there then simply go ahead and suggestions please no suggestions we're going to go ahead and simply say return next response come on now suggestion there we go Json that user already exists so this is nice and easy so there we go again you can make more checks onto this one I'll not do more I'll just go ahead and hash the password now hash password again this is what the basics will be doing so we'll be first creating a salt which is the basic and after the salt we need to create a hashed password just like this feel free to use any number of rounds that you want to have so the B crypt.js library is responsible for creating the salt and if you'll read the documentation you'll find it exactly same the Gen salt will generate a salt with the 10 rounds and again different Frameworks and libraries use different rounds for example Ruby on Rails use 12 rounds nexius and react not react Express and Mongoose mostly use 10 so again it's totally up to you a hashed password we are hashing password we have to provide two parameter to bcrip.j Hash the first is the password which we are grabbing from the request body and then the salt value so absolutely simple there is nothing too much Panic about it now we want to save a user in the database so we have to create a user accordingly so all we're going to do is create a new user just like this this will have a username this will have an email and this will have a password but not the password that we're getting from request body but the password that we have encrypted the hashed password so we'll be going like this so we'll be saying hey let's just go ahead and go like that all right now we'll be storing this into a variable first so let's just call this one as const new user because it's actually our user to be saved new user whatever you like now this is nice and easy now all we have to do is save this to the database you can do it in one line as well but I prefer to have more uh explainable approach of this thing so I'll just go ahead and say await new user dot save that's it it's going to save let's store the response into a variable maybe you want to save it have a look on it so I'll just say save the user again this is a little bit of a verbose approach but you can do this All by shortcut as well but it's a tutorial I need to explain the things so I'm just keeping it a little bit more verbose now after this maybe you want to do a console log of the saved user that's totally up to you I just keep it so that I can show you more things and that's it now apart from this all we have to do is simply return a response maybe in the response I'll just go ahead and hit and enter here and one more okay okay let's just go ahead command Z because I think that is messing it up a little bit yep it's messing it up I'll just remove it like this and there we go so I'll say message is created user successfully then we'll get no not like that success is true and maybe I want to throw in the saved user totally up to you how you want to deal it with this I just want to go like this all right so this is my Approach of saving the user and as you saw that it's not really that difficult now we understand how this is going to be all taken here in the database and absolutely but one thing that is still missing is we are not able to send any data to the page we have to actually work on this page as well because it's right now not going to be doing anything at all so let's go ahead and take care of this so right now this is the basic page that we designed a moment ago now a couple of variables that needs to come once the user will be signed up I need to push it to the login page for this I will be using a router so notice here this use router now it will come in handy so I'll say const router use router I'll use that in a minute I've already created my state so that I can actually go ahead and use it but I'll be creating couple of more states which will be helpful okay but again you can optimize this a lot more and a whole lot of things can go on so I'll just go ahead and create one more which will be button disabled so there we go I'll keep it by default as false button will not be disabled I'll not do much here I'll just change the name of the button on our front end so if you remember on the localhost we have the sign up uh my hopefully my server is not running I guess yeah it's not running I just push the code on the git that's it so by default it will be saying just sign up so I'll be changing the text only based on whether the button is disabled or not so I'll not do too much but you can go all fancy with it so that's all the basics we'll be doing all right now coming up onto the part that how the things are going to work now this button state is all just a fun that we are doing to understand a little bit more about the react use States and all of that now this button will be changed on like usually what how you want to utilize this button disabled so this will add some classes on the button so nobody is able to press it but as soon as the button disabled is gone that means somebody can press it one ideal case is when there is some values in our field so one case one a hook that you can use for this is use effect so what is going to happen in the use effect if there is a user uh I'll just first enter end it so there we go it is dependent on this user so this is a dependency array that how should I how how often should I run this use effect and I'm able to do all of this because I have actually enabled use client and I'm doing this just to show you that I can do it so this is all dependent on this user as soon as something change in that that will run this use effect or whatever the code you write inside this use effect callback so I'll just go ahead and write the very basic of it so I'll just go ahead and say if user dot email so there are a lot of fields into it email email and I'll just check the length of it if the length is greater than zero and wow suggestions I love that then I'll check the user.password length is greater than 0 and the username length is greater than zero then I'll set the button as disabled as false because if the length is greater than 0 the set button should be default to false let me just check that quickly all right and in other cases it should be enabled yeah because it is set button disabled if it is true the button is disabled ah get it sometimes you need to evaluate yourself as well all right so set button disable to true in other cases all right so there we go we can run this and again this use effect is not available so I need to go to react and say hey we will be bringing use effect and there we go now we can do it and based on this we can check out some fun stuff here as well so I'll just go ahead and change up the text here sign up here and I'll just cut this out and inject my variables and based on button disabled I'll check that if there is a button disabled then I'm gonna go ahead and do something otherwise I'll do something else so if disable button is true that means button is disabled so I'll just say no sign up and if the button disabled is false that means button is enabled that means this time I can do sign up so there we go just really basic so we can go ahead and save this let's try to run that server it's been a while so npm oops npm run Dev and let's see how many crashes we are going to see always expecting the crashes all right looks good decent all right so yeah take some time okay so we'll do a sign up and there we go so it says no sign up all right that's good because right now there is no value so if I go ahead and say a oh man the reason why you are not able to see it is because there's a text color so in all of this come on I have to do this for all of them yeah okay no no other option we'll just go ahead and say text Dash black there we go we have to do this for everyone text Dash black one more one more not that much of a big problem text Dash black there we go so as soon as I save this there we go now I can see a and no sign up still then I go ahead and a and then I go ahead and a and it changes to sign up now I can sign up definitely I'm not checking much of these fields neither on the backhand side or front-end side that what should be the minimum length of password we can do a lot of validation but this video is little bit beyond the validations all right so this is the basic that we have gone through with it now let's learn that how we can actually utilize the sign up method because we haven't talked about it we have this extrus giving us the red squiggly line but we haven't worked on that all right the basic and the most easiest way is first have the try catch handle the catch part and that's the basic sometimes people actually get this uh on loading as well maybe you want to show some loading let's go ahead and do this loading as well let's go ahead and have a loading text as well so const and we'll have a loading set loading by default it's false So based on this we can actually render some variable as well uh maybe in place of sign up we'll just go ahead and cut this out inject a variable again and we'll just check for loading if loading is true we'll if loading is true we'll do something otherwise we'll do something so we can just go ahead and say sign up and in this we can say processing you can have better Spinners and loaders but my goal is not to have you parked down with 1000 different libraries but to show you more about next year's we can see this is processing right now because loading is true somehow uh loading all right why this is loading okay let's check if loading is true oh my bad if loading is true this should be processing processing and if it is not true that means loading is not happening that means user can sign up all right so at least this also gives us a check that you can flip the switch all right good good enough good enough so let's go back here in the try catch and let's also add a finally here you rarely see the implementation of finally but in this case finally makes sense because no matter what happens loading needs to go away this is the common syntax now as soon as you go first let's handle the catch part because it's easy and in case you remember I actually asked you to do something we'll actually handle that part as well so if you remember I asked you to have this react hot toast this is your assignment you have to take care of how this Library actually works so the way how it works is you simply go ahead and say toast and then error and you can just give it error message that's how the basically it works now in here it says hey I know I have no guarantee that error will have a message so I'll just go ahead and write in any here so that it gets away the errors but also I love to get a console log because I know I have I have not perfectly implemented react hot toast it's assignment for you but just for the sake of so in this case we'll just go ahead and say sign up failed and we'll also get the error Dot message in the logs now this log message will be available to you on the user side in the browser because it's a use client all the console log messages in the API will be available in the bottom section the terminal because it's on the server side that's one difference as well now let's come back on to the tripod what do you want to try first and foremost what I want to try is set the loading that's the basic set loading as true all right now I want to make a request so I'll just use xeos and I want to make a post request from the xeos now make sure you provide this URL very carefully you don't need to provide the entire URL the next JS is already configured for hitting your own route so slash API slash users the folder you have defined let's check it one more time API slash users so there's an S and then you can simply go ahead and hit a sign up route so I'll just go ahead and hit the sign up now I'm also taking along with me all the data which is user which is stored in here so I'm just taking all of this and obviously once this is being done this will take some time so I'll just go ahead and await for this one and I'll hold the response in some variables so I'll just go ahead and say response the punch response there we go all right so this looks okay now I also want to see that what kind of response is coming up so it would be properly better for me if I go ahead and say sign up success and I just go ahead and say response.data I should be getting a response.data.message as well but let's just say I want to get a response data only and then the most important thing is I need to push the user onto a new page and that is exactly why I have this router sitting behind sitting idle doing nothing so I'll just go ahead and say hey router just go ahead and push the user to slash login make sense all right so that is it that is it if we haven't mistake done any typo attempted import error xeost did we made any mistake typos and why is it having an issue because it shouldn't be like that there we go now it should be happy why did it added these extra curly braces no idea about that all right so this should be all let's hit a refresh just for the sake of self-satisfaction I'll just go ahead and add a username with the name of one email will be one at the rate gmail.com and the password will be one two three four five six and let's try a sign up processing working nice we have been redirected that is also nice let's go ahead and check out in the database in the database and oops uh so let me go ahead give me a second I'll just go ahead and sign in again probably just redirected me I need to actually use my email so I'll just keep you up here till the meantime you can just hang out with me chit chat with me no worries it will just take a seconds I'm just logging it into my detail I don't want to expose that email so that is the only reason I'm just having this ah didn't bother it much so let's go back up here and going back all right so this is where we are and we'll just go into the database and there we go we can browse the collection what did we name this project and there we go this one we named it as test all right we should be naming it better but anyways this is also going to work so we can see we have one one at the rate gmail.com is it visible yep little bit is verified as false is admin is false the rest of the fields since they don't have any value they are not being displayed here let's try with one more user so I want to go with the sign up page let's sign up to as well two this will be 2 2 2 at the rate gmail.com at least we need two users one two three four five six nice very secure password sign up this time it's quick because obviously first time it takes time and you get the idea it is always like that let's hit a refresh and it should be getting us two users hopefully there we go so we can see that it is not that much difficult to actually get the data into the database let me go on to code base there we go and we can see that some of the users that we are getting these users are actually on the backend side so we are getting that but not only that we must be getting some of the users in response on the console as well there we go we can see sign up success which gives us an object and this object has a message which is coming up our own message from the backend user created successfully then we said saved user is getting us that's nice and then we have success true they can be in any order so it doesn't really matter so there we go it's working nice and we can also see the difference between the messages that are coming up some are being read on the backend side some are on the front-end side if it is a console log in the use client obviously it will be in the browser otherwise if it is in the API route usually that will be on the back end part of it or the back end side of it so this is how we can actually go ahead and and create a simple uh sign up you can say uh now the next thing that I want to do is uh similarly take down the route for the login as well the login is almost similar you'll find so much of similarity there but I'll still do it in front of you so that you get more idea I will grab all of this because yeah we'll be a little bit uh lazy you can say there's no good word of putting it all right so I'll just paste it so we have all the things make sure use client is the most important thing again this is all happening in the route not in the front end part we are still in the route of login so the first thing we have to do is connect with the database every single time we have to connect I have spent a little bit good amount of time in debugging when all I was doing is missing disconnect all right so connect who said to bring it to you from HTTP 2. I am bringing this from ah why oh my bad we actually brought this in from the wrong place my bad my bad we should be bringing in from the sign up this is where the real stuff is so copy this and paste it there we go okay so now notice here this is the B Crypt this saying uh cannot find a declaration file for module the whole idea this is saying is I don't know the types about it so all you can do is click on this bulb and say install the types about the big crypt.js once you do this it actually install additional types for you and get rid of the error no need to worry about that part in case this red squiggly line is bothering you too much get with that or fix your linting okay uh this is good all right so now we can go ahead and connect there we go connect in with the database again this is my login route so async export a sync function uh post is good request header looks great suggestions love them it increases my speed of explaining and writing the things so much okay all right the basic starts again so there is a try catch the catch is any and in here we can just go ahead and send any response that you want we want to Simply return a next response so return suggestions no suggestions requestresponse dot Json error message status 500 happy with that done with the catch part now coming up on to the tripart most of this is going to be very similar what we have seen But there are some changes not too much first is how we can get data from the request so it's really same request dot Json this will be giving you all the data so how we can grab this we can grab request body from it and we'll be destructuring some values so let's go ahead and restructure email and password from request.body uh basic so there we go why are you bothered again all these structure elements are unused oh come on let me type first too much aggressive let's go ahead and do a console log and we'll be saying request.body that's fine okay to give us just the detail that whether it is working or not now obviously when we are logging uh into this one so we have to check whether the user exists or not so check if user exists or not otherwise we'll throw him in some error so we'll be saying that hey how can I do it again the user which has all the superpower I can go ahead and say find one and this is bad find one and I want to find it based on the email that's it that is all I want to do if I found it I'll just go ahead and store that into a user variable but since this is a database call make sure that is awaited all right looks nice and if I don't find any user then I'll just request send a response that user doesn't exist so much time is being saved all right but don't rely totally on suggestion they are horribly wrong sometimes all right so what I want to do next this is a login so I've checked the user now I want to check the password all right so I'll just go up here why are you bothered I have used the email just here email does not exist on Typecast it exists I know the email is coming up and I think we need to handle an await yep my bad almost missed that okay sometimes the linting is good okay now we want to check if the password is correct that is super easy we can simply go ahead and validate the password based on the B crypt.js it has a method which says dot compare and we can compare the password which is coming up from the request.body and if you remember this user is coming up from the database this is also bringing the password there is a field in the model user dot password so I don't have to do any magical thing bcrip.js can compare it it knows the stuff how much the default values and everything so it will handle the stuff I don't have to worry about that now if the password is not valid I have to send a response that hey you have an invalid password I won't be doing that now in case that is all done now let's prepare the data because the way how it works is it's actually really really simple if you have never done this kind of a thing it's actually super easy to work on with now once everything is verified that your user exists your password is correct then we actually create a token this token is created by uh simply Json web token we encrypt that obviously it's not just a plain token and we send this token into users cookies not in the user local storage because you can manipulate the token there but we can send the secure cookie to the user and then later on whenever we wish we can access those cookies as well so it helps as a Bridger to verify whenever the user we want to verify it just has the ID of the user but it can have a lot of payload into that you can send a user ID email admin type whatever you wish you can send all this data as a payload to that that's exactly what we'll be doing next all right so moving up here first of all what we're going to do is create this token data so I'll just go ahead and say create token data now how we are going to do this is we'll be first having this ID and one more important thing whenever you look into this notice this uh every single time a user is created it's with underscore ID that's what the ID is there so this is what exactly I'm bringing in although every single detail you can bring in from with this ID again you just have to type in this uh find one that's it based on ID you can find anything but it is no harm that if you want to send extra things like user dot a username or maybe you want to send his email I'll just send this much but you can definitely send a lot more than this now once you have done this then obviously it's time to Simply go ahead and create the token and send this token as well so first and foremost let's this is token data only we haven't created the token now we are going to go ahead and create the token the token this is how it is created uh all we have to do again notice here there's a problem why because suggestions don't always rely on them you have to actually import this so I have to say import JWT and that's going to come up from Json web token again could not find the Declaration so I'll just click here where's the bulb here it is and install all the types don't want to see the Reds quickly lines okay so all it does is obviously uh the process.env JWT secret key that's not my key my data is actually stored I have actually created a sample file for you so that I don't have to Peak it again and again where it is somewhere here uh sample.env uh so hitesh subscribe yep you should do that my token secret is here so I'll just copy this go back here this is not my this is how it works but still it will give you some of the issues that hey what is this and all of that I'm 100 sure that this is coming in so I'll just put an exclamation That hey I know this is coming in so all you have to do is this takes some time to create the token so make sure there is an await here JWT has a method of DOT sign to create signed token it takes the token data this is all the data that we have you can directly inject a object here there is no problem and then process.env.token dot secret how long you want it to stay there expire in one hour I'll not do one hour I'll stay for one day at least totally up to you how you want to do that now all we have to do is token is created but this token is not yet set into the user's cookie the way how we do it first there are a couple of steps involved is we have to create a next response so we'll be just going ahead and say hey we want to have a response we are not sending this response yet we are just creating it and the way how we create it is simply uh next response and it will be dot Json there we go I have an object like this there we go and in here we'll say messages login successful that's a nice message and success true I think that is enough but now the great advantage of this is if you have this response this response right now is a type of next response which can actually go ahead and access your cookies not your the user's cookie so I'll just go ahead and say hey response did I mistyped it no response response response come on too many suggestions response dot cookies there is a s here don't go with the suggestion bad suggestion here response dot cookies and you can set the cookie similarly you can also get the cookies so I'll just use a set here and for this I'll be using token token HTTP only yeah that's that's fine I would love to have it on to a separate line I think that will make sense for me at least there we go we don't need to set even the path that is obviously cookies yeah Escape that escape that don't need that all right so this is what we have now we have response dot cookies being set now this response has already sent the cookies and everything now you can return the response back return response now as you'll be returning the response it will be doing all the things it will be sending the message it will be handling the cookies all the things are being done so that is how it is being done ah quite a lot quite a lot but I think that's good now just like we did here uh we need to now go into the login page .tsx yep we haven't actually worked a little bit onto this page so uh now we need to do exactly all the same kind of thing that we did in the past yeah Basics just like that all right so we'll start this time we'll do it a little faster because I think we have studied a lot all right so first thing uh router because we'll be pushing it to some different page so const router use router there we go first thing done we have got the state we'll be getting the button disabled and the loading as well so we can copy this all suggestions I love that don't need to even copy paste that loading there we go okay all right this is all done very quickly on login okay how do we want to handle the login part first what we want to do is exactly same use effect hook we want to actually use that and since this is a use client or the client side or the client component we can actually do this so use effect and I'll just close it first and then the user it's dependent on the user and it's not available so react please give me use effect there we go and in here we'll be using the exact same logic so let's just go ahead and use it like this if user dot email now it's suggesting me nicely there we go and we can also have an else part and we can have set button disabled to true button disabled is true that means button is disabled okay that's correct and sometimes confused in that so yeah re-evaluating yourself is not a bad idea okay although it is giving me the entire bunch of code but I'll prefer to write it so try catch catch error would be any and all I have to do is simple assignment for you but first I'll do a console log so that I also know that what is happening so console.log login failed error.message that's nice but we'll also do the toast so that you can verify the toast messages and stuff right now the toasting is not working I have not properly Incorporated it but hey and we'll also go with the finally how can we forget that finally set loading uh bad there we go es like this and suggestion no suggestion there we go okay so we have finally this set loading as false that's nice okay Meat part the how we're going to handle this request super simple first start your loading there we go and keep it as true so that we know something is happening then we have to use a weight because it might take some time and then we have xeos axios will make a post request here so super simple where it is going to make a post request slash API slash users slash login that's the route it will also take the users with them so that is nice and easy and there we go and looks like there's an extra yep there we go we also want to store that response so we'll be saying const response and again you can dump down this response into console log you can post up a toast message whatever you like I'll do a console log because this is important and we should be seeing this data as of now learning phase learning phase and then obviously we can hope first before we do router push this is great suggestion by the way but we'll be doing a toast dot Success login success you can Implement that just a few lines of code and then we're going to go ahead and router dot push we don't want to push it we will be pushing it on to slash profile Maybe yeah do we have profile pages did I taught you that uh yep I I taught you that yeah profile page so we'll be free directive into profile all right so let's see if this actually works in action or how many errors we are going to get okay okay xcos is not exported this is again xcos problem there we go save this hopefully things are okay expect errors that's the only advice I can give okay now we are on to the login page just to refresh can I go into sign up yep visit login yeah working nice so the email is one my bad email also needs to go ahead and work with this nobody is able to see this because of my bad CSS text Dash black and the password is also going to have a text Dash black should be okay now also let's since we are here let's also change the thing so login will be based on not like this we'll be having a loading so if loading is true that means processing otherwise we are doing what we are login okay and button disabled I'll not do this you can do this all right so I'll just go ahead and say one at the rate gmail.com and we'll be having one two three four five six the securest password ever let's try login and no I don't want to save it did we call it even there we go on click login on click login so all right so this should be working do we have any data okay so we are receiving the data till here that is nice but it's not getting redirected okay we should be getting a redirection login don't want to save this let's check out and let's see what are the mistakes that we're doing console log okay the server is okay so we are getting a lot of Errors probably we should be going back onto the code file there is a lot of okay uh we need to check out what is going on wrong API slash user slash login that seems to be correct and since we are receiving the data on the backend side that means at least this one two three four five six one at the red gmail.com do we have one at the rate gmail.com and the passwords are coming in okay at least we are getting this on the backend side so now the problem is technically on the backend side so two times we have requested the body and we were able to encrypt that and we were able to actually get this saved user as well okay oh I'm checking on to the sign up route I should be checking into the login route I should be in the login route did I made a mistake okay so here is this this is coming up from here so we are getting this request.body and now we are getting this so we should be actually checking this token data we are getting the user no user here we are getting the user again this debugging will take some time so this is the real world development that's how it happens and let's see if the user is actually getting some token so let's see in the application and here in the localhost we don't get any token all right so this is going to take a little while to debug so let me go ahead and quickly debug this and will tell you what is actually happening here Welcome to the Real World development this is how it happens and Yes actually I found the bug it was nothing I just forgot to save the file there was a big white dot I couldn't see it and that actually turned out and notice here I didn't change anything I was just logging out a few things to check out whether user exists or not not even a single line changed but yes I made a couple of requests then I realized I need to actually restart the server that is all that is all I did and nothing changed and it works nicely now I'll I don't have a log out route yet we'll do that soon but this is how we have I can go into my application now just after restarting I can see there is a token being included up here and I'm also getting redirected to profile but there is a problem there's a lot of problem here I can still go back to my login route this shouldn't be happening and I can directly access these profile which shouldn't be happening if I'm not logged out so there is no controlling mechanism right now also there is no logout mechanism right now now I'll obviously push this code so let's do it right now in fact so I'll just go ahead and push all of this yep all of this and we'll say sign up and login complete good I'll just complete this commit this and obviously I'll push it why don't you use command line I don't it's just easier it's fun so I'm just going with that so what we have done right now and what position we are that's the most important to evaluate right now so let's just go ahead and quickly evaluate this so we are at a position now our front end is working our back end is working we are able to register a user in the database we have tried that couple of times it works and we are also able to log in a user there was a small hiccup where I paused for a minute but again it was nothing more I just had to save and restart the server so once I restarted it worked absolutely fine also I'm pushing the code in the GitHub as well so that you can also see and check out what is happening how is it happening and all of that now there are a couple of challenges in front of us first of all there is no logout button so we need to design that we also don't have any kind of a mechanism to stop the user from visiting the profile if they are not authenticated and if they are authenticated they have the token we have no way to stop them and protect the routes that the logged in user should not be seeing the sign up and the login page he should be seeing just the profile in all of these pages so we need to find a way and of course I'm talking about middleware so we'll be talking about Dem so this is all what we will be doing in the upcoming videos I hope you are enjoying them I'll take a small pause it's already like four o'clock in the night or in the morning so I'll record the rest of the videos tomorrow so just stay tuned hit that subscribe I would be super super helpful if you drop me a tag note on Twitter or LinkedIn there's so much effort that is going on in that so in case you wish you can do that otherwise it's totally fine let's catch up in the next video or after a break and finish up our middleware and remaining of the part let's see you in the other side of the video or the next video whatever that is
Info
Channel: Hitesh Choudhary
Views: 12,409
Rating: undefined out of 5
Keywords: Programming, python, javascript, devops, cloud
Id: 2RxaJrltJKo
Channel Id: undefined
Length: 61min 37sec (3697 seconds)
Published: Fri Jun 30 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.