Complete User Authentication in React JS , Node, Express, MongoDB with JWT - MERN Stack Tutorial #10

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone and welcome back to roadside coder and welcome to the 10th video of our mern stack tutorial series and in today's video we are going to see the complete user authentication in react.js by using node.js and express.js as a backend and mongodb as a database so first we are going to implement our user authentication that is login and sign up in our backend and then we will go on to create login and sign up forms in the front end and then use the backend api to create the front-end functionality we are also going to store our user data in our local storage so that every time we open the browser until we log out we have our user logged in so without any further ado let's get started so i've opened our node zipper folder here in vs code and let's go to our backend folder and as you can see we have created our server inside of this file if you have not yet seen that video in which we are creating our server click on the i button above or check the link in description for that video so now over here you can see we have created a few routes for serving our nodes so these routes are currently serving the static data they are not serving the data from the back end but we want the data to be served from our backend so for our user authentication we are going to create a backend functionality where we can successfully register our user by storing the data in the database and then we are going to fetch that data by using the login api so for now let me remove this app.get api and this let's just keep this api for now because we're using this in the front end so now i'm going to change our folder structure a little bit so we're going to first create a new folder for routes and another folder i'm going to create for controllers so this routes folder will have file which will contain individual routes for let's say one route is for nodes so it's going to contain one file which contains all the routes for the nodes and another file will be for let's say user so let me just show you real quick so if i create app dot use so we're going to create a new route over here so let's say api slash users so all of the routes related to the users are going to go in user routes file so let's go to routes and create a new file called user routes dot js and inside of this file i'm going to import so we're going to import express and then we're going to import something called router from express so const router equals express dot router all right now let's create our first route over here so router dot route so this route is basically an api endpoint so we're going to create a slash route and so since we are registering that is we are storing the data in our backend so we are going to use the post request so post and we are going to have a controller inside of it which we will create inside of the controllers folder so don't worry if you are not able to understand the folder structure you will eventually understand what i'm doing over here so let's import this route first of all so module dot exports equals router oops router all right so we've imported it now let's uh i mean we have exported it let's import it over here so user routes okay it's not auto importing let me quickly go and manually import it so const user routes will be imported from require dot slash route slash user routes okay let me make this restructured okay i guess that's important okay let's start our app let's go to our terminal and in our root folder i'm going to have npm start npm start or you can write node and then the server.js files name so i've configured this script over here if you don't remember uh where is it oops okay that's package lock yep there you go node node mode back and slash server.js okay we have some error over here okay that's my bad i wasn't supposed to do this i wasn't supposed to destructure it because that's a default uh import right now let's see okay fine our server is running fine okay now let's create our controller function for it so inside of the controllers i'm going to create a new file and create user controllers and here let's create a function called register register user it's going to be an asynchronous function since we're going to make requests to mongodb so request comma response as we have done previously so inside of it let's accept few of things from the user so what do you what do we need to register a successful user so we're gonna need name email password and picture okay so we're going to take take all of these things from request dot body so understand this when we request something from the user we're going to use the request and when we provide something to the user we use response variable so we are requesting all of this stuff from the user currently so let's take these things and let's display it let's throw it back to the user so let's say response.json and we're going to provide them with let's say email sorry name and email let's give them back all of these two things okay fine let's import this function so module dot exports why do i keep saying import for exports anyway so register register user okay we're exporting this let's import this over here so just user let's try to import it again let me see what's the issue is module dot exports yep there you go yeah it's working fine now let's test it out let's go to our postman and let's quickly test this end point out so i've opened our postman over here and let's create a new folder or new collection for this project i'm going to click on and click on this plus icon over here and it has created a new folder so i'm going to name it node zipper it's just to make your life easier so i'm inside of it i'm going to create a new folder for user and auth these are completely optional if you don't want to create folders for all of this and now i'm going to create a new request for it's going to be a post request for slash api slash users okay so let's set post over here and and write our url so i'm going to add a new variable for our local host 5000 url so let's add an environment variable this one is so what i want i'm going to name it node zipper environment and let's add a variable called url you don't need to understand all of this stuff just notice what i'm doing http local host colon 5000 so i've created our url if you don't want to create the url you can directly enter it over there so let's go over here and inside the double curly braces so url i'm gonna use this variable and slash api slash users okay fine it's everything looks good let's click on send let's see what happens okay let's inside of our body i'm going to give this some json data and we're going to give name that's it oops email password so yeah let's try to request these oh i could not send request so what's wrong over here i think okay we haven't selected our environment so now we we're gonna be good so just click on over here and select node zipper environment and now try to send it so it's sending the request but nothing's happening let's go to our console and there's some error there's some huge errors cannot just restructure property name of request.body okay so resolve this error what do we need to do we just need to go to server.js and below this this is a very important point you have to do every time whenever you accept the json data from the user so app.use express oops express dot json just type this and let's try it out again let's click on send and there we go we get name and email back from the server i mean all right cool now before moving forward i would like to install a few of the dependencies so i'm gonna go over here and type npm install first dependency will be for bcrypt so be crypt dot i mean b crypt js the other one will be express async handler and the third one will be json web token you'll know all of these things when we use all of them so let's say bcrypt is used for encrypting our passwords express async handler for handling our errors and json web token is to create a token for the user so let's keep moving forward for now and i'll explain you along the way let's start our server again now so we are going to store the user data in our database so for that we need to create a model for our user so let me explain what model is so i'm going to create a new folder over here model and i'm in models m-o-d-e-l-s and instead of this models folder i'm going to create a new file called user model dot js so what is a model so model defines a what type of data user is going to have for example it's going to have a name which is going to be a string it's going to have an email which is going to be a string it's going to have a password it's going to have a picture so all of these different different things that the user data is going to store so let me quickly write it over here so we're going to use mongoose to create our user model so import mongoose from mongoose and we're going to import bcrypt from series okay let me just copy the user schema then i'll explain what it is okay there we go let's understand what's going on over here so we've created a new variable called user schema and we're using mongoose.schema over here so inside of here first of all we're going to take the name which is a required field so we've given required equals true you can go to a mongodb's official website to read more about these data types and it's going to be a type string second we're going to have an email which is going to be unique remember no two users can have a same email right so it's going to be unique and required is going to be true because it is required we're going to have password string which is also required is admin so just in case we need any admin functionality in our app um it's good to have uh is admin field over here which is going to be a boolean so it's going to be by default false uh but it's going to be required so yeah that's another thing and we're going to have a picture and we've given our default pick over here so if you click on this link you can just add any default picture over here so i've just added this link over here if you uh if you want to get this link you just need to go to github.com and just find the node zipper repository so note zipper just go to this repository inside of the backend folder inside of the models oops not notes model the user model and just take this link if you need it okay so right now we don't need it i mean i don't need it it's already over here so by default it's going to have this value if the user don't want to set the picture so yeah this is what it is and we're going to set the time stamps to true so that we can track when the date when this field was created in the database and when it was updated so great this is our user schema so let's go down over here and export it successfully const user equals mongoose dot dot model and we're going to name this model user inside of it we're going to have a user schema that we created above and let's export it so module dot exports equals user great now another thing so we are using all of this schema but before saving the data to the database we want something that encrypts our data we want our password to be encrypted or you know what let's just uh leave that for now and let's create our user controller first for our registration and then we'll talk about it later so now let's see since we are accepting all of these four fields from the user now first of all let's just import our user model over here so const user equals require dot dot slash model slash user model okay and we're going to import one more thing so const async handler async from express async handler so what we are going to do we are going to wrap this function inside of this async handler so this is going to handle all of the errors that are going to be in our application so it's going to be useful for us okay now after we are taking the input from the user we need to check if the user already exists in our database so const user exists equals a weight i'm gonna await this so user dot find one so these are the queries of mongoose or mongodb so you can learn more about it on their website there are tons of such queries but i'm going to explain all of the important ones in our course so don't worry about that so we're going to find it by email so user dot find one okay so if there's some uh a user with this email in our database it's going to find it and it's going to return it our user exists so let's check now if there's something inside of user exists if there's something then what are we going to do we're going to throw an error so response dot status so status this is the status quo for error and we're going to throw new error through new error user already exists all right but if the if the user doesn't exist what we're going to do we're going to create a new user in our database so cons user equals await user and this is the function to save it to our database create we're going to create a new user in our database so going to use name email uh password and picture great so if this is successfully created then so let's check if user that means if there's if this is successfully created if there's something inside of it then we're going to send a response so response dot status 201 that is it's successful and we're going to return the json with all of these things except our password so i'm going to return id it's going to give our give us an id which will come from the database so id comma name which will be user dot name oops let me write the id as well id will be user dot id don't worry you'll understand all of this let me just write it quickly first so email and then picture all right there we go and let's take the is admin as well if we need for just to check so you might remember we put this is admin as default so it should already should have been set to the false since we are not providing it so if the user exists then i mean it's successfully created then it's going to return this else it's going to throw us an error that means there's something went wrong let me remove this first fall else response dot status of error that is 400 and throw new error which is going to be let's go to our postman and let's try this out and i'm going to send this request now there we go it has successfully created now let's go to our database and check if it has successfully been created or not we're going to select our project for you it might be just single projects if you have not created other projects as well so this is our project let's go to collections and there we go we have a user field over here and our user is successfully created but there's a problem you can see our password is in the normal form it's not an encrypted form so this is a huge risk for our application so let's go on and encrypt this password all right i'm gonna go to user model.js and before this we are going to add some instructions that before saving you need to encrypt the user password so user schema dot pre so pre means previous of what saving operation before saving what do you do we're gonna call a function and it's going to be a middleware so it's going to have a next inside of it so that after this operation is done it can move on to the next part of the operation so if this dot is modified so it's a mongoose function this dot is modified we're going we're checking if the password is modified or not if this was not modified then we're going to move on so next otherwise we're going to generate a salt from b crypt so this is a b crypt functionality so we are generating a salt for our password so it's going to be a unique salt salt dot b crypt dot gen salt so we're generating a salt we can generate a salt asynchronously as i mean synchronously as well this we are generating it asynchronously so gen salt and let's say it's going to have a value 10 the more higher the value the more secure the password so this dot password equals await be crypt so these are the functions of bcrypt you can read more about it from their documentation so we're hashing it this dot password comma salt so we're using the this dot password that is the password that the user has entered we are using it and we're adding the salt to it and then making it encrypted okay great so let's try this out let's go to our postman and try to make this request again remember this email is now stored in our database so this should give us an error so let's send it there we go user already exists let's create a new email let's say push one at the right example.com and let's send it again now it has successfully created and now let's go and check our database i'm going to go over here and refresh there we go our password is encrypted in our database congratulations you have successfully done the user registration part okay there's one confusion so just let me add switch to back to that email and send it now you can see this error this error is in it this is giving us this html document over here so we don't want this html document we want a proper error so what do we do we're going to create a middleware for throwing us errors so i'm going to create a new folder called middlewares and inside of this folder i'm going to have our error handlers so for the commoners we're going to add a new file called error middleware dot js and let me create the few error middlewares over here and then i'll explain what's happening okay so i've created two uh middlewares over here first one is not found when the route is not found for example we are requesting this api slash users if let's say we write some route that doesn't exist so it's going to give us this error not found and as dash the requested url and then it's going to throw us an error and it's going to move on so the other one is for general errors it's going to see if the what the error is being thrown by the server it's going to convert it in a structured form just like that if so it's going to give us a message and it's going to give us a stack but we don't want the stack if the application is in production form so we're going to add a node env in our dot envs so let's go on over here and create a node env currently our app is in development so let's just add development over here i don't need to worry much about all of these things that are not that much important but yeah you need to add this error middleware now let's include this in our server file so i'm gonna go to server and i'm gonna below this an app dot use first not found and then the other one will be error handler let's see if they are imported or not yes they are imported what's wrong i've made this mistake of using this so module dot exports equals both of these okay now it should work fine let's go back to our postman and check it out let's send this again and there we go we have our errors in much more structured format so user already exists great so we have successfully done our registration route or our registration api now let's move on to create our login api but before creating our login api i want to create another function in our user models.js so this one was to encrypt the function but i'm going to create another function that will go into that is going to decrypt our password so inside of the user schema we are going to create a function called by using methods methods and we're going to create a method called match password so you're gonna know how we're going to use it in just a second so for now let's create it let's say it's an async function and then it's going to return so there's a function of decrypt called compare so it's going to compare the passwords from our database and the entered password so entered password will be compared from this dot password so this is what password will be the password that will be coming from our database so let me show you real quick let's go to the controllers and first of all let's go to routes and i'm going to create a new route for our login let's duplicate it and create a new route for login all right and we're going to have login user function so let's go login user or auth user let's go into our user controllers file and create a new function so i'm just going to copy this function over here and paste it down here and let's for now remove the content and i'm going to name it auth user let's export it real quick all right and let's import it over here auth user there we go all right so what do we need for our user to log in we're going to need our email and our password that's right so let's use both of these things to log in are you successfully so const we're going to find our user in our database const user equals await user dot find one we're going to use this find one function of mongoose so we're gonna find it by email so as you know our email is unique so we're gonna find it by using our emails so it's gonna check if user if there's something inside of the user and it's going to check if the password is correct or not so wait so by using user dot match password as you know we have created this function a second ago match pass word so we're going to match the password and we're going to supply the current password that we are taking from over here so you're supplying it the password so this is going to check and it's going to let us know if the password is true or false that is it's correct or not so response.json then we're going to return the data we are going to return this data id name email is admin and pick great and but if the user does is not found so we're going to throw an error so let's take this error invalid email or password all right so we're gonna throw this error great now let's try this out let's go to postman i'm gonna create a new request for post slash api slash users slash login here as well i'm gonna have slash api slash user slash login and let's take this data body we're going to put raw and json over here and we just need to send our password and email let's try this out okay this is a post so let's post it and send user.match password is not a function okay there's a error over here let's see what we did wrong so we created this match password okay there we go we are missing a d over here let's try this out again let's send email or okay invalid email or password i think this is correct oh it's uh matching this okay we are not supposed to use this because in this one the password is not encrypted yet so let's use push one at the example.com let's send it yeah that is working absolutely fine there you go you can see the id name email okay this pic data is not correct so i'm not going to send the pic this time so let's send john at there example.com let me give the name as john doe and password as one two three four five six let's send it unexpected token okay we have added the comma over here let's send it again and we have successfully logged in and you can see our default picture is added in over here so go to login and oops i am going to log in again by using john so john example.com and password123456 and let's login yep that's working absolutely fine great we have successfully created the backend functionality for our user login and authentication congratulations so let's recap real quick so we have created this route over here api users and then inside of this routes we are creating two new routes first fall register and the other for login so inside the register let's go we are taking all of these fields from the user we're checking if it exists inside of the database or not if it doesn't exist i mean if it exists then user already exists error otherwise we're going to save it in our database and similarly we are using it for our login as well if you don't understand i mean if you didn't understand any of this part you can just comment down below and ask me anything so anything related to decrypt or user models or anything okay hold on i forgot to add one thing in our backend functionality and that is jwt token so whenever we are sending all of this stuff we are sending our name here i mean this name email is admin pick we need to send a token to the front end which the front end is going to use to authenticate to our backend so we're going to use the uh something called jwt token so we have installed our json web token just a minute ago by using not a minute ago a little while ago so by using this npm install jwt token i mean json web tokens so i'm going to go to our backend create a new folder called utils and inside of it i'm going to create a new file called generate token dot js and inside of it we're going to generate our token so i'm going to const jwt and project from json token and we're going to write a function called generate token oops token so what it's going to take it's going to take the id from our database the user id and it's going to return it in form of the encrypted token so jwt dot sign and it's going to take the id and it's going to take something called jwt secret so process dot env we're going to store it in a dot env file so jwt underscore secret and we're going to set in what number of days the token is going to be expired so let's write expires in and you can give the days the minutes the hours so let's just give it currently for 30 days and module dot exports generate token all right let's just write this jwt secret over here so i'm going to go to my dot env and jwt secret equals p i y u s h one two three four i'm gonna write ph one two three four and yeah that's all now let's test it out what are we going to do we're gonna go back to our user controllers and when we are sending this we're going to send our generated token as well token generate token we're going to import this function and we're going to provide a user dot underscore id similarly we're gonna do this to our authentication user as well let's import it okay it's already imported at the top just like that now let's test it out sportsman let's login there we go we are getting our token back successfully great similarly in our register as well it's gonna work so let's just test it out so let's instead of john let's write jane and it's working absolutely fine so anyway let's move on to our front end let's just close all of the tabs in our back end and let's move on to our front end i'm gonna open another terminal over here and i'm gonna cd into front end and npm start and you know what i'm gonna change the theme of our editor so currently it was for node i'm gonna change it for react i think this is more like it there we go our front-end application has successfully started let's go back to our vs code and inside of our app.js so as you can see we have created our landing page route let's go to our landing page so we have these two links over here for login and sign up which are these two buttons login and sign up currently they're not working so let's start by creating the routes or the page for these two i'm gonna go to app.js and create a new route for both of these first one will be for login and another one will be for register this one is going to be the login page and let's say this one register page page another one for register page page oh you know what let's just rename it login screen and register screen and change this level okay inside of the login screen i'm going to create a new file for login screen dot js and our afce and some boilerplate code let's just write login and similarly inside the register screen as well so register screen dot js a f c e register all right cool let's go to app.js and import both of these login screen register screen so we have imported both of these over here all right let's try this out let's see if this is working or not click on login okay it takes us to login there we go login is written over here let's click on sign up yep it takes us the registers all right so what are we going to do let's go to our original application so node zipper.heroquap.com let's see what we have to create over here meanwhile that's opening i'm going to open react bootstraps documentation get started so what are we going to use to create these so okay let's log out it's opened all right so now login page you can see we have two fields over here one for email address and another for the password and we have a button over here and if the customer is new we can click over here and go to register page so it's a fairly easy ui so let's go to react bootstrap and i'm going to search form forms so we're going to use this forms so how do we create a form we create something called form control which will take an email and inside of it we can write a text for example we'll never share okay we don't need this text for not going to use form.txt so we can create a form group and we're going to have a parent uh id for parent tag of form so just like that we can create a form so let's go back and also for our button we can write this button tag over here as we have already seen our in our react bootstrap video so let's go back to our text editor let's go to our login screen and let's start building our login screen okay first of all we are going to need this main screen component over here you might remember that we have created that it takes the title of the page so i'm gonna go over here and type main screen and what does it take it takes a title which is going to be login in our case let's check oops okay means green let's see let's go to login oh there we go login is working fine let's just give it some capital so login that'll look good yep that looks good now below this we're going to create a few forms so let me create the forms and then i'll be back in a second all right there we go i've created a ui for our form so you can see over here let me explain what i've done so we have used a div for login container so okay i have to use this class name we're going to use this class name in just a minute so i've created this form tag over here which goes till over here so inside of it we have created a form group just like in our documentation we have created a form for email address so it's going to have form dot label and it's going to have form dot control just ignore these comments for now it's going to be a type of email and placeholder will be an enter email so let's check it out so this is the label and the form and just like similarly for our passwords as well we have done this we have the type of password and it's going to have placeholder of password and a button for submitting it and below this we are having a row which asks new customer then it's going to push us to the register here link all right so let me just add these styles these styles are nothing but just to add a few margin for this form so let me add a new file login screen dot css let me import the css login screen dot css there we go and for login screen css we're going to add this we're going to add a display of flex effect selection column and a margin mainly this margin of 20 pixels so let's check it out so as you can see it has provided a margin of 20 pixels okay that looks beautiful great also in our row we have added padding of the vertical padding of three pixels so that's another thing all right great now let's now let's start adding the functionality we're going to create a few states over here we're gonna we are which are going to store our email passwords etc so use state first one will be for email it's going to have default value of nothing so let's import the use state yup just like that let's create another use state for password it's not going to have anything let's create another state for errors so use state error by default there's nothing going to be inside of the error and another state will be for the loading now you're gonna know uh how we're going to use this error and loading in just a second so it's also going to be false by default okay i've misspelled it l-o-a-d-i-n-g okay there we go now so whenever we're changing our email it's going to call this on change function and it's going to set our email with the value e.target.value and it's going to be a control input so we're going to give it the value of email that is this i mean this similarly for password as well on change it's going to change our state so on the form submission so inside of this form tag on submit i'm going to have a function called submit handler that's gonna give us an error because submit handler is not defined const submit handler so what this submit handler is going to do for now it is going to log error and pass sorry not error email and password let's try this out let's go to chrome and click on inspect all right i forgot to add one thing uh when we when we're submitting it we should do this e dot prevent default and let's pass e event from it okay what is this okay yeah let's try this out again let's give it any this and this okay there we go we have our email and password successfully rendering over here great now let's move forward so we have added our states and everything now it's time to call our api out of this let's remove this for now i'm gonna add a try catch block so i'm gonna write inside of this const config so whenever we are making a api request that takes a json data we need to provide it some headers so headers it's going to be content type spellings are very crucial so make sure you take care of the capitalization and everything so application slash json okay as we've created the config now let's create uh the request but first of all when before creating the request we need to set the loading to true i'm going to make the loading true and after the request has successfully completed i'm going to make the loading so set loading to false and but between these what we're going to do we're going to make the make the request so const data equals await axios dot post we're gonna post in slash api slash users and slash login all right now we're going to provide it with our email and password there we go and the third thing is going to be providing the config so recap so we've created the config over here we are calling the api we are providing it email and password and the config over here okay there's something wrong okay so this is an await so it's going to have an async over here so axios is not defined let me import the axios okay import axios from axios there we go it should work now and inside of the catch we're gonna write we're gonna set the error so set error error dot response dot data dot message all right there we go this will be our error setting so uh so let's set the error and loading first of all also i need to add one more thing when the process is successfully created i want the email and password to be stored in our local storage so local storage dot set item i'm gonna name it user info and i'm gonna set it in the stringify format in the string format so i'm gonna use json.stringify because our local storage cannot store the object data so we need to convert it into string data so dot string if i there we go also let's just log it let's log the data also notice over here i'm restructuring the data out of whatever we get so yeah that's another thing okay let's check this out so i'm gonna type john at red example and one two three four five six let's submit it there we go we get the data from our back and congratulations we have successfully created the login functionality in our front end but wait we are we need to create some error and loading components as well so that it looks good i'm going to go back to our vs code and inside of our components inside of the components i'm going to create a new component for loading dot js and for the loading we're going to use a loader from a bootstrap so we're going to use a component called spinner so let me create this component real quick it's not nothing very fancy over here so we're going to import spinner from react bootstrap let me show what this spinner is all about so we're just giving it some height and width and some basic display of flex and some justify continental item center to make it center of the screen and it's going to have a default size of 100 but if we want to supply any size from outside we can do that as well so it's going to be set over here so let me quickly go go ahead and show you so let's go over here above this right above this i'm gonna add loading so if the loading is true and so it's going to show the loading let's go to over here and let's click on submit there we go you can see there was a short loading over there and then our data appeared so try again yep there you go similarly we need to create something for our error handling as well so just have a quick look at the loader so this is the animation just go to a spinner in react bootstrap documentation you're going to know it's an easy documentation you're going to understand what this spinner is all about so and another thing we're going to create a new component for error message dot js so let me create it so for the error message we are going to use the alert component of bootstrap so let's go to bootstrap and type alert yep there we go this is what we're going to use this red one so we've created a alert so it's going to take a variant if we don't supply any variant it's going to be by default info which is blue one and it's going to take some child so let me quickly uh implement it and show you so instead of the login screen i'm going to check if there's inside of something inside of the error and then we're going to have error message and inside of it we're going to supply the error as children and let me give the variant of danger let's check it out let's go over here let me refresh the page and this time i'm going to j john 1 2 3 4 5 6. so let me submit it yep it's correct but let me just remove one o and submit it now yup you can see invalid email or password and you can see this infinite loading as well so let me make this false after we get an error set the loading to false then it's going to be gone let's try it again submit yep it's gone okay great we have successfully created our login functionality now let's move on to our registration functionality but wait we forgot to do one thing over here so inside of the use effect we are going to create a use effect and we're going to check if there's something inside of the local storage so we haven't checked our local storage yet if it's storing successfully our data or not let's first do that let's go to memory i mean application and inside of the local storage there we go you can see uh user info is being stored successfully inside of this over here so let me delete it for now so instead of the use effect it's going to have it's going to take first of all something called history from reactor dome if you don't know about react router dome you can go and watch my reactor after dom video the link will be in the description and i button above so inside of the use effect i'm going to fetch the user info from our local storage so local storage dot get item i mean get item so we're getting this item user info from our local storage and if there's something inside the local storage that is user info then we're going to be pushed to my notes page and we're going to provide this the dependency of history and user info so whenever it changes it's going to trigger this use effect function so user info is not defined it is defined okay i think we should create a state for it but let's let's just remove it for now we don't need it okay so let's login so john and one two three four five six let's submit okay some error record i guess okay submit there we go it has um added it to there but didn't post us to my notes what's wrong let me refresh it yep now it's pushing us so if we try to go to slash login it's going to push us back okay so let me just remove this from the application so that we can go back yep now we can go back and you know what this use effect we're not going to add it inside of our login screen let's just add it inside of our landing page i think that is the place where it will make more sense because that way we're not going to add it at a login screen and sign up screen both the places so we're just going to add our use effect over here so use effect let's import it and for now let's just keep it commented we're going to uncomment it whenever we're going to use it okay so yeah that's that and let's go to our register screen and let's quickly make our register screen as well so i'm going to give it the main screen component there we go title will be register let's see if it works or not let's go to sign up yep there we go let's create the register component as well just like we created our login so i'm gonna create it and i'll be back in a second all right moving on so i've created this form over here so let's go to our browser and check okay yep there we go our form has been created let me explain this real quick so there's nothing special the same thing we have created this login container just like previously just to give us a little bit space at the sites and we have a form over here with a form group of name of email of password and confirm passwords because we're going to make the user enter it twice so confirming the password and our for our profile picture we are having a form dot file so form.file is the part of bootstrap so it provides us a ui like this where we can select our photos all right cool now let's start adding the functionality so let's go to our code and i'm gonna start by creating a few states so these are the states that i have created so let me import the use state over here okay so first of all the state will be for the email the name for a picture so i've provided this default picture link over here that i have provided in our database it's the optional if you don't provide it it's all right but i'm just providing it for example if the user doesn't provide any image so it's going to take this image and give it to our database and upgrade it for our password for confirm password this is going to be a message for example if the user enters the wrong password it's going to throw the error with this message component and this pick message if the user doesn't uh selects a pic it's going to display an error above the picture by using this and i'm going to create two new use states for our error as well and for by default is going to be false and for our loading loading and it's going to be false as well okay so let's remove these commented out things so it's going to set our state you already know the drill so this is just the basic react nothing else okay there we go let's try this off if it's working or not go to the console and let's create a submit handler for us so form on submit it's going to call submit handler right below this const all right and i'm going to log email let's just log email for now just to test it out so let's write anything over here let's add a picture it doesn't matter just register okay our email is logging that that means our form is working fine okay great so first of all before entering i'm gonna check if the password not equals to the confirm password so we have a password and confirm password state over here if it's not same then we are going to throw an error what error are we going to throw set message so this message component that we have created over here so set message passwords do not match else we're going to move forward and call our api so let's try this out first so this is the message component so if the message is true then the error will be danger and you know the drill what's gonna happen after that so let's try this out if the password are not same which they are not so there we go passwords do not match great that's working fine yes else there will be nothing inside of the set message empty or yeah null and we're going to have a try catch for calling our api so just like previously we're going to create a config with our headers of content type application json and we're going to set the loading to true and we're going to call our api just like that we're setting the loading to true and we're calling the api slash api slash users and it's going to be a post and so then we're going to provide it with name pic email and password and our config and after that we're gonna set our loading to false and we are going to set our item to local storage just like this so okay wait again we forgot to do this async okay axios is not defined there we go now it is defined and ready to go okay so inside of the catch we're going to set our error just like that and let's uncomment this out it's just same as previous i didn't want it to waste your time that's why i already written all of this stuff and just commented it out so there we go all right so i guess it should work fine now okay now let's try to do some registration test at the rate example.com and currently we're not setting our photos so no use of doing that so let's try to register okay i guess that uh it's successful register because we forgot to log out the data so let me check our database real quick let's refresh it okay there we go test at the rate example.com we have successfully registered with this test account all right great let's go back and this time i'm gonna log the data as well all right and did the loading work i did not notice it so i guess it would have worked anyway so now is the most important part now we're gonna add the picture uploading functionality so for that i'm going to go to my browser and to a new tab and gonna open i'm gonna search cloudinary so cloudinary is the service which provides us uh with the data storing functionality so let me just log in real quick so after you create an account on cloudinerry i'm gonna tell you what do you need to do to store your images successfully in the ordinary so after you have successfully created your account just go to this settings icon over here and go to upload and here scroll down you can see i under upload presets you need to check this up enable unsigned uploading so i've enabled it and i need to add upload presets so i'm gonna add let's say note zipper for this project and signing mode will be unsigned and saved and that's all that is all that you need to do now let's go back to our dashboard click on more and here you can see you have these uh base delivery urls so what you need to do just go over here sorry this api base url just click on this arrow and take this url just copy this url up and remember the name of the project that you gave for for me it was note zipper for you it might be different whatever you have set it so now i'm going to create a function below this for setting our picture so you can see we have created a pic uh yep there we go a pick state so we're going to store the pick inside of it but first let me demonstrate how this is going to work so i'm going to create a function called post details so it's going to post the picture and take the details so it's going to take pics okay pic is already defined so let me just write pics over here so first of all set pick message is going to be null because that's our error handler so it's going to be null at first also i'm going to check if the picks is undefined okay not this if the pick is undefined or let's just write like this if there's nothing inside of the picks let's return the error of please select an image otherwise it's going to be null okay now let's move forward now let's check if pix let's validate it if pix dot type is image slash jpeg what if that's the case then we're going to move forward we're going to create a new form data so this is how it works whenever we want to upload a new file we create a new form data you might be aware of it this is some basic html so new form data so data dot append these are just generic code which we use while uploading photos and files with cloudinery or with anything so we're gonna add a new field for pix and we're gonna add data dot append and we're going to append our cloud upload presets what was our upload preset so upload underscore preset what was the upload preset for us for me it was node zipper and again we're going to upload add another append which is going to be cloud name and i'm gonna have to give my uh username over here so roadside coder how can you find your username it's just right over here see it's right over here just write that so roadside coder and after that you need to add fetch so we're gonna fetch with this link and we're going to add some methods inside of it so method will be post and what will happen great now whatever we receive from this fetch request so then so this is the simple fetch request that we use in javascript so response or converted into json now we're going to set the picture for so this will provide us with the url of the stored pic in the cloudinary so data dot url dot to string so we're going to convert it to string also let's just log it let's just log the data over here as well and then if the error occurs we're going to catch it and we're going to log it over here all right there we go also if uh if the image is not a png or jpeg then also we're going to provide it then error so return set pics please select an image okay so that should work so let's go to my image and let me remove this comment so if the pick message has anything inside of it it's going to send us the error message and on change i've added this on change over here so it's going to take the event and event dot target dot the zeroth index of our file what means whichever let's say if we select more than one image it's going to select the first image that we have selected so let's check it out let's test it let's go to node zipper and notice the console whenever i'm selecting an image see it's going to load it and it's providing us with this all of the data over here and inside of it we are supposed to use the url so data dot url this is the link so if i take this link copy and let's paste it over here oops let me remove the quotes and paste it yep there you go we have this image over here great our image upload functionality is working absolutely fine now let's try to register our user finally and let's go after example i've given this let's upload a profile picture and click on register it's loading and let's check if it's done or not boom it's done we have a token we have a picture we have a name we have an email and everything so we have successfully completed our login and registration functionality in our front end as well so there's one more thing left that is our logout functionality so to implement our logout functionality what do we need to do we just need to click on logout and it should clear our local storage so it should clear this thing this user info from our local storage okay so let's go to our over here and it's located in the header i believe yep there we go log out so on click it's gonna have a function which is going to do is this it's going to do is local storage dot remove item user info great let's test it out if we click on this it should fire this off and let's just push us to let's say history dot push oops push to whoops push to slash route so it says history is not defined let's take the history out of react. so const history equals use history okay it's imported or not yeah it's imported let's see okay it's imported okay so it's inside of our local storage let's click on it and click on log out whoa there we go whoops so there we go let's try this out one more time so oops one two three four five six and try to log in we have our user info let's try to log out log out there we go so our user login registration functionality is working successfully in our backend as well as in our front end so thank you all for watching this video if you like this video just give it a huge fat thumbs up and subscribe to the channel it supports me a lot and motivates me to make more such videos also if you haven't yet access the playlist just go to youtube.com roadside coder and go to playlists tab and just go over here we have full mount playlist over here so you can watch the full playlist and follow along with the series so thank you all for watching and i'll see you in the next video goodbye
Info
Channel: RoadsideCoder
Views: 7,036
Rating: 4.8941798 out of 5
Keywords: user authentication react js, user authentication node js, user authentication mern stack, login and signup in react js, login and signup in react, login and signup page in reactjs, node js login and sign up, MERN Stack Tutorial, MERN Stack Project, mern, mern stack, mern tutorial, react js, node js, mongo db, Mern Stack with Redux, authentication react js node js, react node express mongodb, JWT, jsonwebtoken, node.js + mongodb user authentication & authorization with jwt
Id: iw5RSIflYGU
Channel Id: undefined
Length: 67min 3sec (4023 seconds)
Published: Wed Jun 02 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.