Next-Auth Forget | Reset Password in Next.js 14 with MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome back to another video on nextjs and I'm going to be covering up very important topic in this video called forget password and reset password functionality so even if you are using the version 13 of nextjs version 14 or any new version coming up in the future that uses app directory you can follow this video so I would say this is the second part of one of my previous video in the first video I have already covered the login user functionality registering new user functionality login with GitHub functionality and building these forms navigating from login page to the register page and from register page to the login page and also most importantly I'm managing the storage of user data if it is registered or if it is login with the GitHub I'm storing the user data in the mongodb database so in case if you want to have some relationship with other data of your user you can have the user data stored in the database and also I have already explained in the first video that using the authorization authentication feature that we have implemented how we can protect our routes and this is the dashboard route which I have actually protected because I'm not logged in currently that's why I'm not able to navigate to the dashboard route this is what I've already explained let me show you my playlist of nextjs 13 and nextjs 14 and also show you the first version of this video so this is my channel if I go to you can go to the nextjs 14 tutorial playlist as well and if I go to the playlist nextjs 13 tutorial you can see that I have created a lot of videos Almost 37 videos if you are using the version uh of nextjs that uses app directory you can still follow this playlist and it covers pretty much every topic for you to become a good nextjs developer using the app directory structure you can see that the best practices of use use hooks uh connecting with the mongodb theming server actions Redux toolkit context API handling with the CMS like the sanity or the gust CMS debugging building apps different ways to protect routes typ script in next js14 this is the first video which I'm talking about next o login register in next js14 with mongodb login with credentials and the GitHub this is what you need to watch if you have already seen that or if you already know how to handle login registration feature and storing the data in the mongodb you can start keep watching the second part of this video but I would recommend you uh to watch the first part first uh if you have not understanding uh don't have understanding of the login registration process mainly with the next o library and you can see that I've already created videos on the e-commerce website building with nexj 14 blog application development SEO how to upgrade from veran 13 to 14 with couple of commands Okay and um I'm going to be showing you how I will be upgrading my project from 13 to 14 just now and if you want to learn how to process the authorization authentication in NEX js14 using clerk package I've already created its video and this one video contains login sign up and forget password functionality in single video using the clerk package you can watch this video and you can see that I'm putting a lot of effort creating these videos for you guys so it's just a request it will really encourage me to make more videos for you guys if you subscribe my Channel right now and like this video so let me give you an overview of the forget password and the reset password functionality first of all I need to create a new user and register it so that it can be stored in the database but first of all Let Me Show You So currently it shows the forget password uh reset password here so here I can enter an email ID and uh let me see what happens because this email ID is not yet registered in the database so if I click on submit it will show me that user with this email ID is not registered so you can see that it is fully validated and all the edge cases are handled in this video so now first of all I'm going to go to the register page and register my user in the database so I'm going to be writing uh AB CD 1 2 3 4 so I'll be clicking on the register so this user have been registered in the database let me go over there and click on the refresh and see if the user is added in the database yes it's added and you can see that the password is completely encrypted for the security purpose as well all right so let's go over here now I want to first of all let me login here so I'm going to click on the login page and let me change the password AB b c d 1 2 3 4 and I'll be clicking on the sign in now you can see that I'm logged in with the same credentials using which I have actually registered a new user and now I'm able to navigate to the dashboard route because I'm registered and this is the email ID which is being fetched from the database for the logged in user and uh I can navigate to the dashboard page now let's go to the log out uh link and I'm going to click on the login and now I'm going to show you how I have implemented the forget and reset password functionality let's click on the reset password here now I'm going to enter the email ID which is registered in the database and oh so let me add it again so this is where so let me click on the submit now let's see what happens so it should navigate to the login page yes it has navigated to the login page we we can actually add some kind of toast as well but that is something you guys know that how we can do it but I've already received an email ID with a link so let me copy the link from my email ID which I have received so I've copied the URL from my email ID which I have generated myself from the code and this is the URL Local Host colum 3000 SL reset password SL token okay but first of all let's go to the database let's refresh and here you will see that it will contain the reset token and reset expiry date as well this is for the security purpose and you can see that the complete functionality is working fine let me zoom in you can see reset token and when I will be resetting it the uh the password this is actually to handle if the user token which is added over here is actually valid or not or whether it is already expired or not not okay so now I'm going to be hitting this URL let's hit that and it will take me to the reset password route now okay so here I will be entering a new password here so let me add a new password so I'll be adding a b c d 1 2 3 4 5 6 okay so now let's click on the reset password now the password is reset let's go to the database and refresh this page and see what happens over here and now you can see that the reset token and expiry date have been removed because it's not in the process for this particular user okay so now I can actually login First of all let's log in with the previous password you can see that it contains eight letters means it is containing the old password let's click on the signin and invalid email or password because this email and this password actually is not correct so I'm going to be adding the 456 at the end so let's click on the sign in and now you can see that if I go over here you can see that I'm able to log in with the new password so this is the functionality which I'll be implementing using next o package in next gs14 verion using the app directory all right so let's get started from the code base of the previous video in which I implemented the login and register functionality so I will be implementing forget reset password functionality from scratch you can see that there are no components no files for forget reset set passwords no API routes for anything so I'll be implementing everything including the UI from scratch in this video so this is the code base of the previous video and I used the verion 13.5 for this video there is no difference the folder structure the app directory structure how we create apis how we create routes are pretty much same okay so I'm quickly going to show you that how we can update the verion 13 to 14 with couple of commands Okay so in the terminal first of all you need to update your node and npm varion which is the 20 in my system so I have actually checked 10 of npm verion so now uh first of all you need to run this command npmi next at latest react at latest react Dom at latest es lint config next at latest so it will update these packages from Varian 13 to 14 and also you need to update the typescript variant as well if you are using typescript but you don't need these couple of packages for if you are using the JavaScript so I am updating the ad types SL react at latest add types SL react Dom at latest okay so these two packages are updated as well if I go to the package.json you can see that the next verion have been updated to the version 14 so our project belongs to the next year version 14 okay so first of all I'm going to be creating a new route for the forget password so I'm going to right click the app Direct Tre click on the new folder and uh I will be creating forget pyph password okay so let's create a page file inside it so I'm going to be creating page. TSX okay first let me run the project so that I can keep on looking the changes which I'm making in terms of the UI so it's running on Local Host 3000 let's go ahead and refresh so here currently I will be navigating to forget password route that what it contains it will throw an error so what I'm going to do is I'm going to copy paste the code from the login component inside the forget password component to copy some kind of UI okay so most of these things I will be needing over here in this file as well it is a use client component because I'll be using the click handlers so I'll be needing these things here as well and I'll be needing this use effect I'll just going to show you that why we need it uh we need to protect over route um and we need to use the use session hook uh to authenticate over forget password so if user is logged in then we should not allow user to navigate to the forget password route it should only be navigated to forget password route if user is not logged in okay I will be needing this valid email regular expression as well I don't need the password I only need the email from the form I'll be removing this if condition and I'll be removing everything from here I'll be implementing the handle submit after that okay so I'll be showing the loading when the session status equals to loading and here it is actually showing uh if the session status is not equals to authenticated and and after this I'm going to change the login to forget password okay so this is going to trigger the handle submit let's remove this password input element from here I don't need that so it is not actually text it is an email okay so this button is a submit so let's add the submit here change the text of the button and uh it will throw an error I'll be handling the errors based upon the response from the the API if the email does not exist in the database or if the email is invalid so I'll be showing the error messages over here all right and uh I don't need login with GitHub on this page so let's remove it uh this is the button all right so let's remove it and uh let's navigate to the login page from here if user change the mind uh to not to reset the password okay so let's save it and I think we are done with the UI um so let's go and manually try to navigate to the forget password route so I'm going to write the forget password hit enter and now you can see that uh this UI have been successfully constructed and we can uh navigate to the login page from here as well all right so we have built the UI for it now what I'm going to do is I'm going to open up the login page and I need to add the forget password link from this form as well okay so I'm going to add it below this one I think um I can add it above these input or you can add it uh below this form as well okay so I'm going to add that a div and inside this div I'm going to add a class name so let's add the text white text Hy 16 pixels and margin bottom four all right so this has been added uh now I'm going to add forget password below this I'll be adding a link so this link is going to have a class name so class name will be having the margin left hyphen 2 text blue 500 hover underline all right so this has been added now I need to add the href as well to it so for the href I will be adding the forget password okay so let's save it and inside this link I will be simply adding the reset here all right so let's see how is it looking on the UI and you can see that it's looking like this over here and we can click on the reset password we can navigate to the login page from here so this is the UI working fine and uh now what I'm going to do is I'm going to create an API route that will receive the data from this form and I'm going to send an email to a particular user okay and for that I will be using the service called send grid and I'm just going to show you that how we can configure send grid use its token to send the email ID so let's create an API route by creating a new folder inside the API directory and I'm going to name it for get password and inside it I'm going to create a new file route. TS and to save some time I'm going to copy the code from the register API route and I'm going to paste it in the forget password API route Okay so so here it contains this bcrypt which I don't need so I'll be removing it um I'll be getting the email from the client from the forget password component which I just created and I'll be collecting connecting with the database and I'll be checking if the user with this email ID exists or not if it does not exist I can actually write not here then I can change this message okay so email does not exists all right so here we are checking if uh the email exist in the mongodb or not okay so I'm going to remove everything from here this is going to be a long API route because we need to check a lot of things inside it so we have checked email existence after that I'm going to be using a package called crypto so this is going to be coming from crypto all right you don't need to install it it's already available in the backend API routes all right so using this crypto I will be uh creating a reset token and the reset uh password token and the expiry data as well which I just showed you in the mongod DP okay so for creating it I'm going to be creating a variable so reset token equals to I will be using the crypto do random bytes function and I can give it a value 20 you can go through the description from here okay so this is the length of the total alphabets that will be added um in this token okay and after that I will be converting it to the hexa decimal so two string hex all right so this has been generated now one thing is that we can store this reset token in the URL that we will be passing it to the email ID and we can use uh store this reset token in the user model in the database as well but for security purpose we don't need to store the same reset token in both the URL and in the mongodb database it can cause problems believe me okay so for uh this reason to avoid this problem I'm going to be creating another token so I can name it password re set token equals to and I will be using the crypto package dot create hash and uh I will be giving it a value sh a256 you cannot change its value make sure you add the same and I will be updating it by passing the reset token we need to pass it because once we will be validating the token which is in the URL and which is stored in the datab base uh this is where we will be using the built-in function of the crypto to validate the equality between do two things okay so after this I will be using the digest and then the hgs all right so this variable is something which I will be storing in the user model in the database and this is something which I will be sending an email ID by constructing a URL which user needs to click on to reset their password after this I will be creating the password reset expire value okay so I will be writing the password reset expires equals to I can use the date function plus 3600 it is in milliseconds so this value is equal to 1 hour okay means that our password token will be expired after 1 hour we will need to regenerate it in order to change over pass password okay so now what I'm going to do is I have actually fetched the particular user if user exist this is where the user will be existing in this particular variable so I can use the existing user. reset token equals to password reset token okay and then I will be using the existing user reset token expiry equals to password reset expires and after that I will be constructing the URL which I'll be passing to the email ID so I can actually use the Local Host in real application we need to fetch these based URLs from the EnV files because we can have the staging server production server so in the uh real application we will not be using the Local Host over here this is just for example all right so I can actually create this reset password route which I have not created yet which is the frontend component route okay and after this I will be using the dollar sign and the reset token all right there is one thing that I need to do you guys who have worked with the mongu models uh that it will not work because I have not updated my user model uh that I created using the okay so this is where you can see that it only able to contain the email password and the time stamps which Auto generates I need to add couple of more things which I have added over here so one is the reset token which I need to add here so let's add an object so it will be off type string and uh it will not always be required okay because while creating new user I don't want it to create any problem so it is throwing any error actually we need to add it like this all right so after this what we have here we have the reset token expiry so let's add that colon this one it is going to be type of date and required equals to false as well all right now when we will be updating these couple of properties for this user model it will not cause any problem URL which we have constructed let me log this URL so reset URL all right so I'm not sending any email yet I just want to print the URL in my terminal and see if the user model model gets updated in the database or not uh so let's try and test our functionality which we have implemented so far so let's go to the browser let's refresh and uh let's go over here let's click on the reset password first of all I'm going to be checking if the user exists or not in order to validate if this particular condition okay so currently there is no user so I'm going to be writing the um do um jam 32@gmail.com click on the submit um actually it is currently so there seems an error um all right so I spelled wrong I think so this has to be the false all right it happens um now it's happening let's refresh let's try with the email ID which does not exist in the database for now so so even if I click on the submit it will not work the reason is that we have created this API but we are not using it we have to go to uh let me close the user model and currently you can see that in the handle submit we are not calling that API the forget password so let's try to implement that so I'm going to open up the login page and uh I'm going to copy in fact I'm going to open up this register one and I just want to copy the overall structure so this is the overall structure of the TR catch block so I'm just going to copy this one and um I'm going to paste inside the handle submit function of the forget password so here we have the API SL register but we need to change it to forget password and the method is post uh we are not passing any password over here we are only passing the email ID so the email is already exist if it is for so I'm actually changing this particular error so user with this email is not registered all right and if it is 200 uh we are automatically setting this error message empty and we are navigating to the login page this is where we can show some kind of toast if you want um and if there is any kind of error um the server is not running or taking some time uh I'm just showing this error so we can actually test this now let's save this file and it will call this API uh on localhost colon 3000 API forget password and it should connect to the database and check if the email exists or not so let's refresh first of all and I'm going to change its added email ID let's click on the submit so user with this email ID is not registered so this particular logic is working fine let's try to register this user so I'm going to change the password first of all so that I know currently I cannot see what was the previous password stored here a b c d 1 2 3 4 click on the register so it will be registered let's go over here just to verify if the user is registered yes it is registered with encrypted password uh this is what I've already explained in the previous video how the register process works using next o and store the user data in the mongod DB so let's go to the reset here and uh now I'm going to use the same email ID which is registered in the database I'm going to click on the submit so once I click on it it will not navigate the reason is that you can see that it is throwing an error because I'm not returning any response from here just like over here all right but I'm using the console ninja package which automatically outputs the console log uh data in the vs code but here you can see that it is correctly constructing the URL including the reset token in the URL which I will be sending to the users's email ID so using this particular URL they can click on it and navigate to the reset password route where they will be filling out the new password and they can uh update their password using this token which uh we will be storing it in the database so to send the email ID I need to configure the send grid send grid is an awesome service it is a paid service but I'll be using the free service there is some limitation so I'm going to navigate to the send grid you need to create your account in the send grid.com and once you create your account you need to login it with and navigate to the app. send grid.com first of all you need to go to the settings from the left bar and you need to click on the sender authentication when you send an email you need to configure the sender email ID and you need to verify it if it is your particular verified email ID and I've already configured this particular email ID and I have validated that I am the owner of this email ID so whoever is going to receive the email ID they will be having um they will be having this particular email ID as a sender and we can also authenticate the complete domain if you belong to a company uh then the all the email ID belongs to that company or a domain will be authenticated as a sender okay so after this I need to create an API key click on the API key from the left bar in the settings and uh here uh you can create a new API Key by uh clicking on the full access and clicking on the create API key and uh I can actually write the next 14 here and click on Create and view okay so this is the key have been generated and uh it will not be shown again so I have copied it let's click on the done and I'm going to create an EnV variable so from that I will be using this key so I will be creating a new name inside it so let's name it send grid API key so let's write send Gore API key equals to paste all right so let's save it we have actually configured the send grid now we need to use the send Grid in our project so for using it we need to install a package I'm going to come to the terminal and I'm going to write npmi at send grid slma okay so I'll hit enter so it will be installed once it's getting installed let me import it so I will be writing SG mail from from at send grid mail all right so it is installed Now using this package I will be configuring the uh title the body and the content inside the body to send an email to a particular user and you know that we have already got this particular user and it contains the email ID to which we will be sending our email all right so here um I'm going to construct a variable which is the body so I can actually write the reset password by clicking on following URL we can obviously uh make this uh UI look better but this is what we'll be sending to the user email ID okay so I will be appending it with the reset URL which I have constructed above okay so after this I need to construct a complete object l let's say a message so what is that so this is going to be two email which is being passed from the client side over here and uh after that what is the from ID and this is what I have already uh registered in the send grid if you have registered any domain of your company uh any email ID belongs to this company can send the email so let's add the reset password as the subject and the text is equals to the body the variable which I have constructed so this is the complete metadata of the email which needs to send now I will be using the S Gmail and I will be setting the API key first of all so API key process. EnV do send grid which I have created over here let me copy it so send grid API key over here or empty all right this is just for uh validation uh so and not NG it is the SG mail so I have set the API key over here now I will be using the S gmail. send which is the message it returns us the promise so I will be using the then and uh this is going to return us a new response so next response I can uh show any message so reset password email is sent and uh we can return some status to the client all right so and if there is an error we can also handle this so I can write the catch block over here so I can write the async error all right so inside this cach block first of all I want to delete the reset token and reset token expiry to undefine it will delete everything these couple of properties from the model in the mongodb so undefined an existing user reset token expiry equals to the undefined okay okay and after this I can actually uh use the await existing user Dove all right and if there is an error I can simply return an error message and uh this is how it's going to failed sending email try again with the status 400 this is what I'll be receiving in the front end application over here all right uh maybe over here or here uh if it is 400 status all right and and uh outside this SG mail so we have handled sending email and if it throws an error after this we also want to add the TR catch block and I want to save the user existing user save and here I want to return some kind of message so it will be 200 and I want to email is sent for resetting password so we can write anything over here so there seems an error so I need to add the catch block with the error and inside the catch block I can return new next response error and then status is going to be 500 all right so this is how our complete code of this API is looking like uh it is actually showing some kind of so I can write any over here so it does not throw any error all right so now I need to verify if the user email is sent successfully to this email ID which is trying to reset their password so let's see if it works let's save it and I'm going to run the project and see if it starts working so let's go to the browser and uh I'm going to open up this let's refresh this page and uh I will be writing it may jam 321 at gmail.com so I'll be clicking on submit all right it should successfully navigate to the login page first of all because yes it has successfully navigated to the login page uh the reason is that it came back to the front end and this is where it is navigating to the login page because the status was returned 200 so from the screenshot which you are looking at currently is my email client and this is what the email is looking like currently if I open up this URL in my browser it will not navigate because I've not created reset password route currently in my nextjs application this is the next step to create the frontend reset password route so let's work on it before that I want to show you this data of the user in the mongod DP um that these two properties have been added over here all right because the email is sent successfully and uh we are adding these two things uh in the users model all right so now let's go ahead and create the reset password component so I'm just just going to remove everything for saving our time I'm just going to copy everything from the forget password component and I'm going to create a new component here so I'm going to write the reset password which is a component and inside it I'm going to create uh a new file so page. TSX all right so let's paste everything from the forget password component and um I'm going to uh change the name uh did I change the name of that forget password let me go uh I did not change so make sure you change it as well so uh we can uh let me change it to forget password here as well it will not affect because I'm not using it anywhere outside this component it's just a route file all right so let's close it and also here I'm going to change its name so reset password let's copy this let's paste it over here all right so let's see what we have here first of all um one thing I have missed I want to create another folder inside it because this is a dynamic route the the email which I have received it will be added in the dynamic route so I will be adding token within this square brackets all right and I'm going to move this page inside this token folder all right so now our URL will become Local Host column 3000 SL reset password slash the dynamic value will be coming in this token so this is how we can actually receive it from the params so params and after that uh we can have uh uh different types since we are doing typescript so for now I'm just adding the any after that so let's receive the params do token so I can actually log that out to verify if the token is actually getting received or not uh but first of all let's verify what we need over here we need this thing we need this uh and also we need another state variable and I'm going to give it a name verified set verified so if we are fetching the token from the URL and the token is stored in the user model in the mongod DB we also want to verify if the token is correct that is stored in the database and the token is not expired as well okay so this is how I will be using this state variable for this reason and uh now I will be using another state variable which is going to be a user and I will let you know why we need it so I will be using use state so ini ially it will be null all right and uh we would need it this one so let's leave it like this and uh this is going to have a use effect as well so I will leave it as is uh but above that uh we can actually verify so whenever we will be navigating to this reset password component uh I want to verify the token valid ation and I will be creating another API for this purpose so we can use effect and it will be running without any dependencies so uh I can add the empty array as well but U I can also pass the params do token as well which is coming from that URL all right so inside this use effect I'll be calling an API uh that will check if the token is valid and not expired ired okay so here um this is where we are checking the email ID which we don't need here and uh I will be using it later on okay so let's remove it I will be getting the password over here and uh this password is going to be passed to the reset password API which I have to yet create so we can actually pass the password all right uh along with the password we will also be passing the users email ID because without passing the users's email ID we will not be able to check that which users password needs to be updated so for now I will just be commenting this whole code within the the handle submit all right so but for now I want to focus on this particular use effect creating its API and verify the password but quickly what I'm going to do is I'm going to change it to the reset password in the UI and U this is going to be a password okay and this is going to be a password here as well uh and after that we have this button okay so this is going to be a reset password all right so I'm just going to remove everything from here um I don't need that so we have this reset password below this uh we have this or I'm going to remove this as well we'll be showing error over here reset password button having the submit and also I want to have this disabled equals to error. length greater than zero all right the reason I'm disabling this button if there is an error so when can be there an error so when the token is expired or token is invalid then I will be adding the values inside this error which will be showing over here uh and then I will be disabling this button so user should not be entering the password in this input field and clicking on this particular button all right so first of all what I'm going to do is I'm going to create an API for verifying the password so let's create an API inside the API folder I'm going to create a new folder so let's write the verify token and inside it let's create a file so I'll be name it route. TS okay so inside this route. TS um I can actually copy the overall structure this one let's copy it and paste it over here so let's close it like this so we can avoid different errors we need the crypto we don't need to send an email here we need next response we need connect we need user okay so here I will be passing the token from the client side from this uh reset password U this use effect okay this is the client and this is the server side code this is what you need to understand because we are inside the API folder all right so once the DB is connected I want to Hash token equals to crypto do create hash and I will be passing the same value which I used to create this hash token and after this I can update with this token and then I can write the digest hgs all right uh you remember that the URL token is different from the token which is stored in the user model in the database and that is the reason I'm converting it into the hash token and using this hash token I can check if the uh user um exist with this token or not okay so after this I can write the user equals to await user. find one reset token let's verify reset token equals to the hash token and then reset token expiry make sure you enter the same value over here and this is called the aggregation in so I can write the dollar sign greater than date so I'm checking here if the token is not expired using this validation all right and if user exists if it does not exist then I can simply return some kind of response let's copy some kind of response from this file and I can paste it over here so I can enter a message invalid token or has expired okay so after this I can also return the success response that uh I will be passing the stringify uh not inside this so Json do stringify user and then status equals to 200 so I am passing the user and this you this is how we can return the data using this next response if we don't want to return any string all right so I think we are pretty much done with it so let's save it now let's use this apiapi verify token in our page. TSX uh to check if the token is valid or not so inside it uh what I'm going to do is let's come here and first of all let's create a function verify token equals to async this Arrow function and I'll be calling this function from within so verify token like this all right so now uh I'm going to copy the whole structure from here I don't want to write this try catch block again and again so let's copy it like this so let's uncomment let's save it so it intent properly and this is not the reset password here this is going to be the verify token this is the API and this is going to be the post request column and we will be passing the token inside it so it will be pam. token and uh if it is 400 then uh we will be setting an error and I will be setting the set verified equals to true as well okay so so this is this is because um uh for the validation so let's add the errors so token or has expired okay so this verify variable is actually checking the process is completed the process of checking the validation of the token okay so this is going to be an empty and uh this is going to be the set verified true okay so I'm checking uh the complete process over here um and after this uh we are uh checking it uh let's try this thing we can have user data equals to await response. Json okay so this is the response which is coming from that API from here okay so so I need the user data so we can actually change the password for a only particular that user which requested to change their password okay so and then I can write the set user data equals to the user data let's see if we have here so this is the set user over here not the set user data okay so I think we are done with verifying this token um and we need to verify it if it's working fine or not okay so I think I generated this URL um which is stored in my email ID and the one hour is not passed so that token is still valid so let me copy up that particular URL and see so let's hit that URL so I'll hit enter so here you can see that it is not showing any any kind of error maybe so if I change the token from the URL let's see what happens hit enter and now you can see that it quickly run this use effect because we have added this dependency over here and it called this API which we have written and it is validating the token if it is valid or not so earlier when the token was correct and the token was not expired it did not show this error and uh um now it is showing the error and this button is disabled now currently I'm not able to click you can see cursor is changing the hover effect as well uh which I which you can obviously uh which you can update this uh based upon this condition uh it's up to you like but it's hovering in case if it is disabled or enabled in any case but I'm not able to click on it because the token is expired so let me add the correct token now it's not showing any kind of error because the token is validated and I can still change the password after this now what we need to do is we need to create an API for changing the password U and we need to create uh the code inside this handle submit button so first of all what I'm going to do is I'm going to create an API Road first of all to reset um the password successfully and update the user model in the mongodb database so let's create a new folder inside the API folder and I'm going to name it reset password okay don't get confused because I'm using the same names inside the API folder and the same names for the routes so inside it let's create page dot not the page it's then API so route. TS all right so for now I'm just copy everything from the verifi token code to get the overall structure of the file so here we don't need the crypto um one thing we need is the bcrypt package because for registering a user if I show you this is the register user route I used bcrypt to encrypt the password before storing it in the user since we are handling the new password we also need to use the same bcrypt package to actually encrypt and hash the password before updating the user model in the database so I'm just copying the bcrypt JS uh I need to install it yet so I'm going to write npmi so bcrypt JS so I'll hit enter so it will be installed U now inside it I will be receiving the password and the email of the user to which I want to update the password so this is the new password which I'll be receiving from the client and this is the email of the user of which I will be updating the password and um I don't need this thing I will be uh using and checking if the user exists so const existing user equals to await user. find one I can find it by email only as well okay so the reason I'm fetching the user because I want to update the password field and save it after that okay so now I'm actually using the hashed in fact let's open up this register and um I'm just going to copy this one all right so let's go over here let's paste it so this is the hashed password with the new password all right and uh after that I'm using the existing user . password equals to Hash password and once it is added with the new password um I want to make the reset token reset uh token expiry to the undefined okay so existing user do reset token equals to undefined and existing user. reset token expiry equals to undefined okay and after this we can uh save the new user and we can actually return the response so I'm just going to remove everything we can use the TR catch block as well so I will be writing the await existing uh user Dove which is saved and then I can return the response so let's return the response um I will be user is um what I can do user users password is updated any message and uhu then I can have the catch block as well uh like this let's copy cut it paste it and uh I can simply print the error over here with the 400 or 500 uh let's add the type for it all right so I think we are done with it uh so let me recap so I'm receiving the password and email ID I'm using this password to Hash it again and I'm using this email ID to get the user to which I will be updating the password for and then I once the password is updated I will be um adding the undefined to the reset token and the reset token expiry to this all right so now um I will be saving it now I need to use this API reset password in my page. DSX let me run the project as well so npm run Dev okay and uh I commented this code let me uncomment this and uh here I'm already calling the reset password and I need to pass the user email as well so since once the it was validated you can see that here I'm getting the response from that user and um here I'm storing it in this particular State variable so I can get this one uh user from here okay so let's come over here and uh passing this email from the user. email okay this is the state variable all right and uh then what I can do is I'm checking if it is 400 uh we can check like any error message something went wrong obviously you can optimize these errors and also we are getting errors from the response as well we can use those error messages as well and after that um we are navigating it to the login page and uh error try again or something like this all right so one thing I want to add over here that I also checked this set verified okay so I want to show the loading bar since I'm showing the loading bar based upon the authentication over here if the I'm checking if the user is authenticated or not but I also want to add this loading bar until and unless I'm not verified the process of verification of the token is not completed uh until then I want to show this loading bar all right so let me save this file I hope that it will work fine so um let's see so you can see loading bar is showing up um it's actually validating let's see DB connection successful and uh now this token is valid I think because we set the expiry date to 1 hour you remember that I updated the password to abcd1 2 3 4 now here I need to update the password but also um let's refresh this we can verify it from here as well um you remember that the last two digits of this password is gvi if we are able to successfully update the password it should be updated here as well and obviously these two properties will be removed from here and gvi should be removed from the token this is just for me to remember otherwise the whole code will be updated okay so let's go over here this one and I will be adding the new password a b c d 1 2 3 4 5 5 6 7 8 9 0 so I have completed all the digits so let's click on the reset password and if it goes to the login page and yes it has gone uh we can see that it has been added over here let's go over here and see if this has been updated or not let's refresh and all right guys so our password is updated uh and uh let me zoom out and now you can see that that this is not gvi means that the password is updated over here as well and those tokens have been removed here as well so here let's go and try to login with the old password so let's click on the sign in yes we are not able to log in let's try to add a new password so a b c d 1 2 3 4 5 6 7 8 9 0 Let's click on the sign in and yes we are able to successfully log in so over forget password reset password functionality is completed and we are navigated to the dashboard which is the protected route one thing I want to verify here um I want to navigate to the uh forget password route here so let's see if we are logged in are we able to navigate to the forget password let's hit enter and yes we are not able to navigate to forget password because we are authenticated and similar to that and everything is being handled through this check okay this check is handling uh everything and also we are using this use effect it's checking if we are authenticated then we are navigating to the dashboard route and we should not be able to navigate to the forget password we should not be able to navigate to the reset password uh page as well so um let's navigate so it will be navigated to the dashboard because we are not uh uh successful uh we are not um logged out currently so let's click on log out one thing more I want to verify here uh let me copy that URL since our uh re password have been reset if I try to trigger the same URL again okay let's see what happens so let's run and now you can see that invalid token or has expired and over token is correct the reason it is showing that because we have already used this token toen to change the password and it has been removed from the database as well so in order to change the password again we cannot use the same token we need to regenerate that token so this is how the whole flow is working and over complete authorization authentication process have been completed so I just want to request you guys you can see I'm putting a lot of effort building these videos for you guys so it's just a request to subscribe my channel and like this video and hit the Bell icon as well so you get the notification for for upcoming videos so if you have learned something new do comment below and share these videos with your friends I hope that you have learned something new and you have got an idea how the authorization authentication process works including storing the data in the database forget password reset password verifying token how to generate token and it is a kind of advanced concepts but I have tried to complete it with easy steps and easy explanation so it will really encourage me again guys to subscribe my Channel and like this video and thank you so much for watching see you in the next video
Info
Channel: Programming with Umair
Views: 8,020
Rating: undefined out of 5
Keywords: next-auth forget password, nextjs 14 tutorial, nextjs auth, next auth, next js 13, next js, forget password in nextjs, reset password next js, next auth reset password, connect mongodb in next js 14, next auth verify token, login with next auth in next js, register user in next auth using next js 14, protect routes in nextjs 14, sendgrid in nextjs 14
Id: sO5df9FVIT8
Channel Id: undefined
Length: 63min 33sec (3813 seconds)
Published: Tue Nov 07 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.