Angular 14/15 JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
uh Hello friends today in this tutorial we will be building a full stack project inside angular node.js mongodb so basically it will be authentication project Json web token and basically I will be showing you that how you can log in and register inside a mongodb database so this is basically the demo of the project guys you will see we have a navigation bar we are showing login and register buttons and this is our the home page of the application it is showing the current status of my you are not logged in so this is the message showing here and all this information will be stored right here inside the table guys mongodb database so if I refresh here nothing is present right here so now we need to create the account here if I click the login button a form will be shown to me so here I will able to sign in with my username so let's suppose if I don't enter any sort of information alert messages will also be shown here validation messages you will see please enter all the fields so for this we are using the sweet alert to pop-up message Library which is very famous to show these colorful alert messages so now if I enter the email but I don't enter the password you will see again it will show me the message let's suppose if I enter the password you will see this email address is not correct it will say to us that please enter a valid email address you will see that so all these validation messages we are comparing it and at the client side in angular and then showing the alert message so let's suppose if I add a add the Red symbol gmail.com so already we haven't registered any sort of email so this email is not present in the database so it will show me that user not found so you will see that guys on different errors different validation messages are occurring different error messages are showing up so now first of all we need to create account so we need to go to the register here and in register guys we have three options we need to provide first of all the name email address and the password so let's suppose I provide the name here and the pass or email address and then I provide my password so so if I enter these details guys and also let me open my application and inside you will see that let me just delete this Java Json web token so nothing is present inside the cookie here you can go to inspect element and go to cookies here and if I basically now submit guys you will see basically a brand new Json web token will be created here which will be allocated by the node.js server Express server and it will be transported back to the angular so it is stored inside the cookie here so you will see my dashboard page will be shown here this is high followed by the name which is Gotham Sharma you will see and this Json web token guys will allow use us to authenticate with the node.js backend server so whenever I try to basically in the future request if I basically open the application localhost 4200 it will automatically redirect me to the dashboard page it will automatically detect this Json web token that is present inside the cookies here you will see Json web token is already present and you can see that this token is already present so that's why it is automatically detecting in the cookie so that's why it redirected me to the dashboard page and we got this logout button also guys and if I press this log out button so what will happen this Json web token will be automatically deleted if I press this logout button you will see Json web token will be deleted and now if I try to go to the localhost 4200 you will see you are not logged in so the status will change so this will be done automatically guys uh because we log out from it so the Json web token is deleted from the cookies so that's why it can't recognize the user so it also has a expiry X expiry date guys Json web token you can set all this stuff in the source code I have basically made a similar video in the last video I made how basically we can Implement JWT authentication in node.js Express and ejs I have given the link in the description of the video you can also check out that video also this is the second video that I am doing here with angular this time and basically you will see all this information let me show you uh now if I refresh the database you will see that guys this database will be created which is node underscore auth let me see node underscore auth and a table will be created user stable will be created guys you will see this is we are storing the name here email address and we are storing the password so we are not storing password as a plain text we are hashing the password by bcrypt.js Library and you will see that and now let me log in with that user name which is uh if I enter got them at the gmail.com password one two three four if I enter a wrong password guys it will show me that password is incorrect because email is correct but password is incorrect so in that case it will show you password is incorrect and let me enter the correct password click on sign in you will see that you will be automatically logged in inside your application so this is basically the authentication system guys and now if I try to basically log out and try to register a new account with the same information that I provided last time that suppose I entered the same email address so it will give me that error message guys this email is already being taken so you will see email is already registered so all these error messages that you are seeing guys basically it is showing up automatically from the back end these error messages are returned here we are displaying it so in the console you will see basically uh these error messages you will see bad request is there 400 so basically inside our node.js if I show you the code here so these if I open the routes.js basically you will see all these error messages we are returning it user not found password is incorrect so all these messages we are unauthenticated you will see that so all these messages via email is already registered so basically we are returning all these messages and then we are displaying it inside the front end using angular so I will be showing you from scratch guys how to develop this project all the source code is given in the description of the video I have written a complete blog post step by step so if you have still errors running this project I have given all the source code in the in the full node and angular whatever directory structure I am using whatever angular version I am using I am using the latest version angular 14 and 15 so it is compatible with the latest version as well at the time of recording this video so if you still want to buy the full source code that I am using you can buy this full source code at a very reasonable price the link is given in the description of the video go check out this blog post so now let's get started by building this application we will look it in the next section uh now guys in order to get started here I will basically go to my directory here project directory and basically I will make a new directory here JWT auth so it is saying that it already exists so I will say JWT project and I will CD into this and then I will open this inside Visual Studio code text editor you will see that basically it's empty directory right here nothing is present so now guys we will first of all create two directories here first will be for the back end and the second one will be for front end so you will see we have created our two directories backend and front end so first of all I will go into the backend directory for the node.js so I will initialize the package.json file we will see package.json file is created so now I will be showing you guys for X node.js Project what dependencies are needed Express will be the web server which will be started and we also need the course module basically in order to prevent the cross or region resource sharing we will allow the angular application to basically use our API so that's why cores is needed and then for interacting with mongodb database Mongoose is needed and then we also need the cookie parser guys in order to set and read cookies so we will be storing the Json web token inside the cookies so we need this cookie parser middleware to set the cookie and we also need the becrypt library guys bcrypt JS in order to hash the plain password so we need that and lastly we need the Json web token so just install these dependencies and in the meantime guys I will go into the front end also I will open a new directory I will go into the front end and I will initialize a new project so I will say NG new JWT app so here it will ask you some questions guys you need to basically allow the routing as well so it will ask you a question that do you want to allow routing so we do need the routing here so that's why press the Y icon and for the style sheet we will use CSS so simply it will now create your angular project as well side by side so now you will see it has already installed all the packages inside your package.json file if you see we have bcrypt we have cookie parser course Express Json webtoonquer and Mongoose now we just need to create our index.js file which will be the starting point of the application so right here guys we will basically start the express server here so here we will basically write the code here so we will see const Express so here we need to require the express module and then we also need the Mongoose library in order to connect to the mongodb database and then we also need the course middleware so just require this and we also need the cookie parser middleware guys so cookie parser just we need to require this also and now we will basically one by one first of all create the app guys of Express foreign we will pass all the middlewares which is first of all we will pass the course middleware you can pass using the use function guys it's very easy then we will pass the cookie parcel middleware simply pass it and that's all that you need and in the course middleware guys so basically it takes an object here that you need to pass here it takes the credentials options which is set to true and it also take the origin option here we need to set the origin from which origin we will allow the access to our application so if you want to allow all the origins you will pass star here or if you want to provide a specific URL here you will only provide the specific URL of the angular application it will be all the angular apps runs on this 4200 Port number so we'll simply pass it so after this guys we will basically also pass the middleware which is express.json so this makes it easy in order to get the Json data that you pass from your front end to get access to this Middle River is also necessary and lastly guys we need to start the application uh at particular port number for this we will use the Mongoose Library and it contains the connect method and here we will be connecting to our mongodb database which will be running on 27017 this is a default port number of mongodb and then we will simply say the database name so here we will be providing let's suppose JWT project this will be the database name which will get automatically gets created so here you can replace your own database name and then it takes an object two properties it takes which is use new URL parser this these are Boolean properties and use Unified topology this is also set to true so now it returns basically a callback function guys so here we can say that connected to database and here we can simply start the application when we are connected we can start that you can listen on this 5000 port number and we can simply say that app is running on Port 5000. app is listening on Port 5000. so if you see now guys in order to run this application it's very easy you can simply say here in the command line so here we can say that node mod index.js so you will see that uh is saying that Mongoose prototype connect no longer accepts a callback okay I think it is saying that it doesn't accept a callback so I think we need to replace it using a done function promises I think it's saying that so what we can do is that here so we can say done and here we can say connected to database and then we can replace the code here so in the latest version of mongoose guys it is not supported so that's why that error is taking place if you once again start this option use unified topology is not supported so basically you can remove this property guys so you will see that connected to database and you can see app is listening on Port 5000. so now we have successfully connected guys and now if I check out my angular app you can also see it is also created we can CD into this CD JWT app and on the front end guys you will see the project has created this is the sample mode angular project we only need to install one package here which is the suite alert Library which I showed you the colorful pop-up messages simply type npmi Suite alert 2. this is basically the library that you will need here simply you need to install this so it's installed here so if you just type this command NG surf you will see it will basically start your application at localhost 4200 so just wait it is starting this application foreign we will create all the routes one by one for login and registration so so what we can do is that in the meantime it is starting this application we can create a new folder guys which is called as routes and here we can create the different routes which are necessary routes.js file and also we will need a models folder also where we will be storing the schema here so just make a models folder and just make a file user.js so here we will have different fields for the user the name email and password and for this we need to require the Mongoose Library and here we need to require mongoose and here we will be having the user schema so here you will say that new Mongoose and here we'll use the schema method and basically inside this we will have different fields here first will be the name field which will be of type string and it should be required so required will be Boolean parameter that's all put a comma and then we will have the email here email will also be of type string and it will be unique so no duplicate email is required so unique is true and it also is required and lastly guys we have the password as well so password will also be of type string that's all and it is required so record so we have three you can see three properties which is the name of the user email and password and then we simply need to export this we can say module.exports Mongoose Dot it contains a model function guys and here we can provide the collection name user so mongodb will automatically add s into it so it will be it will create the collection users and here we need to pass the schema here which we created in the second argument which is user schema that's all so this is all that you need to write inside this file we have automatically created this schema inside model now we need to write the routes different routes we need to write so just refresh it basically it is and for the routes guys we need to first of all require the express router so from the express dependency guys we just need to require the router package so just require it like this and then we will also require the B grade Library which will be useful for hashing the passwords we will also require the Json web token Library guys and we will now require that user model that we created in the models folder you can just import this like this and now we will basically have the router.post so first of all we need to initialize this router guys so we will say that router and we will say router like this and then we will simply say we will have different required Save which will be post request for the register route so so when someone goes to slash register basically it will be async request response for the meantime we will basically send a response here like this created user like this so later on we will basically add the code for now we are just basically having all the requests so we will do it for same for the login as well we will basically send out that login user and also we will basically have the a get request also to the user route also guys which basically this will get the information about the user and whether it it basically will tell whether the user is authenticated or not so we can say that response times user and lastly we will be writing the logout request as well lastly so we just need to module dot exports we just need to export this router and now when we do this module.exports router now we can include this file inside index.js so right here at the top we can include this file so what we can do is that we can include the router that we created so we can say routes we can say require so we can just pass it as a middleware you can say that app.use routes that's all so this is all that you need to do guys and once again sorry we also need to provide a route sorry path here also we can also customize it using let's suppose you can say slash API so each and every route will have this endpoint firstly attached to it slash API slash register slash API slash login slash API slash user this is meant by this you can customize the routes here by adding this property so now guys if I basically refresh my application and if I you I can basically use this tool called as Postman this is a open source tool if you don't have a front end we will create the front end but for now let me just test this so our application is running on localhost you will see it is running on Let me refresh this 5000. and if I make a post request to login click on send it is saying that cannot cannot post slash login sorry our API or slash API login slash API slash login so you will see this basically it returns whatever message that we send right here if you see login user so if I go to slash register it will say to me created user so our endpoints are working guys I am just showing to you slash register you will see created user and if I go to slash user you will see sorry this was a get request so user is returned to us so all the endpoints are working guys that we showed here now we simply need to basically write the code here in order to insert the data inside the database so for this guys first of all we will tackle the register route here instead of returning created user basically we will get the information that the user has written so here we will simply say slash for the slash user basically here we need to first of all get all the things here we can get using request dot body dot email so this things will be sent by the inside body so here first of all we will get all the things that the user say we can get the email like this request.body.email password is request.body.password and we can even get the name also like this request dot body Dot name so these three things we got inside these three variables guys and now we can first of all simply without putting any sort of validation we try to basically uh insert this inside the database so what we can say uh new user this is a model class and here we can pass three options here which is the name here request.body.name and email is email sorry password is password so let me just just replace it name here so we are passing these three things guys we have created these three you will see name email password so we are passing it right here so now to save these details guys it it is very easy we will say await because this is the async function so here we can simply say that user dot save so we can invoke this save method this will simply save these details inside the database and now we can simply return out a response to the user like a Json response and here we will have a message property or we can return simply ID of the user so ID will simply be result.id so this will be the automatically generated ID of the user which is automatically generated so now what we can say is that or we can even say the user we can return the user here like this the full user which will contain all the three properties so if I basically now test this endpoint I go to postman basically I make a post request and I say that HTTP localhost 5000 slash API slash register and I go to body and here you need to set your this rotation just set it to Json and in the headers you need to write this content type application Json so these you need to do this so inside the body we will basically pass the name property as well so put a comma so we have passing these three properties name email and password if I click Send here so it is saying that cannot read property email of undefined let me check guys what is the problem uh guys I figured out the problem here so just go to index.js so we have put this line here which is app dot U slash API routes so this line needs to be put after this after we apply this middleware function which is express.json so just you need to copy this line and simply paste it just after that you write like this so simply paste right here the ordering is very much important so now we can use this middleware which is express.json so now if I go to postman if I make that request let me just make a new request here select post request and then we will say http localhost five thousand slash API slash register and here I will go to body and select raw and then I select here Json and here I select sorry pass three properties name let's suppose I say ABC email I pass here ABC at the rate gmail.com and then I pass the password uh one two three four five six click so click on send guys you will see that automatically a user is generated or user object is generated we have seen name email password so we are not hashing the password it is storing plain here if I check the database reload it you will see one database will be created with a JWT project if you see right here you can see JWT project users table will be created and we have this record ABC ABC gmail.com one two three four five six so now our registration process is working now we simply need to Hash this password so now we can simply do guys we can apply a b Crypt Library which allows you to hash your password this is very much useful so here right here you can create before we insert our password we can create a hash so here you can create the salt here we can say that await B Crypt and it basically contains a method generate salt and here we can create the salt 10 characters and then we can say a hashed password and then you can again use the bcrypt and it contains the hash function guys and here we can simply pass the password that we got this is original plain text password and then we will simply mix it with the salt that's all so after this guys you can simply say instead of the password we will replace it by hash password that's all you will see that now if I do the same thing if I again go to postman and this time let me delete these record here let me delete this so now no record is present so if I again send this request so now you will see that guys the password you will see it is successfully hashed here nobody can see the password it is successfully hashed if I refresh this database you will see the password is hashed here so in this way guys you can hash your password and now we simply need to uh apply one other validation guys let's suppose if I register it for the second time so basically it will return me the error here you can see that duplicate key error email must must be unique because we put that property guys you will see right inside our user.js because email should be unique so you can't register same email twice so that's why it is returning me the error so now we can simply pass that error to the front end so we will be showing that error inside the postman and later on in the angular front end so how we can do that it's very easy basically what we need to do here inside this register request so whenever you do this we created the hashed password we can basically create a record variable and we will basically find out user dot find one it contains this method find one and we will basically pass the email here so whatever email is there we will basically find out the user whether this user is already present whether this email is already present inside the database if this is mashed here if the record is available in that case we will return it simply a error response dot set status 400 and we will send out this error guys which inside this message variable but email is already registered now guys you will be seeing a specific error and in the else block we will simply say we will execute this code that's all so you can see that we have put a if condition here we are checking it we are finding the user whether this user already exists if it exists then we are simply passing this message to the user so if I try to register it with the same email address guys now let I just need to refresh my application just restart this and ABC at the red gmail.com is already present so you will see email is already registered so this this message you can display it on the any front-end JavaScript angular view JS reactors we will be displaying it in the angular front end so this is basically I think is complete register request and we just need to basically uh set the token we after we create this response guys after we save this we just need to create the JWT token which is very easy we can say that first of all we can extract the ID from it from this result we can say await result we can convert this into Json so after extracting the ID guys you can simply create the token we can use the sign method of JWT as you can see we are importing this Library Json web token and we can sign this token guys we can pass the ID property here so whatever ID is there and here we need to provide the secret key guys so this secret key you need to store it in the protection in this environment variable or a very secret location in the production but I am just showing you like this so this will be the secret key so after this guys we need to set the cookie so we'll say response dot cookie and here you can name this as anything but I will name it as JWT you will store the token and then it take the third option which HTTP only is true and the maximum expiry age of the tokens so we will be setting it for one day so after one day this will be automatically gets expired and deleted so this value in it is in seconds so 24 divided by 60 divided by 60. I think it's this is in millisecond so this is so that's all guys that you need to do so we can simply send out this message send this message is not required but we just need to send it the success message that's all this is basically the uh backend register route guys now we can go to the front end and basically complete this and I need to do step by step once I complete one request in backend I will be showing you inside angular front end so just go to your app folder guys you will see that this is basically the application if you open localhost 4200 this is your angular application you will see that this is brand new angular application now first of all inside this application guys what we need to do we need to create four components namely this will be home navigation login and register so I think you will be knowing how to create components inside angular if you don't you can execute this command which is NG generate and then we say component followed by where we need to create this so when say component slash home so now this will create the home component guys you will see it will create a brand new components folder and we will have basically the home component and similarly we need to create the navigation component guys also this will create the navigation component and also we will have the register component and also we will have the login component so simply create these four components so it will get created you will see so we have home we have login we have navigation we have register so now the second part is guys we need to open this file which you see app dash routing dot module.ts file so now we need to implement the routing as well so whatever routes that you have configured inside this array we need to Define all the routes so we have a Path property here so when we go to the home page when our user goes to the home page the home component will be get loaded you will see automatically this will be there components home home component so visual studio makes it very much easier to do this process and then we will have the second path guys which will be if you the user goes to the slash login this component will get loaded which is the login component login component you can see and similarly we will have the path for the register as well so when I was user goes to the register component this component will gets rendered which is register component so you can see that so all these three components are loaded here so that's all that you need to do inside this file guys so navigation will be constant in all the three components so that's why we don't have the path for that so now you need to open the app.module.ts file guys so for this you can see all the components are automatically included by visual studio so once you created those commands so we do need two components guys two modules which is the forms module and the HTTP client module so here you can import the forms module from angular forms we also need the reactive forms module as well so simply require that and then we also need the HTTP client module as well guys so HTTP client module so this will be coming from at the rate angular slash common slash http so after this you need to Simply add them inside your includes array forms module and HTTP client module and reactive forms module so you can see we have added these three properties forms HTTP client and reactive forms so I think that's all that you need to do right here inside this file so simply close this file and one more important thing that you need to do guys you need to go to tsconfig.json file and right here we inside your compiler options you need to add a property here which is very much important which is let me show you uh I think this property is strict strict property initialization so this you need to make it false so just make this property so this is a very important property guys if you don't add this your project will not work so simply add this tsconfig.json simply close it now you need to Simply go to your app.component.html file simply delete all that stuff and now we will simply include the app.navigation component at the top so inside like this and then we will have the main tag and inside this we can say router Outlet so we will be displaying the routing Pages whatever we configured you need to give it a class form sign in and also guys you need to go to index.html and for this we need the bootstrap we are using some bootstrap also so you can need to include the bootstrap CDN so simply you need to bootstrap CDN and include the bootstrap CDN here so simply you can grab this CSS only we need so just after this paste it and now in I have given that code app dot component.css guys this is custom styles that we are added so you can go to my blog post and we have I have added the CSS code which is required for this application so I think it is given right here yeah this is a code here so very less CSS code is there simply add this so now if you open your application angular app just refresh this and let me just start this NG surf so it is just starting this application so just wait you will see it is started you will see this is a navigation component guys it is staying and this is a home component now if I go to the login component here slash login this is a login component you will see login works if I go to slash register this is basically the register component you can see navigation will stay constant right here at the top here because we included this inside our app.component.html file at the top but these three components will change depending upon which endpoint that you write in the address bar and now we will need to first of all just create the navigation component guys this is really important navigation this will have some bootstrap classes guys navigation bar navigation bar expand MD navigation more dark background will also be dark so these are some of the classes of bootstrap so we also need to say margin bottom four inside this we will have the container fluid class or bootstrap you will have a router link property so now to link Pages we have the router link attribute that you need to write you will give it a class nabd or brand page so this will be the home page so if you go to click this it will redirect you to the home page so if you just refresh this application so you will see that now we have this home page you will see that nav bar expand dark BG dark mb4 and then inside this guys what I will see guys I will simply paste this code this is just the HTML code I am not good in HTML and CSS that's why so you will see that basically we have two buttons out there the login and the register button if you refresh this you will see we have login register uh you can see that inside I think I've copy pasted this inside index.html we copy pasted the CDN so I think why it's not let me just see guys why the styles are not seeing right here uh hi guys I figured out the error guys because if you see inspect element bootstrap is not loading here if you see inside console nowhere else is there but you need to set a attribute called as cross origin Anonymous so whenever you include this inside your angular apps just need to include this cross origin and Anonymous so simply include this attribute and if you refresh this still will it will not work so I will say that so I have whatever I pasted the CDN this CDN seems to work so you go to my description of the blog post simply copy this CDN simply replace this so I think that bootstrap CDN is not working so simply include this so if you now refresh you will see it will work here so we have the home page so if you go to login it will go to slash login if you go to slash register it will work here now we need to show the login forms guys if I click login and register this is really important and now first of all we will tackle the register form just go to the register component dot HTML so right here guys you will have a simple form element and we will basically have form group this will set it to form you will also be having a submit event handler so when we submit the form this function will execute so here we will have a H1 so again these are basically classes guys so I will simply copy this code you can get this code from my description so namely we have three Fields name email and password so we need to give it these form control name this is really important form control name to each and every input field so this is placeholder placeholder placeholder these are all bootstrap classes and we have a submit button so now we need to write the submit function guys so once we click this button so we need to go to register component dot TS file and right here we need to Define this so for this guys we need that form group form group dependency so right here we need to import that so we need to say import so this will be coming from angular forms this form group and form Builder so after you do this we have to have a Constructor inside this we will pass these three properties first is form Builder which is of the type here form Builder then we will have the private http client so this will also get imported you can see that so just do it like this and third will be the router guys this will also getting imported from angular router you will see that so these things you need to pass inside the Constructor guys and now we need to write the NG On in It guys uh let's just this is basically the life cycle method of angular so inside this we will simply say this dot form Builder dot group we will initialize and reset the fields here like this name emails and password so for this we just need to implement uh just write this implements on in it just add this so we need to import on init from angular core here like this so after you do this guys we just need to write that function once we submit the form this function will execute and inside this you will get the values whatever user right using this function which is get raw value so if you just console log it inside the browser if I refresh this application you will see basically the form here and if I inspect element and if I go to console so if I write any values here you will see a object will be created and hopefully you can see that this is email let me just elongate it you can see we have an object it contains three properties email name and password so we can now easily capture these properties guys and pass it into the post request so first of all we need to validate these data so how to validate this we will have a simple if condition that if user dot name is empty or user dot email is empty or user.password is empty in either of these cases guys we just need to show a alert message to the user that please enter all the details so for this we need to import the sweet alert library right here at the top we will say sweet alert from so just import this module guys and right here we will use the fire method and inside this we will simply say I think this is a basically a method here and we need to say title will be error here we will Define the error message please enter all the fields and this will be the error message so you will see guys if I basically don't write anything here and if I try to submit please enter all the fields you will see that this message if I enter the name what if I don't enter this again you can see that I need to enter all the things now this message will not show we also need to do guys if this is the email field here so if I enter an invalid email address if I don't include this at the rate symbol we also need to show a alert message so for this we need to create a separate method guys which is a you just need to make this method right here at the top which is this validate email so it will have check this against this regular expression and it will basically return either true or false so now we can use this method inside we can simply have a health safe condition so we can say validate email and we can simply pass the email address you can say user dot email so basically if it returns false we can put a not sign here in that case we can say please enter a valid email and in the else block if all the details are correct guys in that case let me just show you the alert message now let's suppose if I enter a wrong email address please enter a valid email you will see that if I correct that email address you can see that nothing happens so now if all the details are correct guys in that case we just need to make a HTTP request this dot HTTP and here we will make a post request and here you will see http localhost so wherever your back end is running so our backend is running on localhost 5000 slash API slash register and we will simply pass the values which are distort form Dot get raw value so we already store this inside the user so we can simply pass the user variable which is an object um we also need to pass this third option guys which is very much important which is with credentials with credential sorry so this will automatically send the Java Json web token in the cookies so we just need to set it to True with credentials it's very important option and now this will return we need to subscribe to this method so subscribe this will return either the response so here you will simply distort router we will navigate redirect the user to the Home Route so here you will say slash and if any sort of error takes place in that case we will display the error message like this error error message that's all so you can see if any sort of error takes place we are displaying the error message error message if you check my backend API if you see uh if you check basically the back end API guys so here inside routes inside our register request here if any sort of error take place we are sending it we are sending it this object here which basically contains this property message so you can see that this message property we are sending so that's why basically we are showing this property right here error.message so if I try to refresh this application guys and if I try to register and let's suppose already one record is present here ABC at the rate gmail.com is already present in the database if I try to enter that email address ABC at the rate gmail.com one two three four five six you will see email is already registered so you'll see this error message will be there I need to basically give it a ABCD click on submit you will see it will redirect you to the home page and if you check your basically the cookies option go to application cookies you will have your JavaScript sorry Json web token created this is a Json web token it is automatically gets created and once you close this window guys again open this this will be valid for full one day again this will automatically detect and it will redirect you to the home page this is registration process complete guys now we need to Simply tackle the login process so this is the registration process complete and now we simply need to put the login process and one other thing guys we also need to show the logout button here instead of login and register button because we have successfully logged in so for showing that we need to go to the Home Route because we are now uh if you see we are basically uh navigating or redirecting the user to the Home Route we now we need to open the Home Route here guys just go to home dot component dot TS file and here we need to write some code so inside here we will basically display the information of the user so message we will declare a variable you will have a Constructor and here you will be basically be having HTTP client it will automatically get imported and here we will basically NG On in It guys we will inside this life cycle method we will basically make a get request so just implement this on init just import this and basically guys this we need to make a get request here this dot HTTP code get and here you will be having the address HTTP localhost 5000 slash API slash user so here we will putting the details guys with with credentials true so once again this will pass the Json web token in the cookies automatically with the single option and then it will again we need to subscribe to this method so whatever it returned to you response we need to cast to any so here we will say this Dot message is equal to we will use by vactic symbol Hi and then we will simply say response.name so you will see that so we need to Simply here so now guys basically we were there you will see we are printing out the name here of the user which is currently logged in so we will simply write like this inside backtick symbol this is response.name so this will basically print out hi followed by the name of the currently logged in user and now let's suppose if any sort of error take place we put a comma here and we put any sort of error take place so what we can say is that here this Dot message and here we can simply say the error that's all so now guys we just need to make this method which is slash API slash user inside our backend to detect whether this client is authenticated or not that we are having this request so now we need to go to routes.js so we have put this route uh we have made this post request of register similarly we need to make this request of user slash user so here we need to return the details of the currently logged in user inside this request so first of all we need to or surround all the code inside try catch block so here first of all we will get the cookie here of the browser of the user browser we will get the cookie using request dot cookies and here we will get the value JWT we will get the token and here we will simply say claims and here we will verify JWT verify and we will verify the cookie here value against the secret key that's all so now we will have a if condition if the token is correct we have put a not fine guys so this simply means that if the token is not correct in that case we need to return a message to the use of the with the status of four zero one which is non-authorized so in that case we will send a message to the user that on Earth unauthenticated that's it so you are not authenticated to access this page so here we will simply if the user is authenticated if the token is authenticated then we will get the user detail by user find one and here we will pass the ID of the user which is claims.id like this so we will get the information about the user so just make this as async function guys because we are using a weight keyword here so this will get the information about the user so we will extract by destructuring it the data about the user we will say We'll convert this into Json by using the user.json like this and then we will simply send out the data that's all and if any sort of error take place guys in that case also we will simply say message unauthenticated that's all so basically this is a request guys so let me summarize this firstly we are checking the cookie JWT token whether it is present inside the user browser or not then we are verifying it using JWT verify method if it is not a correct token then we are returning a message that you are not authenticated user and then we are simply finding the details of the user and sending the details about the user that's all response dot send so that's all guys that we are doing this and after this we need to go to our component here which is home.component or TS file and right here we just need to display the details here so we were displaying the details so let me just see if any sort of error takes place here we can display a message here that is you are not logged in customize message and now if I basically refresh the browser guys so what you will see right here if I see if you go to the home page it will simply say homeworks because we need to replace this message we haven't replaced this message so we need to replace this message inside home dot component.html it's right here instead of this we will simply replace the message inside double curly brackets that's all so just replace this guys and now you will see you are not logged in because if you inspect element the token is not present the token is present but it's not valid and if you now basically register now if I register with this new name I say email address click on submit you will see basically JWT and you will see basically the token is created and still it is saying that you are not logged in I think it's somewhat a mistake is there let me see what is the mistake here uh home dot component.ts file I think we need to refresh the browser guys for the application to work so just refresh this application oh so I think we need to again if I refresh this so if I provide a name so this sorry name email is already taken so let me change this email address so again this message is popping in that you are not logged in let me it returns a object here which contains these three details thank you let me see guys what is the problem here uh sorry guys I figured out the error it was a very silly mistake you will see the port number that I replace 8 000 I need to replace it 5000 because my application backend server is running on port number 5000. so just replace it and now if you try to register a new user guys and if you see the message will change High followed by the name let me again register here with a new name this name and this is my email address provide a password you will see in the application this again a new token will be generated and this is your name hi followed by the name and now we also need to show the logout button guys instead of login and register button if you close this window again if you go to localhost 4200 it will once again redirect you to the you will see that now we need to basically show the logout button so how we can do that it's very easy so right inside your home component.ts file we just need to create emitters if you don't know about emitters guys inside angular basically it's a way by which uh multiple components communicate with each other so now we need to tell the navigation component that the user is logged in you need to show the logout button for that we need to basically create a new folder which is let me create that folder inside the front end inside the app folder so in the in this folder I will create a new folder called as emitters so this file will be a simply ammeter.ts typescript file so this will be a slightly just two lines of code we will simply import event emitter and this will be coming from the core library of angular and we just need to export this class guys which is emitters and we will have a static property of auth emitter new event emitter so we will have a Boolean parameter here Boolean so you can even just transfer string value as well here you can also transfer number value but we will be transferring the Boolean value from one component to another component so this class we can use inside our home component so what we can say inside homecomponent.ts file so right here what we can say after this whenever response is there we can simply say here inside I think yes we can basically say ammeters so you can see the class will be imported from The Source app emitters emitter automatically and it basically contains this property static property that we defined here auth emitter and it contains a method Amit and we will be emitting true in this case a Boolean value because the user is authenticated if the error is there in that case you will be emitting false false that's all this is a very simple logic guys so if the user is authenticated then we are transferring this emitting this value which is true and if it is not logged in we are emitting false now we need to catch this value we need to subscribe to this event emitter so now we can go to the navigation component here navigation folder go to navigation component.ts file and right here we can subscribe to this event so it's very simply we will create a variable here which is called as authenticated by default the value will be false we will have a Constructor it will be private HTTP of the type HTTP client automatically it will get created and then we will again have this NG on in it this will be of type void so we will implement this on init [Music] so just import this so inside this function guys we will basically subscribe to this emitter start auth emitter dot subscribe and whatever is the value inside it Returns the value of auth which is of type Boolean so we will make this value authenticate this dot authenticated is equal to auth that's all so whether it's true or false depending upon that now we need to use this value guys inside our navigation component dot HTML file we just need to add this if condition here mg if right here so star ngf we will add this condition based upon so if the user is not authenticated we will put dot symbol here authenticated then we will show the login and register button if they are authenticated in that case let me copy this paste it one more time if they are authenticated then we will only show one button here which will be log out button so simply replace here log out and we will go to slash logout for the logout button that's all this is all that you need to do guys we have added this mg if condition guys depending upon the authenticated value not simple we have added false we are showing login register if they are locked in we are showing logout button so so if you now refresh here guys you will see automatically this are showing the logout button here the user is currently logged in and now if I press the lockout button nothing happens because we need to implement this functionality so this is very simple for the logout button uh this is a simple command here we are basically executing this function log out let me see here slash login and we also need to add a on click to this so just click on click so when we click this button guys basically we will execute this logout function so now we just need to Define this logout function guys inside navigation component.ts file so we will basically have this function so log out and inside this function guys we will basically make a HTTP post request to the endpoint that we will create right now HTTP localhost 5000 slash API slash logout and we don't need to pass any sort of data to it so empty parentheses sorry curly brackets and here we will pass the authentication Json web token with credentials to true and we just need to subscribe to this method and inside this guys we will simply say this dot authenticated dot is equal to false that's all we just need to make like this so after we make this post request so we just need to make this post request inside of a back end go to routes dot Js so this logout will be very simple uh let me just write this uh this one yeah let me make a new request here router dot post so someone makes a logout request we basically simply delete the cookie here so for deleting the cookie guys we will once again set this JWT and we will simply make the expiry date we will set it to nothing and max age we will simply say to zero that's all this is it will delete the cookie after that we can simply say message success simply it will log out the user and if I basically now refresh the browser if I click the logout button it will redirect the user to the home page just refresh this click on logout you will see the user will redirect you to the home page I think I think we have made a mistake in navigation component.ts file so what we need to do is that we we have created this dot authenticated when we click localhost 5000 API logout with credentials to true if you check your application you can see that it is gone here it is no longer present the cookie is not present if I once again register here if I change the email you will see now it is JWT is created if I click log out it will be deleted here from the cookie but still this message is appearing right here I need to change this to you are not logged in so let me see guys why it is not appear guys I figured out the problem here because there is no router link available such as log out because if you check inside your router file basically app dot app slash routing module.ts there is no route such as log out so we need to redirect the user back to the login page once we log out so that's why here inside your navigation component.ts we just need to replace here slash login so once we log out we need to redirect redirect the user back to the login route so just replace here slash login so if you basically now refresh you will see you are not logged in and let me try to register a new user so we will see JWT token is created if I click logout you will see it will once again redirect me to the login page and now you will see you are not logged in so if you click home you will see you are not logged in you will see that the status changes and if I again refresh you will see the state changes now we simply need to implement the login form guys so now we need to allow the user to login so we just need to go to your login folder login.html so here we just need to replace a simple form guys and similarly what we did inside registration we need to do the same thing for the login as well so we have a simple form guys we are executing the submit method and we have two Fields here email and password we have a button so if I refresh it it will say this function is not defined so we need to Define this function so we just need to go to login component.ts so here we will first of all Define this function so once again we will have these properties that we written for the registration form as well so we just need to import this all that stuff so right here at the top we just need to import that import HTTP client and also we just need to import the router as well so so angular router sorry so you will see we also need the sweet alert Library guys for showing the pop-up messages so after this guys we uh we just need to implement on in it so here we can simply say all in it so for this it will need to implement this method and G on in it so inside this method guys we once again need to do the same thing we will reset the values so we will initialize the new reference of form Builder you can see email password so we just need to Define that submit button guys submit methods which will get automatically called if you see now we have a sign in form guys so we allow the user to Simply enter the email and password so before we implement this we simply need to write the route guys go to routes.js and inside this we will simply write the record for the login process so this is very simple this backend API request is very simple for this we simply need to first of all get the user we will simply use a weight here because it's a async function you will first of all find out about the user by using again this method find one we will pass the email address which the user has passed using request.body.email so if the user is already present if the user is not present in that case you will simply say that status we will say 404 we will send out a response back to the front end that this message that user not found that's all so this is very very important we are checking if the email is present or not then we will compare it for the passport if the password doesn't match then we will simply here we will simply say await we will use the decrypt Library guys we will use the compare method you will pass the password that the user has supplied we will compare it with the hash which the user has stored user or password if they don't match in that case we will return a message again that status this time the status will be 40 400 this will be unauthenticated so your credentials are wrong so here you will say password is incorrect so now guys if all these conditions are true in that case we have a uthenticated user will simply sign the JWT Json web token with the ID user ID like this and here we will supply the secret key secret key should be constant guys in every secret jwd token that you sign it should be constant and then we will be setting it inside the cookie JWT and we will set the token and we will provide the this one to be true and maximum h this will be 24 divided sorry multiplied by 60 multiplied by again 60 and this is in millisecond for this is for one day you can change it for any day of your choice three days five days and then we can simply send out a success message to the user that's all this is simply your login route so now we will simply go to our login component.ts file guys and here we will simply try to pass the information through the form so here what we need to do guys so we do we need to do the same thing once again which we did in the register form so we need to Define this validate email function so if you don't enter email address or password you will show the alert message so we are doing the same thing so if all the things are correct in that case we will simply now make a simple post request http post and http localhost 5000 slash API slash sorry this is yeah this is the one so here name is not necessary sorry yeah so here we will make slash API slash login and here we will pass the information which is present inside user and the option will be with credentials to be true it will pass automatically the Json web token and then we need to subscribe to this so whatever result is returned to you we will simply redirect the user desktop router navigate we will navigate it to the home page you will see that and then if any sort of error take place in that case we will simplify a message we will say error error message and error that's all so login functionality is also complete guys so now if I try to refresh the browser and if I inspect element go to the application you will see nothing is present here no JWT token is there if I try to basically enter a email address which is present inside a database let's suppose KBC gmail.com I write but I don't write the correct password in that case you will see error message will be popping in password is incorrect if I write invalid email address user not found you will see and now if I write a correct email address and if I enter the correct password in that case you will see you are not logged in I think first of all we need to register here let me register it with the correct one two three four five six you will see that iqrt and now if I login it with the same name add the red gmail.com so it is telling me that you are not logged in it is saying four zero one unauthorized uh let me see guys here just wait guys I'm just looking at this uh guys I figured out the problem here there was just a typing mistake inside my backend request here the front-end code was correct so you just need to go to the description of the video and basically just type the exact code here router post login and there was just a mistake typing mistake typo mistake so I just copy pasted the full source code from the blog post and now if I refresh here you will see the application is running smoothly so if I try to basically log in with the correct email address ABC gmail.com one two three four five six click on sign in you will see this page is saying hi ABC and if I close this window if I directly go to localhost 4200 it will detect here I ABC we have a logout button if I click logout you will see now we are log out if I go to this you are not logged in if I want to register a new user I can register it put a name put a email address put the password so this is your application guys the node JWT authentication system with angular 1415 as the front end this is a full stack uh application so hopefully guys you should like this video if you like it then please hit that like button subscribe the channel you can go to the description of the video to get all the source code I have written a complete step-by-step blog post if you do want to purchase all the source code with directory structure all that stuff whatever version that I used you can purchase the full source code if you face any sort of problem and I will be seeing you in the next video
Info
Channel: Coding Shiksha
Views: 6,608
Rating: undefined out of 5
Keywords: angular jwt auth, angular express jwt auth
Id: F5CZNI4Kbj0
Channel Id: undefined
Length: 88min 21sec (5301 seconds)
Published: Sat Apr 01 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.