Building Node.js APIs with Express and MongoDB | Flavio Oliveira | Skillshare

Building Node.js APIs with Express and MongoDB

Flavio Oliveira, Web Developer and Instructor

Building Node.js APIs with Express and MongoDB

Flavio Oliveira, Web Developer and Instructor

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
29 Lessons (4h 18m)
    • 1. 1.1 What is Node?

    • 2. 1.2 About the Express Framework

    • 3. 2.1 App Structure

    • 4. 2.2 Code Quality

    • 5. 2.3 Database Setup

    • 6. 2.4 Configuration Driven Application

    • 7. 3.1 Routing Bascis

    • 8. 3.2 HTTPie and Postman

    • 9. 3.3 Resources Router

    • 10. 4.1 Basic Structure

    • 11. 4.2 CRUD: Create

    • 12. 4.3 CRUD: Read

    • 13. 4.4 CRUD: Update

    • 14. 4.5 CRUD: Delete

    • 15. 4.6 CRUD: Profile and Dashboard

    • 16. 4.7 Choosing What to Display

    • 17. 4.8 Hashing Passwords

    • 18. 4.9 Model Validation

    • 19. 4.10 Model Sanitization

    • 20. 4.11 Challenge: Create New Resource

    • 21. 4.12 Solution: Create New Resource

    • 22. 5.1 What is a Middleware?

    • 23. 5.2 About Static Files

    • 24. 5.3 Handling Errors with Middlewares

    • 25. 6.1 JSON Web Tokens

    • 26. 6.2 Authentication

    • 27. 6.3 Authorization

    • 28. 6.4 Role Based Authorization

    • 29. 6.5 Refactoring Code

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

Learn how to use ECMAScript Modules in a Node.js application. We will start from changing Node's module system  and step by step you will learn how to create applications with the Express Framework and MongoDB.

You will learn how to do CRUD operations (create, read, update and delete) on MongoDB using Mongoose. You will understand how model associations work in MongoDB and you will also learn how to sanitise and  validate user inputs.

We will learn how to authenticate users while learning about JSON Web Tokens. We will also cover role-based application end points, like "admin only" area that can be used in a plethora of use cases.

You will learn how to properly setup your development environment using best practices, covering things like: 

  • How a config driven application works

  • Use Linters (Eslint) and Formatters (Prettier)

  • How to automatically seed your database with thousands of entries while in  development

  • Get your application ready for deployment

Throughout the course you will use only the latest Javascript features shedding off the unnecessary boilerplate from previous versions of Javascript and Node.js

The course is divided into:

  • Coding along

  • Challenges

  • Sandbox (how it works). 

So enroll now and lets get started.

Meet Your Teacher

Teacher Profile Image

Flavio Oliveira

Web Developer and Instructor


I am a web developer and code advocate, passionate about programming languages such as JavaScript, Go and Rust.

I've learnt to code about 17 years ago (HTML). It started as a hobby and for the last 5 years coding has been my full time profession. My focus is on the Node ecosystem and it's integration with modern front end frameworks. 

Currently I work as a freelance web developer while I continuously learn new stuff and technologies. I'm also an online coding instructor here on Skillshare and on Youtube.

My main focus is on practical teaching and I will help you to take your skills to the next level through real-world projects. 

I think coding should be a basic skill taught as early as possible. It is a s... See full profile

Class Ratings

Expectations Met?
  • Exceeded!
  • Yes
  • Somewhat
  • Not really
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Your creative journey starts here.

  • Unlimited access to every class
  • Supportive online creative community
  • Learn offline with Skillshare’s app

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. 1.1 What is Node?: for a start coding. Let's take a look. How old words Take a look at the boats description on its upside. It says here this and no use and even know blocking your mother. Let's take a look at what that means, but open my term now, and I'm gonna get to my desktop and create a folder. Call it son books. I'm gonna open this and box in my cozy editor. Now here, I'm gonna create a fire call synchronous but yes. And to better understand, we need to learn about the a synchronous coat and asynchronous. So I'm gonna first create us some synchronous cold. Basically, I'm just gonna Consul. Awesome stuff here is enough. Just going to look this. I'm gonna read from my disk some stuff which is gonna block them. The flow. This is gonna be executed the first than the second. Then the turds. Let's do something that is gonna take a while toe. A process which is reads director sink from the fs module, the fs module. It's one of the model that's come beauty in note. We're going to learn more about it after, so here I'm reading from my disk. My home folder when I open up my terminal and I'm gonna run this cold over the common note synchronous And now, as you can see it before regime reading from the disk and after reading it visited the first, the second and the third in order. But if fingers you don't want your application toe stop every time that there is a B I request or something that is gonna like processing image on the background, So the way then those works, it creates a callback for every event when death Quebec, it's don't processing. We were turned to take you. So let's already this coat now in Ah, a synchronous manner. I'm just going to create a new file called asynchronous. You're just gonna cut this same that's we're having here. But here, instead of this console log, that's great to go back to represent on notes workflow. So, fs this time I'm gonna use read director, I'm gonna you Olynyk So that's the way my home folder looks like. If you are windows, you use this sea or whatever folder you want to display. So, uh, Quebec takes on their first and then on whatever that you're dealing with. I'm gonna cause a lot of that data back. Plus put some message over here. So now if I run this called again note they sink, as you can see before reading after reading and then reading from pump folder. So this event was executed when it came to this one. It create this go back and then went down on the for the next event. And after this Quebecers processed, he returned to the Q and was displayed. So is that Event river for every event he creates a callback which is gonna allow it, Not the block. They work, they float. So let's take a look at another things. We use this offense library, and this is one off many off the libraries available to us if you go on docks and then on the FBI here on this side where you can see a bunch of other modules that can use you gonna use the age to be, you also use the euro. Let's take a look at this year I'll and also their age tipping. So I'm gonna close this one's and here I'm gonna create a new file court. You're ill. Yes. And this basically what it does. It allows us to read from the front of your ill. So you're require your all what a great variable. And I hear we're gonna use a method that comes with them. Your oil module and I'm just gonna feed it. Ah, your oil. Whenever you get like a interrogations Mark, whatever is after it means is aquarium. You have, ah, the main domain protocol that was used like either HDP or is to be s or F T B or S and P whatever. So I'm gonna call select some staff. So 1st 0 the protocol, for example, let's to all of them with permission. So critical is the host. I said curry. Now, if I, uh, run this court No, you're ill. You haven't. He allows you to break down the royal and picked information you like you want. So these methods that we used over here toe grab this information, you can get them over from the royal module. Here, your fuse, girl doll, you got your ill. And here we have the host name the host used and the political. So let's take a look now in the H dip in which is gonna be awesome. We use it to create a Web server. So basically, I think that's one of the most important once from the ones you're going to be using server dot Js you have another. The same from the data is to be viable and required. And, uh, basically how it works. You create a server with the H two b creates sirve, and this comes with the baby. Here we create the function that's gonna receive a request and response. So users ask for something. The server, You think this request does something and the response, and then we need to tell it to listen and give it a pork to open up a connection in our browser. So this is the basic structure for unload server. So let's console log something. None of the requests the request comes with a lot of information. That note makes available to us if you run this cold. So no server. Nothing happens because we did not send any feedback with this console logging the request . So if you go to your brother and go to a local host Colon 8 80 any press enter, you see that nothing happens but your browser is, uh, hanging. If you go back toe, you're germinal. You're gonna see a big objective here. And when you go up, you see incoming message. And this subject is full of information that this you can use in our application. Let's request something so we can future out that information. You're gonna do that you're ill so before as well and for Bethany to restart the server. And when I go back to my browser overload here, I'm getting there. No service slash. And that's because I'm on among the roots. The minister is the route. But if I goto users and the press enter, see, I got the users over here. So this is just one of the many information we can get out of the request, which is importa. Let's take a look at the response again. Are you restart the server? No, I mean that there is no response. This console log. Sorry about that night five reloads. I get that big object again, but this is ah, server response. Right now we just conserve walking this, But let's see, how can we send back some information? Your response, But and and the here is gonna terminate the the event with the response so you can have anything a resource or you can even put that string. I think there did cover a Hell Awards. Now, if you run this and you go toe the page and refresh, you see hello words. So whenever you use the response dot and this will terminate the event and whatever you add under, we're not run. So if you close and start there you go, you got there. Hello words. But you don't get the other one If you move this one up and then I reload the serve again Well, I'm gonna save it. There you go. So these will terminate the connection with the response. Now, let's take a look. How can you build something a bit more meaningful than these? I'm gonna greater if block And here I'm gonna take the request. No. Zero. And if the request is equal so the root I'm gonna do something. If not if the request is you're our is equals toe. Let's say about Oh, there's something else. So here, let's dio response no end because we're gonna march. That girl is gonna send this response we're gonna use, Let's see Homepage here, I would say about Paige. And now let's create one that is going toe cut everything. If there is nothing, we were send up, not phones back. So let's try it out on the seven. I goto the browser, and if I run, I get the home page you have about and, uh, any route that I go that doesn't exist. You're being no phones. So this is a little basic Rati with notes Web server. Now we're gonna take a look at express. But before I go Oh, let's talk about the required here. So the common Jess this require it was this part of the community s which was created when no did. I had a way to organize files like on the Web. They have the script dance, which you can just use it to link your grants five to another JavaScript five. But the thing is us greater because no dinner had a way to do these things. But the problem is, that is, it's not part of the EC. My script that's 39 in 18 79 which the group that controls on JavaScript like they do the features we're using today and tomorrow. But they have a proposal going on, which is the proposal dynamic in parts you can take a look if you like on the Ripper. Start their replies that TC 39 you can find basically is gonna use that you can use our imports like that instead of using their require which eventually they required. And the Kama Jesse's gonna become absolute. And it's also because it's second time. So for this course, we're going to use the USM, the S and much of the proposal, as you can see here, is currently and State Street, which is not supported in note yet. But we have this library coat. Yes, him. It was made by the guy who created low dash. Let's take a look. How can we build applications using the EC, my script module? As you can see over here, all the features he has, he has the import export, which this is what you're going to be using. A lot has dynamic like binding loading and other stuff. So let's get going and learn about express next 2. 1.2 About the Express Framework: so expresses our reality and a midwife web framework. You can think of it like a process line in a factor. I think like you have the routes that you manage. The end points, like the entrance off your application is lash would be. They wrote his last users. You get the user least, for example, and then you have requests, which is the orders. From there. Things enter from one side in the process line and stuff are done to it. And then he comes out express orchestrate how this stuff is done through the use of Fida wears. We're gonna take a look in depth or what? It's me, the one. And we're also gonna take a look how we can use the NPM. The note package manage module to install. Some people are me, Dolores. If you go on resource me doors, you can find a bunch of other middle. Where's that we, some of them we're gonna be using and, uh, their plants offer used for stuff that the express community are red billed for us. So, as I mentioned, we're going to use the yes and module. If you're going get started here, they have this express generator. But the problem with this this you create application using com O. J s merger, which, as you can see here, is gonna be with this syntax, and that's not what we want. So we're gonna create our application completely from scratch. We're gonna start building our projects application. I'm going to my desktop. I have my son box over there in that I was before he I'm gonna create a folder called Express Up. You can name it whatever you like. Now I'm gonna sit into it here. I'm gonna npm in it. That's right. This is a normal command to initialize er applique another application with NPM. But instead off just like that, I'm gonna use the A s M module that we spoke before. Then you can press center. The dash wine is gonna say yes to all these questions. So I'm gonna open it on my Cody editor. And here you have the package. Dodgy some yes, and model does install. And then there's the index, which is wrapping our main Js file. The man Jesse just are the final we're gonna use to create start creating our application, and it's wrapping the five into the US and model. So this is indexes doing older job for us. So let's build up a basic express application first made to install it. Of course, when I opened the integrated terminal and I'm gonna do any PM in stuff you can use install like that or just that I for Short Express, you know, that's dumb Here, I'm gonna be important Express on express. Now I'm gonna create instance Off Express. That's now I can use that up variable so I don't I am not gets And here lies the routes, the endpoint I want. And here is that function a request and the response amusing the abbreviation. So it's easier to type. But that's the request and response. And here's you so we can use you know, that would be the end. Like you works in express, we use sounds that's gonna send whatever you will have it over here like, could be Jason or whatever. And then I do abduct. Listen, So it's stock my server here we'll take also the report, but I also gonna pass Ah, function that is gonna console log What is doing? Yeah, I was gonna say services running. There you go. So now if I run this application to the index so I don't know Index, and that's gonna run our application, the next gonna get the s and modules, and then it's gonna run arm Mendel Jazz. Now, if you go to the browser and go to local host and TNT, it works. So that's basically how we can create a basic application with Express. This is running on the next lesson. We're gonna go deeper into it and you're gonna learn about the application extraction and where to put files in. We're also gonna create a script that is gonna start our server so that we don't need toe specify any file name in here, So I see in the next lesson. 3. 2.1 App Structure: So now let you know how to create a basic express application, and we're using the yes and module. So now let's learn how to organize and structure our application. So first, I'm gonna create a folder cost source and put all the stuff that belongs to your application in it because you're gonna end up with lot off little fires outside like not getting our and packaged RJ Sohn link. There's configuration file. So you want to keep it by replication side one for them that we can easily on find stuff in it. So let's school make director the source. So this is the basically structure that the express generator creates. We have, ah, views public, which is Scott, your static assets. You got the routes public, and so and also the application dot Js. So first, I'm gonna move this main Js application into our source folder And I'm also gonna really me toe up because I don't like may You can live it for life. So it is moving. May the source slash up vote Yes, There we go. Now I need to fix this one here toe, find the up over there in the safe This is the last time we did this and also in the Pakistan. J. Saunders, This some margin, I just need to change for Oppa's own. So that's it If I run? Yeah, note index viewers. So now let's create a few more folders gonna create a views source views. Among also gonna create assets, which is gonna be my static assets. And inside the assets, I'm gonna create one for Starship, and I'm gonna create a fine call main dot CSS that again. You can name these folders and the final however you like, But please don't follow along so we can. It's gonna be easier to follow the course. Let's create a few more fires for application. So source, we're gonna need the router. But Js one also create Medawar about Js me The worst I'm gonna create one for my database configuration also creates a, uh, helpers O. J s. We're gonna go through these files later, but basically, this is the structure. I'm just showing you now so you can have an idea how toe put it together now for folders. I'm gonna have also a folder that is going toe hold my configuration, make it dear Asli source conflict here. I'm gonna put configuration for my like, environmental configurations. And, uh, it's what I like to differ from. From what express has on their website. Yeah, they're putting routes in a different folder every route, like the users, they are you putting the rows together? They would put the models together or not envisage pattern. Gonna learn about embassy pattern afterwards anyways. But for now, just follow along and you're gonna understand what I'm saying. For example, whatever your application has a resource or a source is like a something that you can create you can indeed, on your application is arrest full 80 I cause that you can do like you can create. You can least stuff. So these things that, like users, projects, block post whatever you can think off. I like to put that in a folder, Call resource and, um, at all the files that belongs to that resource into that folder. So, like this, you can keep, for example, let's create one for user. Somebody make their hope was dashed. Be over here because they folder is not yet created. Sources. It's last users. So here I'm using users is because it's a collection off users and he has many users and resources. Your application could have many research. That's why I included arising here. And the dust being is because the resource folder is not it doesn't exist yet. So here just need to add this source. So it's gonna be assigned my source folder resources users. When I do enter, it's gonna be over here. So I have in that. So basically, this is what I do. I do user the router, the GS user, not model, but Js. And then you have controller, not Js. So we're gonna look into this files each of the spice later on. Just bear with me for a moment. We're going to work in on in the pattern called embassy, which is model view controller. We're going to learn about this later. But usually Creator model, you have a controller that is gonna do this stuff and then you have your views, which is gonna show that the back to the clients. So so far we have response. So a resource users views views were not gonna put anything for now, and you have all of these others things over here So now I have the Pakistan Jason and here we're gonna create a script. We start our application, I'm going to remove this because up no one needed for No. And we're gonna do Ah, script course. Start this start and stop is one of the main scripts that it's ah, available to us from the NPM. And like when you put your cold in a server that's ever is gonna look into why stacks crypto stop your application. So this is very important. You're gonna go note index, Not a few door NPM starts is going to start our application now before we get going, let me, um, mention another thing that is gonna be used for for us. So here we see he works Now if you do a change on your codes when you go back isn't even if you're refreshes not there, we need to stop the server and then it starts again. And then when you refresh is that so? Let's install a package called No demon You through what you for five change and then we automatically restocked your server for you. So NPM install no demon, I don't, as you can see over here on the installation there is, like no description or proposed are fueled some warnings over here. You can ignore it, but we're going to add some stuff in it. You know, it's not that it was installed and know them over here. You can just come on to the stat script. You can stop the note for no demon. Now, if you run your server, you see it picked up. So now every time you save your application is going toe, watch free and it's gonna recite a serve automatic soul. It's on that safe. There you go. Now let's take a look up, NPM. So it's not Jason is what you can handle. Everything that happens in your up just to keep a track on what independence is you can put like some other information. Ah, description. You cannot do another stuff to eat as well. He wouldn't. It keywords because keywords are for engaging Keating, a package that you're gonna public may make available the and being a mom, where is history so we can remove this one. But we we need to put private, which is gonna tell it not toe to make it available for people to search on the NPM resisted for it. So here on the package dot Jason NPM files packages Jason, you can find you can find a few of the stuff that you you can onto your package. So, like you can put the home page and and other things, you can go for it and have a look. We're going toe act. I get triple stomach to it. Like so. So it takes on object inside a type in our your ill before that will need I get reports started. We're gonna do that bit so you don't need none of this. You can leave it as is. But as you saw on the they're not before it was giving. Ah, warning about the description and also the these No get reports turn. We're gonna start out later. The get we were down the description here. Basically, what do you want to do? Is always put private If you have all your privates called in it. Like if you have your gun, your own application you don't want this to be our open source module, for example, you on that. So now I have our application with the folder structure. Now let's continue with our development environment 4. 2.2 Code Quality: so before. Anything, this is just an overview is not meant to be a in depth with Julia. Just a quick note down how to set it up. You can read the doctor if you want to learn more about it or if you're not interested, just keep ahead to the next video. So Linder's, why should you use it? You must be thinking like ah, shit, another stuff to learn. But don't worry. After you learn the benefits and you see how easy it is, you never called without them again. Most new developers you shy away from like we're looking conflict files. I know I did. Just like you see what back stuff is like. No way. What the hell is that? So but little doesn't to be complex. You can started, like wish one single line and that's all you need to get started. So let's take a look we're gonna use to Labour's Yes, leans and prettier. Yes, Leans is I style guide on how you should write your codes. The thing with it is that you're always gonna tell you like this is wrong. This is wrong and like you can check it out. How to fix it, and then you can go and fix it before you're called. It's on Red Toby Butte, and preacher is a four. Matter has nothing to do with anything. And that is just gonna format your coat in a nice and organized way that you're gonna keep my standard. So, like, if you ever gonna share your cold to someone, we're gonna get some people called. You can use your your If they call this argument, you can just quick use preacher to formatted, and that's it's gonna look familiar to you. Depends on day settings you're gonna be using afterwards. So let's get started. First, you need to install Yes. Late. So nbn he stop here, gonna pass the dash d flag and then yes, leads did actually save it. A sob development dependency. So if you're checking here in the package that Jason is a death dependency, this will not be back it. Stop with your up. It will be used only while you're coding. So next we need to create a conflict file for this. Yes, lanes. He's gonna stay on the road for application, and that is basically statue for dots. And that means it's gonna be Ah, hidden file. Yes. Leads R c this RC on UNIX machines. Basically that means, like, a configuration file or something like this. I don't actually know what stands for, but yeah, most files are by that are See, you have the yes leads. And now we can create an object. And here we can say extents. And then he s needs color, recommend you save it and that's it. That's your configuration file now to run because you don't have it installed globally and you actually don't need it. You can use the MPX, which is ah, feature from NPM. After I think npm 455 Maybe they comes bundled with this whenever somebody comes and PM And this MPX which allows you to run local install package as a global So MPs he ext? Yes, lead. And here you can say I did They finally want to leave or not for everything. But that changed my criminal here so we can see properly. Then you press anthem. I have a type of typo here is recommended. Sorry about that. Probably so there before and now There you go. You have these require is not define Ma Jo is not define And that's because we're using note and, uh, yes, Limb doesn't know. And we also using module, which is not all by the fault, it usually script by the fault. So we need toe at this two things in here and that you can do with the environment. So here you just coma and then you put in here is gonna be another object and you can put a note to and yes, six, which is what you're going to be using, but through as well, No, but when you save tried to run it again Now you only have one read only require should not be mortified. Barcia Import and exports may appear only when the search type is module. We're gonna change that as well. So here's the next part. Parse options. Now the object. So let's dough, the McPherson. And here we cannot any virtually wants 2017. We're going to be using on this course. So next the source time. And here is the one module. Now we just need to tell what kind off Eckman features we're going to use. And we can set modules if you're using our regular on loads application and you said yes, linked recommend and they know you should be fine, but because you're using GSM, which is not yet supported without the the package we stall, we need to do this extra step. So if you do it again yes, late sparser option most cases. And I was like, as I mentioned before, You can do you for liner. It's Ah, this one would be enough. But because you're using the yes and modules you using note we need to set up set this other things over here. So next thing here we have these average global require should not be much five. And you also have a console log statement over here, which is our I also log over here. This is not recommended to live in production. That's why it says it's it's a Nero. So now we cannot remove the stuff by using the rules and here on the actual that you're going to use And it's here, Lebow, no global sign which is this one in here for that fix This one. No global sign and there no console. So before I cleared the time now and I run it again. Let me show you. How do I get this information over here? So this is the problem that is causing. I would copy it and then in the yes, leans not are websites. You can just pasty here on the docks and it's gonna peer over here. This allow native objects no global sign when he clicking that it's going to show you some rules and some options that you can set like is exactly what we did over here. But instead off the object, we're passing the require. Which is that the hero, beginning with the noble ball signer. And now the 2nd 1 is there? No, no con. So back again on the search. Zollo, No closer. Here's Roseman. Us explain you about this rule and how can you do it? Allow or not? And so I'm going to disable for now because we're going to be consul. Logged a lot of stuff for the course. Also, if you are another two are here. If you go to user guys configuring yes, links. Here are the things I just we just did. We'll set the fires Options Tau sigma six. These are diversions that you can use. You can also set us at 2015 years, 16 or 17. This is what we using for the ECMO version. This source type you will set for sleep. That's why he gave us the hero. And then you change for module, which is the source type module in the ECMO features. Wait. We add the modules which were using the Yes, I am. So, as you can see, the futures are here. There are more rules, for example, Like if you same Kahlan and stuff like this, all this stuff you can find on rules. And here are the rules and how you can get more information about them. But this we're gonna get into more details about the rules when you gonna get the prettier Lucky. So for now, I'm just gonna run it again and nothing returns because everything What's so right? So I'm gonna use I'm gonna comment out this console log over here for a second, and I'm gonna run it again. Now, I have this problem over here and the warning. So what I'm gonna do, I'm gonna show you how to format this output. This output doesn't look very nice. So we can format it with that's dash for months, and then they But I like the table for months. And then the doctor as we did before. So that's not for my table. When you do that, it's gonna be in a nice, uh, table four months, and, uh, you can check it out. The for matters here on the US guys, For mothers here, there are different ways to display Were I like the table. But if you scroll down is this is how it's gonna show checks die cold, friend. A lot of people like this one as well. This is, ah, personal preferences. I like the table because he keeps some things organized. But also, if you are in a the smaller term, now is not going to look so nice. So anyways, that's what I wanted to say about for Mateen types. You're on. It's 000 warnings. Now let's create a script on our Pakistan. Jason, that is going around. These linger for us. So let's colleagues his name. You can give it whatever you want. I'm gonna call so we can use Yes, link. We did, uh, that's that's for month. Dave O And now we're gonna pass Dash, dash, fix this. If there's any arrow is gonna try to fix by itself, it just kind of cool. And then the doctor's gonna delete every file in this project. So now that you have are yes, Lean install and the configure it it's time to get our for mother. And this is this is the one that you're going to use He basically just for much of code doesn't do anything else, but it's really important. So let's get it started with we're going toe configure with a preacher integrated with yes rings Now the informations But in ah, that show it's you need to install prettier, yes, plugging preacher. And yes, Linda conflict prettier the extent we're gonna extend. Ah, Richard as well. So here we need to make an array off options. And you used a plugging preacher slash recommended. So in the rules, we need to add preacher euro. So whenever there's ah for my tea, the problem is gonna shows a narrow Let's try it now. So let's run our or our leader and PM Ron links. We still don't have any problem at the moment. A the leader it's set to use double quotes as a default. They glitter all this for months that this is the fault you can see by, like, a Just pay attention on this are called over here is gonna change for double quotes. You're on the links. There you go. It for matter cold with the preacher And then he fixed the links problems if there is any now, Peter, give us a lot of options on how to set it up. The same goes for the for us. It means every option that every error that's a yes men can cause in your coat. You can turn it off or you can do something else of it. So on preacher, you have a bunch of options that you cannot configure. Like, for example, a lot of people don't like some columns or they use spaces of taps. It's totally based on your preferences. So anyways, these are the options. You can find it here on the docks, the critter dot io options and here that there is a list you can go free and see your references. For me. This is what I like. And there are a few ways that you can put You can create a preacher dot Ours adopt critter I see over him, but I prefer to put it in a package Stop, Jason. We just need toe a richer over here, and then you can have your preferences. I don't like to use and colors. I don't get whatever you guys said. I like it. I don't use, um, spaces. So you stops through, and I like singles. So back in here, you can find you stops, send columns and stuff. All these informations on here. Single quote Here's they call that you need to put over there is the a p r. Over. Right? And here's the defaults they felt for every option. So now that this dunk I'm gonna open up my, uh, up dot Js and I'm gonna run my lint again, I have ah, type you So use thumbs for run again. Now my court has changed the way I like. Now I have our leader and our critter set up and you're ready to go 5. 2.3 Database Setup: we're going to use along with the B as our database mama to be is an open source and no secret database. It starts that in adjacent like formats That comes very handy for us because we use Jason everywhere in JavaScript. Words also among is ah, where it differs from, the other database is this is no secret that obeys no single of the base means that he doesn't is not like a the sequel. My sequel, What's grass and so on? What is that? The base you need toe create your models and then your app is gonna follow up that model and for the no sequel is the very round we creator up However you like and just give the information we need to save Tamang go and need to save for us We're going to be is also a schema list Schema is where you can model your data. So we're going to use a library called mongers that will help us modern in your data. So let's get started. I'm going toe my application and he inside my database I'm gonna creates a connection toe mongo db and Easton. She ate that that a base inside are. So first, I'm gonna install mangoes in three and installed Longo's now here can import, and I'm gonna create function. This function you can name or every life just that at the base connect. So here, when you return mongrels but connect connected method that comes from mongrels and we're going to connect to our database if you have a local istan just used in mongo DB look, a host. So here you can pass a name for your letter base. I'm gonna call this one express. I'm gonna add that death in dance. Are you explain? What is that for? Later And here can just do them because the the smoke goes returns a promise. And I'm gonna just cancel lock so you can check if you work the knots can write anything you want. What was? The date is ready. And now, So I'm gonna do a catch. You think the era and I must have been a console? Log it. But nine years I string interpolation something that's wrong, you know, other era. So now I just need to use this that the base connect and I'm gonna stand shades. How about the basic here you need to import is the relative path toward at the base. And I just need to call this function now. If everything works correctly, we can start our server first. If you have Mongol star locally, you can start the server if you're using Ah hosted mongo like in labs. You can pass pace that address over here, he said of the local host. So let's go ahead and I start our server. There you go. We're going to be It's ready. We have no error, so we should be working. If he works, we're good to go. 6. 2.4 Configuration Driven Application: Now let's talk about the conflict driven application. As you can see, over here, we are hard colding stuff in our application as we did with the port in with the database. So this is not really good to go, because after we're gonna have toe, if you ever change this address, you gonna have to go everywhere you add it and change it. So we're going toe set up a few files that is gonna check which environment we are and set those values accordingly. For example, estimation I had the dead over here. For example, if you're gonna be production, would you use a production that the base instead of these because you don't want Toby coding practicing and stuff in your production of the base, That's ah, no. Or a test at the base with the leads, all the content in other base every time you run it. So let's create some configuration files to Is this fight when and where we want to use this information? That's how you create the conflict folder. So I'm gonna stop my server, and I'm gonna create a few fires. Source slash will think for someone to do index, then uh, that's and I proud. Those are shorts for production and development and all views. And we're gonna start with the index, which is gonna be the base configuration, not expose something called the process for us the processes in O. J s process. And it exposes the environment for us. From here we can get the note. That's a things these contains what environment We're all like production or development. So this one, we're gonna start to play around with it, and this is gonna be equal. Either this arm is going to be a development. So he's first going to check if you set. If nothing is in there is going to set as a development. Now we can create a con sto make investing short was done timeto time that stuff all the time. And then it's gonna be the process, that image. So this one is gonna be either be they wanted their it set or is gonna be development. We're saving it. Enough in this are aimed variable here, we're gonna create a base config, object based conflict. This can hold anything that you want. Always. All your secrets can be here. Here is where you can put your A P I keys like your Google maps. A p I keys are your brain three for people. If the I key stuff like these things that you want to keep secret, you should never add this to your cord. Should never committed stuff. Toe Get up. And then we're gonna create on empty config here, and we're gonna fit up this and conflict with that of from this switch block we're making over down here. So we're gonna test for the end in cases of development or in case is a the short hand for it. We're gonna do this end so he's gonna be equal to the development config. We don't have this yet, so let's go and create. It's gonna be in development, and he would just need to create a constant called that config. And we can add all that information we want usually put support. And here we cannot use the process of ANC, which also has ah a port affordable. But we can set consented for 2000 either reports or for 3000 you cannot set our database and here is going tobe a Let's put that the base that development with a comma over here. This is the name of the database we can name whatever you like. I'm just making sure that is different from the other ones And whatever secrets that you want puts for development. So with this that we just need to export as a default. Beth, Cough. You know, we can import here, Justo impart from that. So now we have access to this death. Cough over here can continue so that there would be done. So we do a break, then you can test for the next case, case production or case the shark. And here we go the same. Mr. Copy this instead. Off the death is gonna be frogs. Let's go and knock radius again. But this time we're gonna copy this one, and I'm gonna based in the production here, I have production, and I'm gonna change the ports to 88. Which is that the fourth court for age to be hurt requests. And I'm just actually just making this up. Ports like this. So it we can see the difference while you were testing? No. So we have these now. We just said the defense, which is the African figure over here? I bet So, In case this environment will be equals two development or just death, we use this death configuration file the database and what have a secret is here If its production If this equals toe the production, we use the prods configuration and you always gonna defaults for the config. But this don't we can just this part. The fault. So here we need to merge this and this based conflict together we need every configuration and the baseball thick together they're going to use Ah, low class merge for it. So do NPM install low dash dot merge blow dashes a set off a libraries that it helps do like little matematica staff and little bits of JavaScript code. That is really helpful. So here we're getting parts merge wrong Well, gosh, merge. You can diverge. And then we just made the baseball fig with the anger conflict. So again, Ah, human it doing parts the production breads. Okay, so let's say Rick up not has thes process exposed the process and from there we can get the environmental variables from it. There's a viable cold note f that stores whatever environment you are like if you're in their server or in a production environment or if you are a development like we are in here , if either is gonna be alright, set or it's gonna be development and then we're using this result of it here and saving it in tow. This end variable. No, we're creating a base configuration. You can add anything over here which gonna be shared amongst both development and production so it can add anything over here. Let's dio go. This will be saved and it's gonna be available to us on both development and also the production. So have the base. This will be shared between death and production and then we have on empty and config which is gonna be, which is gonna be populated by this switch block. In case we create to case one case for the development in one case for death dependence you're putting Are you a setting the old environment via Brenda? So it's getting the config Miss populating with the conflict, that configuration in case the development and here, in case the production, the config is gonna be a production and you have it defaulting toe that here using merge from low dash that is gonna. But this environmental and F config and based conflict together So another thing that you need toe, be sure these three files is gonna be start in Ah, in our gets hub. So for development is fine if you have this, because this is quite common scenario that you use local hosts that the base three star or it's no one cares. You don't really don't We'll have many secrets over here that you need toe, say somewhere. But let's say you are sharing a P I key between your development environment because you actually need to use the key on developing so FBI. Okay, and here, whatever, like my secrets key. So in this scenario, as we're gonna commit this to get up, it's gonna be available to anyone to see whoever the load your coat is gonna be available there. Same goes for day deduction. Here. You will share this one and this one would be available. Czar Production. You never use this local host. You have ah hosted that a base like emblem And then this is the that the base you need. You're gonna go and based over here and then your your passwords. So all of this gonna get committed, and that's not gonna be safe anymore. So what do you do? There is a library called dot inch that is gonna actually keep this in a local machine and safe. So let's see, stall npm install dot anc and that. And, uh, you can create a file. Cool. No, thanks. In the right off your application. So he signs what are viable a pikey and and that the base, when working with five global viable said this we tend to always use Pep does. So here we going toe cut this, I bet. And also this one because their own safe and not to use of a him you'd call the process not , but not the base here. The same is the process. If liking, remember the process from no, you expose the whole environment you're using and the start of viable is that you globally exposed with this final over here. But this guys are not there yet, so we need toe actually at it and you could add in a configuration file. But we can also act over here in there when they start script. So here we're going to use dot bank slash four fig, and that's gonna be a required. So that's our that aims poking. So this is gonna pick up this file on the environmental and it's gonna load those variables into our process that now we saved these things. Inside are production environment and not death. We have this one's and this are completely fine here. We can change as well for the production. So this a Paki won't be shown in our developments. This one is fine to stay, we can do the port. So let's dio here the inch we can do a port zone It's eating. So there you go. We have the process that ports and here I'm just gonna leave us. Well, the process port or 3000 in case we did not set that port so no less tested out and see if you work go, npm start, everything works and the part is running on port 80. So this your something that we hard cold that we need to change as well. So if you go back in here, we can change this for process that actually lets great ah viable cost parts because the process of time but port. So here, begin you a sport. And back in here, you can use stinking their relation the part. But we need to change this for tactics now in Iraq, this should be reflected in the environment over here based on a change for 3000 and then I'm gonna run my server again. So as you can see, not my port is running. My server is running for 2000 so the applications successfully pick up this fine with this database and we can use the data as we doing over here with no longer hard coding. Anything we have all development but that the base that we can show our a p I key over here . So now we change. The port is no no longer hard coded. And our development are environmental Keys are working. So now let's go in a re factor our database so you can use the conflict instead off this. So here anything part are configuration file, So import at config strong fig here inside the that the function we need to pass that config viable so you can pick up inside. So we set it from coffee. So that's and here instead of the hard coded that the base connection, we gonna call convict. But that the base. So now, if Ira, I'm getting this error here off course, I made a mistake there. The death he is not equals is our color. And also in the broads. My God, no. But he works. That seems the environment while we're here. Uh, toe, make sure we know which one we're dealing with. The config will be the development firm is gonna be for 2000 and the production will be part 88 and I'm going toe. Also, remove this part from here. This is no longer needed. So we're gonna change the environment before we starting our server. And, ah, for development. Oh, here's production. You owned exporters. One needs to be changed. So everything works properly for production is gonna show part 8000 for development 3000. So let's tested that this out. To change that, you need to goto our package that Jason and here on the demon, they start we dough before we call the note. Dima, we passed in new variables so no and equals production. And then we can call whatever else we are dealing with. So if you run the code now, start service running on local host on the fine. And then there's authentication failure because probably my password is wrong. Password. 123 And here the same way we called. Configure that the base. We're going to pass a port. So here, instead off setting toe process that change because we deleted the one from the end. We need toe the config, not part which is gonna come from the configuration file recreates in Port Apple fig conflict. Now when you're safe, it should work properly. Let's just call it config. So we know that it's belongs to this conflict. Fine. So now it's all well is running on 88 because the production it's 18. Now, if you remove that production environment to set for death and we started serve again, you pick up the 3000 over there here. That's why you created the development and they the two K's Over here. The development, the shorthand and the development or production is because you can use them over here if you like broads save and any fuel here. As I said, you always need toe because you're dealing with a part the service on They know the mom is not gonna pick up change on it. So there you go 80. Now, let's quickly recap. This will keep our database our secret safe. Like a p I secrets and everything. Like we did before production that the base over here and then you were passing. It's for the production. We're passing it straight from there. So this weekend, this can be saved in together if your coat with no risk of exposing any of your private stuff. So another thing when it dough we need toe at this dot Aimed because he has our security key over here. We don't want this to go anywhere as we mentioned. So we're gonna add it to the get ignore, Not thanks. Over here. So now when you're gonna try to save this, never gonna show. But in case you were divided, share your cold with your colleague or someone that needs these environmental things to work. So for them to go, what is it that they should have in order to make her up works? You should copy this. Cooperated that aims in. Ah, call it whatever that sample there. So this one's gonna be safe to get hub, and then you come here, you delete this and Italy the secret key. So whoever picks up this are schooled off yours in the future, you know that they need on a P I key over here and on database key. So this will be saved in your computer. You can add whatever you like. This one is gonna go as, ah sample for them to know what what they need to be, what they need to aunt. And yeah, Now we have a fully functional, conflict driven application. So now that we've done all the configuration is a sire in an application, let's are committed to get and push it to our our get triple star. You don't get status. We have, ah, few new files inside the conflict folder. They am sample and would find all this fires. So let's go get commutes with message. And here we can say development environment. This is how I always name. I commits. It's based on what is it that I worked so development environment and what I did after the colon. Here we are, uh, are not the base connection. Bless up configuration and that's then we cannot get pushed or easy, Master, here is my express up and I have my commitment over them. 7. 3.1 Routing Bascis: So let's talk about one of the biggest topic being expressed. Three more. They're out. Every up needs a way to receive requests from the user and act accordingly. The Royal the user is at the moment, So let's create some basic and points and see the concept behind, as we saw earlier note exposed to methods, the request and the response. So about the words like these, the user requests something. We go to our euro. That would be a request. So they use a request, something, a source or a page, and we respond. We used the response method, so send back the information we want. You do some stuff and then we can send these so to break down our out a little bit more. Let's move this route route. It's on five, which in created Over here person one of import express and free distance off the router. Now here, I'm gonna be that viable. Well, Tyne, you can call it up route if you like single just Well, it's fine and express welter nature. You have this one. It's Capito because this is a glass inside the express paying work, and then we can just do right there. Doc gets and you're gonna call for that sprouts. It's the same once you have over here. So I'm just gonna call this function Basil. Now all I have to do is export boost. Delta. Now that you have a route and exporting is you can just import no application. So here in the old route to help, we can just to replace this function with the rocker. And here he said of Get, we're saying we're gonna use it because we're using this route. And here we are, getting the you're ill when you say that. So you should try to run and start began that, but I'm looking wear. We left from the biggest lesson we left in production, so I'm just changed this real quick here. I want to stop my server here, the start development, and I'm gonna set a port because I like to work in the Port 88. I'm before to the here. And this will pick up the 88 because having here prevention, it's either they part on the environment or 2000 so and starts for 88. Any word on the development environment? No, we're good to go. Let's tie it off in your browser. Our routes. Hello from Progess. That's great! One more. Oh, now, I was gonna change this one in a 1,000,000 simplicity and you're gonna copied. And I'm gonna create an about page somewhere yesterday before Utes will be about I can get to that ball space as well. So basically, this is how great simple Raul spew express Js this weird only sending data back to the user . But they're sometimes that we need toe ask users for information, like in a form for that use the HDP protocols or http verbs they've anyone's. You get to see our debts opposed. Books are batch and the lids gets. We request that from our service, but one change anything, you know, resources the most. I meant to post that, in case you have a farm used a post method and you can send a doctor from the form to your server. So they put and bunch they work a little bit similar, but they put if there were source doesn't exist. It creates and replace existing data. The patch is meant for partial updates. So is unknown destructive way off topic lately just keep in mind. The bat support is limited, and we're not going to use in this course the courts. We worked fine for us. And you have the D lives. Yeah, it's tough. Let's check it out. How this works. We need to deliver this Clinton tops for now and here, but a great around for signing in Sanaa page. So this is the sign up is also gonna be against the signing page, and then you're gonna have a router books most. And here's sign up. So now, instead, off doing a sense. First, we're going toe. There's some stuff over here. You're gonna have some information that comes with the request. And one of those things is the body. So we're going toe. Request the body. Let's say we have ah, form. And he has made you and password. So let's do a viable 40 million, and then we can call Request the body. The maid. Same for, uh, bus words. You're gonna out quick so I can select both in the S codes in the animus. Gonna change boat together safe time. Now we can just start to Ah. Is there a viable there? Were we kowtow A 1,000,000 passports. And here we can send back the user Sam user like that. You're the four Express toe Be able to read the information inside the body. We needed me the way that can pass that information. So let's get body part. Sir, do npm install body bar? Sir, we haven't talked about me the wears yet, but we're gonna get there in a later chapter. So to use the needle where inside the application, we need toe first import. So let's import body bar, sir. Wrong body parts, sir. And here before we do anything because I'm middle where it works and I stock we get the request and then he goes through a day process line, as I mentioned before. So you need to go up about use and recall the body part. Sir. The body Parsa has ah method called Jason and we just call it like that. This will teach our application how to read Jason. And then we do the same. Opt out. Use body parts, sir, but the here we gonna So you're all included, You know, like we saw before. We can send some information with their you out when you play around with your model from so we could pick all the information we need. This will do the same. So here. But we need toe in extent equals through, and this will teach our application to Reid's euros. So after you save our application express, we know how toe help to read the body from the request. So now here's the thing for us to be able to send the post request as we don't have a formula, we need some kind off application that we can do that. 8. 3.2 HTTPie and Postman: there is a list of application called postman. If you prefer that using your faces or if you're like me and prefer doing stuff on the term now I like to use the H City. Fine. So here is the postman and this is a very simple to use for most of the stuff that we're using today. You don't need to learn anything about. It's just a few plates. I show you know it. There's a three plan so you can go loads from the download bottom over here. And then it was a platform. So now the next one that I like to use is the HD five. And this is a STP command line. Are you sure you know how to use it? You can you stall over here for lean abs for Mark used the reinstallation. And then if you go on docks, you have Bill looks, which is there. Some of this division is over here and for Windows it's gonna need himself, Pete, which is a fighter. But his men is like our npm but this fightem. So we start we start dollars fighter and he stall that should come with so we can do this. Come on over here. Now let's see how you can use them. This is my endpoint. My server is Ronnie bringing first? When you first opened the postman, it asked you to create an account or signing. So there's a sign and they castrated to up. This is the application. You can close this being over here. And what do you want to do? You want to send? Let's first get sit down. I get requests. You are signing base. So local host 80 80 slash signing and he's a gets. If you hear Does that all the ones that you you can use So when you send you will send us back these If you go for our you got their home page. So that's how busy you know. You put throughout lesson here that what you want again, you can ask for information. Now we're going toe post request to the sign up. What do you need to send on the milieu in a passport? It's how you do it. You're posting you go on body the teacher's role. And here on the type you consent, Which is that Jason and he would make a Jason by this so name he made. And that's and then the passwords just like that. And then if you're Sands is sending us back the information, send me back the user over here and it's a 200 which is okay, a status. So there we go. We're sending this information as a J saw, and then you are sitting over here. Now, let me show you the way I like to do and the way I'm gonna do on this course. If you are using this one, you can shoot changing here for later offer the leads. But they put that you're going to use and then use this information as a Jason over here. We should get the input and you can check the status over here. I won't be coming back to this application anymore, but if you want to use it, you can learn more about it in the website. So, http fine. It's very straightforward. So what, you want to go? It's still big request. We're going toe post, I say, let's say we were Getty we get look a host 88. If you do that, you get our home page. There you go. home page. Same for the other ones. Slash. There you go, you got Here's a status. This 200. If you send a request somewhere that we don't have, you get the 44 era. There's no phone. So now let's do oppose request. Actually, before that's we're sending by these right here, toe. Make it faster The same way we're doing my these, um, you can for me to get and you go it's found in the same, but you got to get on it and you can also call me the local holes So column column 88 name . There you go. So it's quite fast to get typing And then, uh, for the resting it to its respond because get is up the most common. So they kinda let you slide on the wall. Supposed 88 then we're gonna go sign. No. And here you just really space. May U equals I love you. And then bus swerves because, well, when you know that there we go for me using like this it's ah much faster. We are inside our Cody editor. We don't need to go anywhere. We don't need to stop any other stuff. I mean, apart off this, it's typify, but yeah, you can choose whatever you like. If you're more confident with graphical user interface before you to have the postman. If you want to used a stick bias here as well. Make sure you stop one off either one off this because we're going to use it a lot coming up later on in the model section. 9. 3.3 Resources Router: Now we're getting this information, and so far it's all right. So let me delete this comment over here. You need it anymore. Most probably your applications going in some kind off users out of control and diminish them. So let's move on and creates the router for a ruse user. And they were going to go the same way as we did open here being no Meireles, we're goingto be part express later, an instance off the router and you're gonna get our infants. So here about users, we go import express, Long Express and create the instance of the robber buying here. I'm going to name it User Router on the other one. Our name, It's Ralph. Only here could be the up because this is This represents the main application route, like directly about the rules and stuff like this. And here is Onley. They stopped that relates to the user resource. So express about Ralph. No, we can do user router. But yet And here you specify the welter like then and points wait will be users. And he requested they send informations and be part request spaz. And then you could eat the function. That's gonna do some stock and yeah, send flowing for May. So sent. Let's do, uh, user least for now. No, let's try it out. We're gonna import it inside the R welter Main router five. So reports user welter sources users did not below ever seen. You can just do router, but use because you're going to use that router. And here you specified the buff and the router over there is a wrong Laura Grasp and is missing the sport. That's because we're gonna became viable. But we can export. So let's do export. It should work. Now here's the thing we're having the users over here. Slash would be the homepage and then slash users would be the user least if you choose to put your name space in this school named Spacing, it's like whatever you're gonna call you resource like users his last folly, for example, they'll be the name space users. If you have products in your application, you leave products is lashed. Looked want something like these. So it's better toe act your name Spacey inside the main router because later on, you're gonna have a bunch more Rogers over here like Lulu exposed whatever. And then you can you have only one place to come and change the name space. Is that off? Going down the side, every single folder and resource and change it over here. So if you add your resource name space inside the rotor, it's easier for you toe operator application after, if you decide to change this for only user or is that when you, for example? So let's recap we are creating. We are important express waiting on the steps of the router called User Router. Here we're getting the user routers, getting this and points and passing this function that's been overturned, the user least we're exporting. They use a route, your important inside darling router. And here you're telling, They dropped the main router to use welter with this endpoint. So if you go to your browser and that's it, out the home page and then if you don't use us, there you go. You have our user least. So now how about if you want to get a user like folly or the user? I D. For example, you can use that with a request that caroms back in. I'll use a router here just gonna create another use a router. But yet and here we're gonna pass the I d off the resource you can. In case we're doing, like, a block post present. We can posses log. Whatever you're passing here is gonna reference what is in your model. So, you know, mother gonna happen. I d and that's were passing to the parameters. And here's the same. We're going to get the pass a function request of this moss, as you can see what you're doing, that a lot requests a response and create a function. And that's the main barber plate for express application. So here is Sandia's. Well, that's the, uh, string interpolation here, user. I d is request, but bottoms. But I think so. What response? This bottoms you do if you look up for whatever we passed over here, the information If he's loved this Mr Beatty slunk. So the bottoms you look to your your idea and extract whatever this evening after the colon now he suggested I just repressed is now my user is punching before folly. As I mentioned before, if I get is long, if you look the same, the name here doesn't matter as long as you have this information in your database afterwards. Because here we don't have any information. You just posse around the parameter. But after we actually gonna have an idea for our users. So it just makes sense to use the idea in the user scenario. So we created a maybe around a fine. What is gonna host old and may application related routes, created resource routes, which you have all the rights that relates to that user only. And we learn about how toe get in post. So they're out to get information out of the routes and posting information to our server as we did on the sign up. So to continue with their outing, like a belief that date, we're gonna actually need a real database to work with. So first, let's get some Batta, and then we can play around with the route. If you want some extra information about the router, the best place to look for information is always the official documentation people guides and routing. You do have some examples and some more in the explanation. We're gonna go over all the strings, but in case you need for future reference or you case updates makes it just Just so you know, that is here if you need. So before we move on toe models, let's commit our work in the router to get so get committing with a message you're gonna see Rob Rotter. Basic route structure plus user and off Rose. So So I see in the next lesson where you gonna learn how to use at the base? 10. 4.1 Basic Structure: longer the bees I schema last type of data base. So by using the Mongoose package, were able to design in constraining our models. So let's take a look not to waste time. Let's create our user model while learning the ins and outs of the mongo DB and mangoes. Let's go with a basic structure inside our resource user. So excited models, we got important mongrels from long was Now we need to do a few things. First we creates ice came up. This is where you're gonna do they that Ahmad early. Here's the cost schema, There you go. Then we're gonna need toe create the model itself. The moderate here recreating you would be like the tables in a relational That a bit database. So here we are, using user schema like New Mongoose but schema and here for in dysfunction we need to pass that this schema we created over here schema. So this should be enough. But let's pass a bit more information every time you create a resource is always good to keep attack for future reference when the Ugandan update or create like a users you my one show on your application when the user create accounts like member scenes or things that something like that. So you use that time stump, you need to pass it through the time stuff. Every time we create a new record off a user, it you created it. You adds a created at an updated at. So you know, when they use the last of the account and when they're created so you can use that information on your application. Next, we're going toe export a model. So here, exports cost a new creator user captain, which is going to be a model so longer hours that modern. And here you passed the instance off the user schema. So we created a viable and we're storing this data in here if you call the user and you passing the user schema, which is a new mongo model. So let's start with far schema. We know uses gonna have I am au and password. So let's do email you And here it takes an object. There are three things that you can do for the only thing you must do is tow. Give it the type, the rest is optional. But for password, we know that is required. You can leave it like this. Or you can also pass a message like through. And then you pass a message. Please enter bus words or whatever you want. Your email. You Actually, we want they made to be unique. You don't want a single user Created many a concert with the same you may. And there's one called Dream. The dream removes the space from the passwords present book. If you this is a form the user would would fly view and then puts more space that would remove they space from here and from here. So this is another base type of validation. It's only one in a platter off ways that you can check the data. We're gonna see more later on. So this was our he made. I'm gonna copy this one, and I'm gonna do the same for passwords. So here is required with change for passwords. It's not. Doesn't need to be unique, but you can also adds a few more validation. For example, minimal length. There's maximum lands. And so you can grab this information from the moguls. Mom was just dot com read ducks. So here on this kima types, you can have the type of information you can save here on example. And here are the options that we're using You. Can I just put the string or like we did as an object? We have a require. So I have a default here. These things that you can apply to restraints type off data here, let's at this lower case to the mayor. So whenever they user well, type the bus there may whatever. If it's off like that or not, If you change for lower case here, are they one used for the passwords? So if you ever induct, you can take a look at this schema types and hear the information you might need as well. So let's continue. I also want the user name on about a tax dream, and I'm gonna also dream it. As we saw, we can actually add, just like this is wrong. We don't need to create a new object, so b o drink. You're all stealing and you can also use ah Bulla. So let's say it's at me or not bullet. You can add whatever information you want. I think this is enough. We're just testing. Anyways, let's continue that. So we have our schema. We're creating a new model. Where that schema. Anyway. Also other time stamps. You could have yourself in here like created ants when you date something like this. But mongrels is nice enough to give us this option that were added automatically for us, which is, and a nice and then this user model that we creating. We're saving the user schema, and we're passing it over here and you're referencing with a cap value for a model. So now that you have our model, let's move on. Next, we're gonna learn about the crude, the create, read, update and delete. 11. 4.2 CRUD: Create: Let's take a look at the basic foundation when dealing with that we call it crude. It's a creates great update and delete functionality that we need to. So all the information we going toe learn right now you can find references. See here on the models and documents in case you are stuck ordinate Watson more information through application. So let's go ahead and start to play around with this methods. We're going to use the embassy pattern in our application, which basically separate the concerns into the three modules. You've got our name for model? No, we're it created a model which was the M for the embassy. Now let's create this. See the controllers, You're basically we go our functions and then we're gonna pass it to the views, which is the on the embassy we're gonna do with the V later part of your application. But the main concern off hours now is the model and the controllers. So let's get started. We're going to be the crude in the controllers instead, off doing it inside the shelter like we did before you were creating our source, which would be a user. But we're doing it inside the routes, which is not so good because you're out there. Find is gonna stack to be toe become very big, depending on what you have. Invisible force Tian, when you're creating a user will sign up. You need to very fight a doctor, which you're not doing over here yet. You need to go stuff to eat. Ah, hash a password. All of this information would be here, and then your router finals gets bigger. So basically, you you should always try to make your models. Your controllers is skinny, but never on the rocks. You need to end toe at most of your logic replication logic inside your model. And then they controllers. You mostly see applications express applications where they use the router. They teach you how to create all your functions over here. But I you can do that. But it's not a good practice. So let's get started. First, we need toe important user, the user mother. And then we need to create our controller to create our these air controller user solar. And that set it for the entire object for no. And Leslie, we export. We exported exports. The fault is there controller said that. Okay, with this long, that's creator. User inside our controller. The user request this, Boss. So what? We need to go over here the same way as we created our out over here. We got the request. We got the email and passwords from the body were going under the same. So we're gonna get our user with the maybe passport. First we go, uh, user, and then you're gonna call new user. And here we can get the information they may in bus Word from the request to make it simpler. I'm gonna use our method from the low dash library called Peak. So first, let's install it. And I am the stuff. No, that's not it. Having a lot of the here, so I don't need to install the whole load dash library because they have plenty of this NATO motions here getting so only the ones I want. Like I did, we did waste emerge using emerging here. So here I'm just do not import. Well, that's not now for the user. I can go big, and then it takes two options. This is where to pick from. So we're gonna do the request that body. That's where the function is going to get information from and what we're actually requesting. So we want the made in the passwords. So here we're basically doing what we did over here. We're setting any milieu in a bus word valuable. So the equal. So they requested body, and then we're creating a user east object with that information. This is a little bit better. You just need to remember that the big asked you for where it's a big from and what the people, That's all you need to remember. So another to create this will go user that safe, and that will save our user to guard at the base. And then you could do a Dan and read the rest of her logic in here. But let's use the casing function. We pull it, await over you voice for the user to the saved. And, uh, you know, you have a scene to make it, they think, and here you can just add the rest off your oh logic response that sends you're gonna send back the user for now. So now that this this works, if you tighten belts, you sort of work but we're not managing any mirrors in here, So let's do that. No, you can use the try catch block, and we're putting our our cold inside the trying and then on the country. Just want a sense response. But let's do a status because you need to said they started Stow 400 which is our error, and then we can sends the era. So here you are setting a user with this information that we're getting from the request of body. We're taking this to information and saving it, decide the user viable. We're calling the user and using the same methods from moguls. And then you're sending back successful you're sending back the user. If not, we're dealing with the air over here. Let's try it out. But first I need to hook it up to our routes Now inside the user route. You can do that so as we saw before, and that's a post request. So you know the users, but post and not someone goes toe the last users the same with this one. We're going to get that information back from the equals. So we need to add the users controller as you can see my, uh this is Controller Waas Auto imported over here. But you need to impart because you're using. And then you just need to call, create user in it. So instead of heavy all this information insides here, here, like this We are creating it in its on module. Very important over here. So let's try it out. First of when I started my server. Okay, He works. Open up on you terminal. And here I'm gonna do my age did because so you remember is the h defeat. They just 35. You gonna post are users and you just need to Something may in the bus words. So now if you impress answer There we go. We have, ah, 200 means was successful And here we have a new objects we have I may you I did created that an updated us. And as you can see, you have a problem Over here we have You have no passwords if you check in. Our controllers were passing the password over here. But that's one good point about the mongrels. You can actually you don't need toe pick anything from here because of the whole body so there. So the same method. And then, um, mongrels. We'll see what is in our model and what is in the airport. And it's just gonna save those information that is in your model if you check our model. I made a mistake because I cop it and I didn't put password here, so we don't actually have a password toe toe be created in our model. So when was But when among was received, this information it so that there was no password in a model, so he didn't use it. Now, if you do it again, I need to change my he may. You could do it again. Us created. Now I have my passwords. So here is sending the password. But we didn't have the password here. That's why I didn't save. Now that you have the password in our model, I never sent the information if you're safe as well. But if the information is not my mother, you just skip so we can side out when I send it. Now, here you have it. Object I d and the bus words. So I'm gonna drop my database. So let me create on user again they're going on a successful and I have my bus word over here. You can see you have a created up and updated that in a dates for months. So in the latest, the s code 1.24 Microsoft added, um, plug in called cause must be which is this one? Here you go this as your cosmos to be. So if you start, you're gonna get this new icon over here, and when you click on it, you can attach other the base and here you can choose What kind of that the basic plot features DB and then it's been asking for their address. It's that means the local host ever that actually gives him this information. And here it is attached at the base Macron's. If I do that, I have my local host of all year. And here is all day database that I have. We're working on the development and exposed this pas. So here I have my users that the basin likely he's day, You wanna just create it and I have my objects, i d This is the way Mullah tv. That's the idea of us. And this is also created if you don't find it, always gonna outplayed this idea for us. This is a really nice adult forgets code. It makes very easy for us. Just inside the record editor we can do. All of the staff we have are already be that you can check any time you want without opening up any other application. So let's get right. If you don't have ah yes, cope well should get it. Otherwise, you can use the Mongol compass, Mongol capacity Street to use, and you can get it from day mongo db dot com Musical Gets Mobile You can get the compulsively here, so you just choose whatever but from your own there's a community version, but the other one, it works fine as well, so you can just download it and stop on the campus when you open it, it's gonna displayed this, that over here it's automating this abdu some information over here, like if you please connect, it's gonna connect your database and here you can find the same information that we have over here on the cosmos. On TV. The developments have all users and here you have our NT you can delete. You can refresh without the basically hearing is you have some more. Yes, he did different way. Yeah, for Motley's. You come with the schemers and other stuff, which I don't think it's available here, but I don't think I'm going to use this the moment. So in case you're gonna use any off this other options, we can come back here. 12. 4.3 CRUD: Read: now, The next one is they read part of it. I need to retrieve our users and displayed in our page. So we're gonna go again, a scene, get users. You get the request. In response is their function. We need that comma over here. In the end, no, like that is always. And here we do our logic. We gonna make a Bible call results. So we started information that you're gonna get from their database so you can wait for that information and user. That's fine. We're calling this fine methods in the user model. This fine metal sing us. This safe comes from the mongo DB. And here, if you do find just like that is going to start everything and then you can also change a few more permission. You want to unite physical sort or limits is that this is like a few. We make him a products are least you can limit it toe. No. Last five. Something like this. So But for the user, let's do this sort over. Created that, remember? Created. That is up. He was created automatically by Mongo here. You need to pass this information if you want toe you want to find a person but a name or whatever. It's past the death information here on this art for the fines. It takes a few more parameters. You cannot specify what you want to find the here as well. You pass an object. Thank what they may you. So if you passed some information like this an object with some back over here right now, we don't have this to information a 1,000,000 passwords. So if you'd have, um, something else, let's say a paradox resource that you would call a title and then you can pass the tight over here would find only the title. We can check it out. But first, let's finish it. I'm gonna live it without just find. You can come back to this one. So now we cannot do the same sandy response. And now let's say they status said they started Sport 200. This is common Good practice toe. Always us at the status we want to live with like this. You can Actually, some are stuff like if they stop, those equals two days. You do this If you need that in your application and recently back the results as though the catches well, Status 400. But Senate Herro now these status were using this information. If you search for the http status called is this website down here is http Status not gone ? It's quite nice for my So if you check it out, we'll be using the okay. Which is, for example, you know, user, in our great function, we would pass this status two or one. So either that sand, it's tattoos. True, No one just like that. So that means that was created. And if you're dealing with payments, was a stroke or chew and so on. Now we also have, like, the redirect part of it. Which is the 204 100 are the errors we have. We're using the bed request. We also gonna use ah for Oh, for which it's like if you find a page for simple and he's also like for the payment and stuff so you can search. I own this website or search for H two piece that schools and you can get this information . So let's try it out. Now it's to be And then is the report 88 users. We're getting the user, some least for dysfunction to work. We need to hook up to the rotor. So let's go to our open and changes. Get users from the user's controller with the route. So here we're sending back these user least you want to send that, um, function we created in here get users. So same as we did over here with a create user. We're gonna do the same. They did this user controlling, not get users. Now you can save. And if you go back, hit and search, they're ago would have not rate. As you can see, here is an array and we have the information. Now let's create another user so I can show you the fine method over there. So let's create a post request. Who are users? Here are name you mean in crosswords? There we go. Now we have on you. Object If you go to our database and reload here, I have the other object. So no, let's up on do another as one other request toe the users you get to request now already has two objects inside. Now let's go back to our function controllers And here the find like, Let's let me do this thing I mentioned to you before. So if you wanna search only in May you that contains something let's say only mine then If I save now, if I run on the SDP again Oh, get only mine in here. So the other objects, they're both this. This is useful when you have, like a a resource like a product, for example, that you want to get some information like a category, like for the way, If you have a attack on your product, anyone find all the produce with that tongue and then you would use this here on the documentation on under queries and then you can find over here. So as you can see here, you can odd things, the conditions for the request. So, like this, you can sift through your daughter and find the information, the type of information you want to return or if you only send the object back like an empty object. And as it so it works without as well. When you do, the request is gonna return. They hold our collection only the ladies, which is the same now, One more thing before we go here we're doing. Ah, using the same route for a wet and opposed. We cannot risk factor this coat toe user route, not rope. It's a method that comes from the express welter. And here it takes on the tough, the endpoints. So you do get user controller, Don't get user. That's and then you dough, let's break it down is down into its lines That post is there controller about 38 User, it's like this. I'm gonna format to make it nice medicine. I can delete this one now because these routes are the same for, uh, these two are using the same endpoint. You can just use the route and separate them and the only one. So this looks much nicer and organized. Now let's go meet arm Pretty function or red function to get up. So get Sam proves Redd's get to users function. You go now. The next will be the update function 13. 4.4 CRUD: Update: now the next is gonna be the update function. Let's create our from sending here updates user bycatch. So we're gonna use a method called Fine, but I D and update It's great. Viable toe hold our user and then you dough await user model and the call find as you can see, if you start to type or you just press the dot and start type, you can see the metals available. If you have a intelligence sense. Intelli sense find find body find by the end. Remove Find valuable updates and that's the one he wants. Find my I D and updates again. You can find this information in the mangoes in documents you can have the information here find by Dean find by the an update. So let's go and, uh, continue far function. Uh, what it asked is, of course, the ideas find by i d. So we saw you before They i d is restart in the routes firearms and you get it's from the request up forums. That's the first thing that is asking, and then it's asking also for what is it that is going to update. So we need to pass the request that body. And here If if you just do this whenever you update, is gonna operate in your letter base. But you won't show in your application. So we need to pass on new through. So this is gonna happen. Date and refresh your application application on that as well. Then you just need to do the same as we did before start was 200 send user. Here's the same Zeist Artists 400 was sending the era. So first, let's try it out without this new and then we can get I can show you what I mean by this through thinking. Well, before we do this, we need to do the router. Before we test, we need to do their water. So let's go again. And, uh, as it's always going to be on this one were sent. We can remove all dysfunction over here and here. Let's do the same with this one because you're gonna have the delete you're gonna have some input. See here. Same was doing before, so that's gonna call route. And here you can put things, units. So we're gonna use the foot. You can also put the elite and we're also gonna have ah, gets to get the user's profile. We're gonna use the put toe update it and the delete in case you need to village. So first, I'm going toe comment on this trip, and we're gonna work on the foot. He's gonna be user controller. That update, user. So now my stride out. First, I'm gonna do ah request to our user least so I can grab i d. When I got from the 1st 1 here. No, um, we use the put htp, but you need to capitalize. Don't forget that it's 80 users and then we passed the I d. The next thing it's asking, but the idea And now what is it that you're going to change? Take a look on the model. Let's under quick you. So be a because here's because it's a bunch of fun stopping. There is a space we can use. The boats go in if you enter. As you can see, it didn't do anything. It returns whatever it was, um, before when you did the less request. But if you go to our database here in my user, it was updated in here, So let's change this and add that to that I mentioned before. So we say through I mean new through it's not. Let me try again. I'm going to remove the instructor and breast. Enter now. I got updated and return it for me. If I check out my database, I need to reload my database in here to get the latest. There you go. I've developer. So whenever using the find by idea and updates, you need to pass this troops. So is gonna reload the your application estates. Now that we got our update on Let's committed to get and move on. So I am Groot update two years there. 14. 4.5 CRUD: Delete: next one. It's a deletes Function, uh, back on our resource. Use this controller. Let's tear young and a new function that's going to delete the user request. Dispose Same boilerplate as usual. So here we're goingto go viable toe. Hold the results I await for this off function toe return. So the leads one and here it's going to be the I d and us you we can see here on there that the base This is how the I d saved the other scar When the when you create, they were not going to be created another baseball's. It adds this underscore. So we need to use that. So I did will be the pranced, but I didn't. So here we are, limiting one, and it's asking for the i d we passing the I D. Which is, uh, we're gonna get it from the requires work, our request, not problems after these adjusting to send the results back. So let me just actually copy this block over here. That and also there era. So let's get the welter before we forget, and then it's the delete can implement. And then his user controller, the lids loser, you go. So we're getting down. So now we have our basic crowd you create, We are ready from the database and you're dating and reliability. Now there are two more things that we need to do. Choose one. Get that user profile which is like most applications. Got to show the or the user base, for example. So this would be a basic get asked me did over here with the as we did over here if they get users. But that's gonna look for the user by I d. We're gonna create they use a dashboard is old. That means the user that is signed being like his own profile creates. We still need to do this some gets and they dashboards. So let's commit this Fruits the lids go 15. 4.6 CRUD: Profile and Dashboard: now what's left for us to do is to get the user profile with these. We've done that before with the users which displayed the user list. But now we want to display a single user from that least. So let's see, How can you go about doing that so belonging To create a new function, We're actually gonna be creating two functions in this video when it gets fine. Request was boss, and we also gonna create another one. Get this board press responses. Well, so this one is going to get the authenticated user. It's on profile, and this one's gonna be anyone's profile from now user list. So people would go to the user list, select a user click on it, and you will go to their own page. This you only show for the user that is authenticated. If, uh, you're using is gonna show your data if I'm using is gonna show my data. So let's go ahead and great dysfunctions. So on the top in here we created a We use the user dot find toe, find all users on the list on the raid here. We're gonna use find my i d. So try catch, cost user and user dot find My idea you go seem have mattered over here. And we just need to pass their request bottoms. But I ve now here's the thing we need to do a check If that user actually exist, Otherwise going to return as an area. If you do you there's not there. So if not too user way can were third a response to status for a For remember, the 44 here is not found so user not found. But if it does exist, we go there one we did before it started 300 which is good to go. And then we send that user for the Contra deluding opposites status for hundreds error and we send it here. So let's try this. Get performed. I'm gonna go get someone's I d. I hate it to be so here. I would do now. Http, it's 80. It's last users. And then I passed that I did which is the route we're giving is the end Point slash users that comes from here are in point slash users slash idee the press Enter user not found And why we did not do our Route e. So get use their controller, but get no fire. So now I have our full router gets put the lids get and post on the slash users and on his last users, I d get a profile. We update the profile or the user, and we can also believe the user. So let's try it again. We're getting ah and subject. And here's the problem with your weight over here. So this Ah, Sam is getting is a coated before our data comes back from the server. So if you save it and it's right again, there you go and let's like with the other objects have. And when I changed that idea, other objects there you go. So that it works. Let's get going and do the dashboard. Now the best bored I'm going tojust create the boilerplate because we actually need the authentication toe make you work. It works very. Fight the uses there and, um do what do we need to do? So I'm gonna do the track catch and just gonna send some that over here. So the here in here, I'm gonna send just you must signing first and this one instead of off getting the from the harems in here because he were getting from the your ill When they users goes toe someone Sapporo Fine. It's gonna show it on the of the euro the i d. So here we're getting the problems we're getting that i d from there on their your our But here we're also gonna used a from I find my i d. But you're getting the idea from the database in the database, as I mentioned, has an underscore here I d on this car. So request that user that I mean well, first we talked, escaped the user and then save the user to the test. So first of NATO creator are off system for this tour. When you gonna create when you going to authenticate the user, we're gonna add the user object. So the request we're gonna attach to it so we can have assess. So this idea So this find out we won't work. So I'm just gonna commented doubts. But so far we have everything we need for our user and resource. You have ah create user, get users and updates the lead users get profile, get dashboard. Before we we commit and finish up. We didn't test it for the deleting the user. So let's go ahead. Invest it. I'm gonna get the user. I d from here. I'm gonna let second object. So we dough http, the leads and the idea you press enter. You showed up here. Okay. And if you check your database, you should have only one entry, which is mine. If you want to delete this one Coffee. The one you couldn't go in the late again. So like that. And it's OK. Refresh. We don't have any what was vaccinated anymore. So our application are user. Resource is complete. We need to authenticate the user so we can finish up. They get the dashboard. But the basic functionalities in here We just need our dedication to request the users Then user, there's no s over there. Ana, when our authentications gonna be read, it's gonna ultimate. We're gonna attach the user. I d the user object to the request so we can use it in here. So now we can commit every five plus dashboards. One thing I didn't mention before. It's every time you commit. It's always good that used a linker so remember we could A Today, Jason, we create the length script. So Hughes, MP, an Ron linked, should fix anything. And also through for months. You're cold his own. So now we can continue. Next. We're gonna talk about that, a base security. So stick around and assume the next lesson. 16. 4.7 Choosing What to Display: Now let's talk about Mother Security. How can you protect our database and our users data? So let's open up terminal and start our server. So he find to our request my users. I forgot I related. They won before, so let's do Ah, week, user over here. Suppose now if I do on request to my users so it's not getting saved. And the reason is because I'm trying to send the creating the user is on my sign up. And if you saw before, we're doing it the endpoint in the users. So let's change that because sign up is the good and want to create users. You can check out a route we're using your sign up, your passing this information. So we need to the ladies and instead, off using this, you're gonna use the user controller that create user just see, got important here. So we re part they use their controller and then use over here for the sign up and then on our user. We can actually delete that route that is posting over here so we don't need it anymore. Our first save it, and around this called again that you safe and actually safe to the database. Now we're getting all this information here. This some words Stop forgetting to user i d. They created art updated up and also the passport and the password is in plain text. It's really horrible way off dealing with bus words. But first, let's talk about this other stuff that is coming with their response. We don't need this on. The user DOESn't need toe. Get this information. This is for our own use inside the application. So let's hide this information. And remember, I told you that we should always keep well, should always try to keep the logic in off our application inside our models, like keep the more respect and the controllers skinny. So in our controllers who have all the information to get the profiles into response, which that's exactly what they should be doing. You just sound Wasim poco so the database and retrieve the information it's required, Then answer with some kind of response or a neuro. So our controllers are good to go, but our mothers we need toe workout on how the data is being sent back, and also we need to tackle this bus word hashing. So here, after we create the users Kema, we can start to create some metals and attacks toe that skimmer. So let's go and create here. We're gonna create something that is But I choose user data to send back the client. So here we're going to use the user schema and we're gonna methods This comes from the mom was it is unethical to Jason and this takes a function. So here, you need to make sure you don't use are a function because you need to use the geese. So we're gonna create lets users object because toe this that too object. If you return that object we want, we're not again. We're gonna use the peak method from mallow Dash SoGen imports peak from both speak And here Can you speak and you're gonna remember It's ah were to pick from and what the people . So we're gonna pick from the object, and here we're gonna past it information. We want to send it back. So I d you may you use their name and you Ah, So how these function words First we're calling the method. So, Jason, is your gonna take our database and I'm gonna converted to Jason and you're gonna save it inside an object. The user object from that just used the same. That's to pick the information we want. So if you save it and you try it out, you were getting all this information back. Now we're only one. This one's so if you do the same, it's clear that they're not. And if you do, the same request you see now is returning. Only the other information. The seat again. If I commented out and I save it, you find the same request is returning all this other Doctor, over here. So now you are hiding all these extra information that we don't need. Save it again, as he's. And now it is hiding the password. But our password is still saved. Us plain text. So we need to fix that. We're gonna do that in the next lesson. 17. 4.8 Hashing Passwords: So now us we saw were hiding the password from the view. But is it still gets transmitted over the Web? And that's a big security shoe because he saved us. Ah, plain text. Anyone that has listened for pockets over the Net, it's gonna be ableto get that information really, really easy to solve. These were hashed passwords and then save the hashed password into our database. After that, when the user signs ing with the call that the hash password and compared if they user password input. If it's good, we can move on with the authentication and it is not. We're gonna send that hero back. Hashed Passwords is a must We should never, ever say they user password in plain text. If someone grabs hold off your database, they would have assessed toe everyone's password and usually people even. I confess I use the same passwords in most of my icons. It's I shouldn't. But most people does that. So if your database gets hacked and the that password gets licked by someone, do you have the persons in May and the personal password, which they can use to try be any other websites? That's probably the buster is gonna be the same anyways, so we're going to use elaborate called decrypt. As you can see here on the NPM, Uh, there are two implementations for big creep. Decrypt is actually beauty in C plus plus and then they ported to a few different ones. But if use playing decrypt, you might have problems installing because he needs us in simple plus plus compiler install on your computer and you might not have that Soto other that we can use the become a J s, which is the same, but it's completely written in JavaScript. But it will be, uh, less performance than the C++ counterpart. Just bear that in mind. As you can see here, there's a weekly dollars is 177,000. It's a very popular library. Let's install it and see how he works. When I clear my turn now and my basic commander here now we're going toe use that library insider model, so we need to import it. The crypt from Js for a big ripped from the crypt us. So we reported and this is what you're going to do gonna hash passwords before save to the database mongers has some life's lifecycle books that we can now use to create our functions. One of them is the three that were going to use now and you have post. What they do is like it's something that you can ah function that you can create any visible users schema 0.3 and here greater function. That is, it was going to say before safe and then we can pass the function we're going toe. What is it that you're going to do on this function? So basically, here we are going toe use the free and mongrels life cycle. So before we save, we're going to do this. They think, and we call it function. Remember, it has to be a the full function, and you're gonna also passed next and explain in a bit or despise it. So first to get if these this is the user, he's most five. First, you need to check if his most fine and then with the passport. And that's because, for example, if they use to create the password, you'll be first time, of course, is gonna hash it. But if they use a change, the passwords we kind of need a way to check if the passwords is new or not before saving. If you don't do this, it will hash a password on Lee when he creates the passwords. When it created, the user created his account. Not when he updates his passwords. So now we can do a salt, a weight and any corporate decrypt and do that generates south. That's is a method that comes from big Crips. And here is the South Factor. So I'm gonna call this not password, which is the user, That password, and you're gonna wait again. Could be cribs, got hash. And they knew this past both the bus work and this salt we're checking if the password is much fight or being created, and then we are creating a constant. The crypt is generating assault with the factor off them. And then we're calling decrypt again toe hash, the password with that salt. But for this work, we need to use the next. We're gonna learn more about it in the middle, where class you need to tell the application to continue for code. So the next tell ah, mongrels that you've done it and it can go on ahead and save your data. So we called next. If the password is not about five, we just call next time we don't leave it, we don't need to do anything. So let's recap again. Here we are using the are great book from the Mongols, which is gonna do stuff to your doctor before saving 1st 1st checking if the password has been most fired or not. And if it is, we're creating asking B crypts to create salt with the tractor off them. And then we are using because it again toe hash, the passwords, the user password with the salts that we created here. After that's done, we just call it next to pass it to the next function, which is would be this saving. And if you nothing, that if the password has not changed, we could just call it next. And this function one run. So let's try it. I'm gonna save it, and I can create a new user. It's to be bulls must sign. No. So when I pressed Enter, my user was created. I'm getting the good information over here that we did in the previous with dysfunction. Now, if I check my database reloads there. Go. My user password now has this long, harsh sting over here. Now, in the authentication part of your application, we're gonna use big Krypton toe be called this hash and compared to the users in quotes. So now we have two functions in our model. So let's save our work to get plus word cashing, but also push it toe my repose store. 18. 4.9 Model Validation: So now that you can started after the users can be opposed to requests, let's make sure that they're sending the right data that we asked them. This is called validation and is a must do. If you're working with user inputs, you should never trust the users to send the right information. So there are many validation Middle wears for Express, one of them called Joy, and is very popular and has over $1 million there week. These giants part off the Happy Js. Different work for no others. Well, so you can get grab some FBI reference here later. Here's an example. How to use We're going to create a function inside our model. So first, let's install Joy NPM install Joy. Now I just need to import its here. I'm using Capital J because joys classmethod so just below all the way down in our mother. After way, it's part the user. Let's create an export of function that's gonna validate the years of that and so export function. So you I think the data you'll be the request that body. So inside this function, you take a look at the joint example he could. It's Ah, schema with the model data the mother fueled and then you can call your validation inside in it. So let's do that in here. Create a cost for schema. So is joy that object? No keys. This is to pick up each of the objects inside them inside their modern model. So let's do it. May enjoy the string first. And here we just change all the politicians. We need to know that we need a new mayor Now we can go bust words. Shine that string. It's also required. And let's AB one called me many more length. So six, Remember, we're puts six over here has been holding and this will serve as a second layer off protection. We're all data. So after a creator schema, we just need toe pass it to joy. So return joy. That's about a date And here takes the data and this schema. So the data you come from the input in our controller and the Eskimo is this one of you? So let's call this belittle date function Insider controller create function its user. We're going to use the very day to use them. So here to try. That's first rate valuable that is gonna extract the air, responded some information. We pass it here through the request of money. So now we can check if there is a mirror. We're does something with it. So return response, that status gonna be 400 is a hero, and then we can send the information. That's first. Send that Europe so we can see. How is the object? My terminal. I'm gonna start my server first time in a moment of you seeing them start. So here. I'm just going to send the on empty most requests. So sign up. So, http ghost 80 80 sign up. So we're not getting any aero over here is because we are using the function, but we're not important. It's on the model. So we need to Abbott over here. And now if you run it again. There you go. We have these objects with the error message. If you remove this joy validation era and we try it again, we're gonna get this big, long validation error here. And this comes from among with the big but the work with Mongol divvy it is a little bit harder door customized the air a message. You're gonna have to create a lot of boilerplate. I'm gonna show you now how toe customize the message with joy. You see how easy it is? Somebody bring back there validation from enjoy. And here again, we're not dried out. So we need to get this message over here. So era the details, which is that it tells over here. Right off. So now I have this Ari. Um, all right. You need toe iterated through the the iTunes inside so we can get them message over here. So that's the first item. And then we can call that message when you do that. You We have our message over here, but not to customize it. We don't really have an option to customize them their message itself, but gives us a method called label which you can change into our mother over here. So here and they may. I'm going toe that neighbor and here can pass a message. But you can see the label that you're passing over here is meant to be the label Over here . Furano, There you go. So change these. We need to go back to our validation air a message over here, and I'm just going to remove these and I'm gonna course along the detail again. And here now, we have this context. The keys in May and here have the label. So we just need toe course, a look there context not label instead off your message. So here, just door context, not label. If I do it again. There you go. We get our actual labels on the model here. So let's add it to the man today. May. And they may you? What can go wrong is the minimum length of here. So let's other message that Saiz plus words still short. No, I'm gonna run it again. But now possibly maybe you in the past, Ward, we just got 123 And now there you go. Bust words still short. So now we have our validation with Coastal message here in the joy npm page. There's some examples over here, and also the a p I reference in the reference Yeah, all the that. The types with the methods that can call on Lee on them. And then if you click on them, you can find some more information on what they do. So now Let's commuter saver validation to get over, get status, get on it. It's a message, but a day to use their input, it's gonna push it toe the start as well. 19. 4.10 Model Sanitization: validation alone won't do as much. We also need to remove or replace any data that my have some malicious called What is we gonna use Another library called expressively data. This library also those validation, but it's not as popular as joy. So this is how it's done. You call sanitized body, and then you passed name, I tell you, want to sanitize and then you change your the methods. So let's do this. So we're gonna add a team and escaped. The dream is going to remove the white space, the same as we doing here. And we're also gonna add Escape, which is gonna replace any programming coat with some singles. So let's see how it works. We cannot sanitize the update and they create users because we get those are too. That is, we're receiving that A from it's here and on the router here. So let's start with this set up after the brown you're gonna bust in the rig, Isn't it? Nice body and we only need toe sanitized a May because password gonna hash. Anyways, that's what you're gonna save in the database. So it doesn't really matter for us, and we can call team and then escape I that spritzer toe. So this is our middle where when you think parkas sent ties body and before and if you win , you toe actually started. So any Fiemme stall expressed bullet data, and this is what we're using sanitized body and sanitized fields. So to imported, we need toe you part So thighs, body thrown, expressed by the data. And here we gonna use the future because this function is inside future. And then we can I skim off a few kilobytes over here and see if you don't put that 53 kilobytes. If you have it little bit less. So now we have access to it. We can use it. There you go. No less. Right off here. I'm gonna do that. Most requests again. Bossa Rio Password? No, with more than six characters. Invest. He was passed, was created. Let's check it out. The base. So he was created successfully. That's right. Out to the user update. Now here. We're gonna do a few more. We need to go on the Iran biography user name here on the photo. You really don't need because you're going to use the same type anyway. Toe holiday photo The much we need to do, they may again. User name, biography and you're out. So, Mr Denton, same thing again. We pass in the rim, and here we can do all day. Sensitization. That's body. The media also dream and escape. So let's pulling their sanitize body stock copies from here. So here to save time, I'm just gonna properties. And I'm gonna based a few times he was their name. Bill in your own. Someone fix it up with 32. So this is what we're trying to avoid. Whenever the user you send you some data, they can actually use injection. Inject some javascript to run behind your back. So if you do our HDP put requests, so there should it. Let's get user I d. First, but request that user. And here I'm gonna bust. Was her name falling. So far so good works. We have our doubts over here, but then he fell on to send something else by this. If I sent the script a javascript function over there. If I don't have this escape here marked and I send it, I'll get the saved. So whenever people runs this cold and it's not proper, sanitized. This function were wrong. So let me malicious hackers can send any kind off codes and because you didn't know sanitize it properly, it's gonna get saved, and it's gonna get run in someone's computer. So this is really bad idea. So, Allah, sanitize your daughter. So now if you do again with the escape, as you can see over here, I have the electable here. And if I send it again now, it got replaced by this much of symbols in here. So here you're escaping and we're replacing the HTML tanks with this information you can actually remove instead off replacing them. This is totally up to you. This is something that it's really worth toe. Get deep in tow. This is something that you must do on every application. You can never trust music. Send the proper data. So basically, this is how you do it and why you do it. I urge you toe learn more about this and act accordingly because this is not cool to live your up open like this without a proper sensitization. This library uses some another library under the hood. Call validator validated that? Yes, by this guy. So if you scroll down, you're gonna see their sanitizers over here. He says you can blacklist because you're doing rejects and stuff escaped. What we used this is the stream. And I came over here, but we did the dream, which it does both got normalizing. May you here is, like use cases. The Pentagon day milieu you're using. I wanted to assure you something. So here you are. They may schema. We need to remove this lower case. That was just to show you the possibilities. So back in here in the normalization here can check which ones you need, like toe. Get the gym mayor Outlook. There's a lot of options. You can also change the doctor toe whatever field you needs. Like if you need the update, it's to make sure it's a date or it is Ah, integer this one. Is that one to be used as well? So here we get more information. So now let's commit to get status. Get get cm. There you go. So now that you got out not too secure, we've password hashing with validation and sanitization. Let's keep going and we gonna learn about me. The wars 20. 4.11 Challenge: Create New Resource: so far, we've learned how to create group functions, create breathe the late update. We also learned how to create the routes and, uh, on our model, we learn how to validates. And we learned how to you use external libraries, toe sanitize the user inputs. Now it's time to put this knowledge to a test. I want you to create a new resource with the following. It's Kema. We call it shots because what we're going to be building, it's ah, what for you up where users can upload image. And if you have a title description, a now tour and it's either gonna be public or not like as a draft. So I'm gonna create a file pretty model, just like we did over here on the user user, that model. And here I want you to create a resource for the following schema. That means creating all the Croat functions, the routes and validation. So go ahead, try it out. You're free to use the mongrels documentation. If you get stuck over, you need some more information. It's a mongrels dot Js mongers Js that calm slash knocks. So in the next vigil, we show you how I created mine. Good luck 21. 4.12 Solution: Create New Resource: So welcome back. This is how I created mine here in the model. I've added Jamie on title and description. I've also other required for the title and for the altar because we need a ni de over here . For every post I've created on the fox False for the draft, he goes straight Oh force. And they have to Monory make it public. I mean, party Mongols, giant and big, which speak we're using over here toe send it back. Just information we want. Like we didn't you? The users I'm exporting shocks the model and here, doing some validations title and sending back some a hero message on title is required for the scripts on just checking if he's a string and the outer is also required because the user must signing so we can get their user i d And then I'm check into that and this schema So on the routes I've got the main routes and the rots which forums I mean for to express and sanitize body here I'm exporting the shot rather which are important over here in creating endpoint with shots shut Welter. So here I have I'm gets to get all shots and opposed to create a a shot With this sensitization on the title and on the description, the rest off the items from the model it will be internal. So we don't need to sanitize the altar is gonna be the i d. Much we're going toe have Ah, whatever image user upload, we're gonna hash its name and you're gonna send it ourselves. And he is either two or four. So no need toe sanitize anything for the problems I have gets boots and the lead on the boat. We also doing some sanitization for the title and description. Now, on the controllers, you're an important day shot model and validate shots. I mean, party picked. And here you are. We got a track catch here doing the validation. I'm creating the object shots from the user inputs that we get from the request body, that body, and then I'm awaiting for the shop to be safe. When he saved, we send it back to the user to the application. If not, we got and there are here to get the shots. This is the shot list we just use find. And then we're starting by creating knots So we got the latest on the top and then we are sending back the results. Also, we got a catch toe, send it back in ears here is to get a single shot and you're using the find my I d which you get from the pounds from the route here. If there is no shot available if this idea that we get has any mistakes so it doesn't exist were sending back on for four that the shot was not fouled. If he's found, we can send it back to the shot. And also Kochi in here top today to use the same as you did before. For the user. We used a fine idea. An update. It takes two parameters. Did he actually he takes the i D. Which I can't stop date and then what stopped dates were getting it from the request a body and also the true is just toe refresh our application states. Then you're sending it back and cut years to the later used really to one function from the bongos. And then you were passing the i d as the parameter Cindy back the results. So let's try it out when I open up my Tirreno and run my server here, I'm gonna do a request toe STP 88 shots. I got the name Terry because you haven't got any yet. That's great. One most, capito. I'm gonna send the title and the altar, which is required the outer. We're gonna get the idea after, but I would just leave it like this for now. There you go. You defaulted to force, got the title, and he was created. Idea. I check on my database. Now. I have the shots in my new objective earlier. So now let's get this idea. If you do a search on the shots that the shot list now we get the one. You know, we can gets the detail page here, have the shot list, and now the shot litter. Let's try to predated. That date is put and we're going to updates. Ah, let's update the draft through. So Noto make make it public. That's true. If I refresh my that, the base. When I look in here, he changed the truth so we can did so. Let's try to add warm or when I description. And there you go. New description. If I reload by that the base and nightly creaked again. Here I have my description. Don't. So now let's check the delete. When I copied this idea, U H ticket delete shuts. You passed the ideas, the parameter you go. Wow. I check my database. I have this money here. When they were loaded, it's gone. If I do it is to be request for the shots. I get the emptory again. So I hope you managed to create these by yourself and no, have a full blow new resource that we can create, update, delete, get the least m Also the detail. 22. 5.1 What is a Middleware?: the middle of a stock can greatly improve your application. They're basically a series off functions that your applications go through and they get transformed. The camp changes and improvements on each of them. In a nutshell, it can run some cold. Make change to the request response, and you can either end the request response cycle or call the next middleware in the stock . Middle. Where's function have assessed that very question response objects, and they also have, ah, next function that comes from the rotor, which is used to pass your application into the next function in the stock. In the middle, where stock it helps you, the couple cold and also organize it, making it more readable and easier to the bug. The bread understand how you work. So let's build a simple middle where so it can grasp all the moving parts. And then we can go on and create more complex metaphors. We're going to create a simple middleware that we love the request method and the euro back to us. So inside Almihdhar, that's export function call longer, beginning whatever you like here with the request response and next I was in this young yet , but there you go. Next. Here we just need to console log and a science. We was back. Tick physical. I used think population. Let's say incoming requests the method. We've status. Here's we're gonna pass them. Start to this Will response that status coat and let's and the euro was requested. Next we just need to call the next function and this your move on. So what now, then? Just to use this blogger insider application, as you can see here, would have a few me the wares that you were using from body parts. Sir, we just need to add this longer. So we dio that use and you passed the longer let's import London universe. So if you run our application, everything works well. You check out the local host on page incoming Get request They started 200 to the roots. If you go anywhere like users, that's changed the euro and still 200 we're passing our function are up inside this function which is gonna check the request, the response Get this informations and send it back. So the next one which will be the rotor. So if you add more your application is gonna pass through all of these functions until you get so to the end. But most of the time, because express has ah, large ecosystem. Someone already created a middleware for your use case. Whatever you can think there might be Ah, middleware out there to help you out. In this case, check out the express website. Well, resource made aware you have a least off middle wears modules that express recommends. And if they could look at this main ones over here. You have Uncle Morgan, which is the HDP longer. Let's install and check it out. He was gonna go something similar. What we did we far longer over here got the methods status, schools and request of Europe. He's gonna pass all this stuff this a response time as well. So let's see, starlet and check it out. We'll open up on your turnover here in the end, installed Morgan and inside are up just below, But a passer I'm gonna What? You wanna call it longer? You can call it whatever you like it here, Morgan. Good. Now commenced out our with the where and here is going to use up meth use longer and here. Gonna positive. So the death you have here you have tiny we have combined redefined for months over here. So let's use the death and find out Close my terminal. This is all the Syria and run it again. Now, if I go all my page and I reload, I got this information over here was to get request to this year. Oh, is a 44 And this is how long it took tow. Run it if I run it again because was cashed is less. So you find toe users. Is that three or four to EUR 40? Some request, but there was cash, so nothing changed. Return the same. They took 12 seconds. Children milliseconds. So that's basically what it does. So I'm gonna delete this one. They want to create it. And just because they Marvin for now Hey, I'm gonna comment it out so you can have that information for your future reference. But here's another thing you are using the longer helping here. But in case we want to keep this one and on Lee run inside our development environment so we cannot make if statements you're gonna make sure that the op is running on the development. You get the environment with up that gets. And here, if that is equal to development, then we use the longer if you're not, if you're in production, this we're not running, so it's better like this. 23. 5.2 About Static Files: So next week and check it out. How to use the static, which, you know, served like static finds like we have over here on the assets like the CSS and things like this toe up to your page you need to use, they express static. To do that, we're gonna do it here on the top. It's going up not to use. And that comes from the express of eternity style, anything score ecstatic. And here we're gonna need the path because we need to get this asset folder to get these information. So we need to import it. He remember path is belongs toe the note from bus. They're buff. But, John, because we need toe get the absolute path, which is this one's gonna give us day, whatever folder were working on. And then we gonna need the assets, which is our assets over here. So this one consider note this is because of difference between UNIX are when those computers that they start another in a different place. This one's gonna normalize your doctor and give you the absolute laughter. Your assets. So that's why you needed powerful 1,000,000,000. The knife. I'm gonna add a folder here go. You must and then just gonna download something, and I'm gonna put to it. You can download anything you like. It's gonna get then note log, and I'm gonna save it inside my image folder. He was gonna rename it Tow Boat or make it easy. You know, if I goto the browser again in my, uh, Fido slash us slash note. But the engine I'll get my image without this. But all this meta where you wouldn't be able to assess that you much over there. So now we can add, uh, any type off static assets and we can use inside their application. 24. 5.3 Handling Errors with Middlewares: so far, we're getting years, but we're not being able to display none of them. So let's create a few the words that is going toe despite the errors for us. First, I'm gonna do Let's do, uh, made aware for not found, like a 44 page. So again export cost because you're gonna get somewhere somewhere else. So not found. That's the response. And next, let's great that cause for cheer. I can create a new era and to see whatever you like for four page not found. And then it's changed the era for the status it's a for for and then you can call the next and pass that this hero. So here's the thing. This is not gonna do anything if you don't have another function below that is gonna handle this error. So let's create them either, where that's gonna use this this era from here. Call it the fault zero number. So we're gonna respond with status or flax. Hundreds is either gonna have ah era, or you're gonna call internal server error, which is the 500. Then we can send me back the message for this one we don't need next because this is gonna end with the sand over here. But you also need to get the era, which is another thing that can you cannot get on the economy, the work, and then you get a request and then a response. And then you call something else, which is the next. But here we're gonna enter this end. So this one, it's it's passing this era down to the next one which is gonna log the arrow, and this one is gonna finish the middleware stock. So let's sell import toe indoor up so we can use it. Import for me to wear you have not found. And also the log errors for the ears. You need to add it after your outs because it needs to catch the heirs from the routes. So go app that use that's phones. And after two years, uh, log paris here. We're not calling a function. We're just passing the middle where the media wears is on actual function. And here's our era stock and loose. If you save it and let's try to run something and crash our application, I'm just gonna close this one so we can see a term No, it's running. Save it. It's OK. So if I go some page that doesn't exist. I get the for a four and page not found. That's the message we passed over here on the middle. Where? And it also get it on on the server logs as well. So to recap, what is what it is to meet others are doing this. One is catching the era from any kind of page. If the right doesn't exist, it's gonna create a new era. This is a tax changing, the status called and then passing the ball. So these next function over here and this function is gonna I don't have the status from here it because the mirror has to be either internal or you need to express if I ous we doing over here? So 500 is internal server error. So is gonna be either this one or double, and then you send me a message. So to continue, let's get a little bit deeper. We're gonna do if if you see here on our resource user controller, we're using the try. Catch all the time here in every function using these, because on the A sink await. If you don't catch the aero and something happened, it's gonna break your happened. You're not gonna know what's happening. So anyways, we're gonna create a function that's gonna wrap this route and then is going toe to get us that hero. So we don't need to repeat ourselves all the time here that the order doesn't matter. So let's start. We cannot create. You can call it whatever you like. I'm gonna call my catch errors, and here it's gonna take a function, which is our out function, and I'm gonna pass it to another function. So this function over here is this. So we're getting these information and you're passing, though here now we need to wrap it inside the middleware function, Do you remember is a request response and the next That's why we're wrapping that function in here because we need the next now because they they think it always returns a promise we need toe get the try catch. So we cannot should get there. So he's gonna be that function presser supposed. If there is no hero, we're just gonna pass the the function the way it waas. But if vehicles are era We're gonna catch the arrow with the next and passed the era of them, same as we did over here. We're passing the error to dysfunction to display it. So basically, Rick, up here, we get any day function from here. And then you were rapping. It's inside the middleware function. Like this one we created because you're doing a sink. Await. We're going toe. Use the track lunch toe either. If there is no era, we don't do anything. But if there is, we get in the era and send it to dysfunction. So not to try. We just need toe. Come here removed this. Did I catch blocks? So it's gonna remove all of them. Remove the right, And then over here, somebody's gonna use creature toe clean up the court, so that's much more readable. And let's boilerplate notto make this catch error function works. We're not going to use it in a year like we did the others, but we're gonna pass it to our outer. So here we're gonna important. We need to go up One look, One more new doors Now here it is. You gonna wrap this function? This is the the function we're wrapping and we need that information here. So to get these requests and response over here, we need dysfunction. So in the router, we get that function and you're gonna catch errors. The new passenger function now. So this is this function, and then you're passing it down to dysfunction. So now we just need to go. It's for all of them, just like that. And we also have some okay to user over here. So now if you save it and we run our let's go to our user space, everything works. Now let's create an error so we can see the results Gonna go to my get the users and here instead, off sending the result back. I'm gonna Dylan era Just write a message so we Oh, no, Because that mean me the where so, Mr I don't if I refresh my page So now our function is working Everybody sat sending us the era So let this weaken reflector o r Facing functions and you can write less goals and, uh, we keep it dry. Don't repeat yourself and it is much easier to the book. So this is the power off middle wears you can modernize your cold. You can remove some off being complexity off one function, break it down and use the middle wears toe. Pick your code more readable and easier to the bug. This is a stock because from the top to bottom passing the information now and the last one on the stock issued always end or send something like a year is ending the era message. As I mentioned before, here on there Express page, there are plenty off order me the Where's that is really good for us to use. Like the compression this one's gonna compressor your responses. So is less data going down to the user Cookie Parsa is to be able to read a cookie. For example. Cars is do able your application to talkto other websites. We use Morgan the motor. You can use it toe upload image, serious static. We used it. They express a static. We also use the favorite com using the body parts that we use in the Logar. Here's some other ones. The helmet. It's quite popular. This is gonna add some HDP Heather's like SecuritE stuff for you. Publication Passport is a very popular one as well in the express community for authentication and authorization. The more you work with expressed, the more you see the need for, um, using me the worst, and then you can learn or create your own. So I see in the next lesson. 25. 6.1 JSON Web Tokens: replication is the way to control what years there's does and what they can do, innit? That's where authentication and authorization comes in. Authentication checks, if they use it, is who he say he's an authorization is whether he can do stuff or assess information. So we're gonna use something called J. Some wept token to authenticate users, so it's a bit like when you go out from a nightclub or a cigarette, you pay to get in and you're there and then you want to come out for a smoke. You just go to the entrance secure to give you like I stop in your arm, and then you can come back and just show that stump. That's the Jason. What talking? That's that stump over there. You don't need to go through the cashier again to pay the entrance to get a. It's similar to like you don't go through the signing again. You already have your stuff. You can come and go as you please. So that's what they Jayson Werth talking does. So let's create one, and we see better how it works. We first need to install Jason. We're talking, so let's open up, up there. Now I'm gonna stall Jason Token, and this is gonna be a model method that we're gonna create for our users. So in their resource, the model? No, just after our to Jason model. That's great. And other users kema methods and he lets you generate off token. You can name it whatever you like. So this is gonna be a function here. We need a function because then it'll says they use them object from this model, so we cannot use them are a function. So let's call it token. It's gonna be a JWT, and we need to importance one. So you on the top JWT strong, Jason, why poke in? We're also gonna need the conflict because you need the configuration. So jwt, what is that medical sign that comes with it? And here it takes the information that's going to pass these libraries Gonna sign a token is gonna create this talk and force, and inside you can put whatever kind of information we want before this kind of tech. Most upsets would use Cookie to start this information for this session. But the problem with that that cookie it's very small. It doesn't fit much stuff. This is where both the fares they cook based authentication and talking Basic indication the cooking. You'd put something like a session I d. So you could identify the user authenticated to it, and then you delete a cookie and the authentication is gone For the talk inside, we can add more information. So here, we're gonna on user I d. And you're gonna also adds you can add all of these if you want. But the problem is that this talking is gonna go back and forth with all with every request . So the morning, the bigger you make the talking, the more bandwidth we we consume to run your application. So let's create an object over here and here. I'm gonna answer the user ivy. Well, it's underscore because that's how long was start the data. If you see over here, that's idee. Underscore Ivy. That's how long ago it starts with that, not Longo's. So this that I think because you're getting date user objects from this model, let's also other if Adami So let's keep it simple. We can house on like who the person is and what they can do. Keep it simple and short if you want. If your application needs it, you can send more information totally up to you. So after we create our object with our user, we need some kind of secret key that is gonna be used to sign. You're looking so let's ah, actually created. First we go toe coughing. And as we have this one here, lets great because you don't need this one. So JWT booking double t secrets your mother like that? Same for the production, Mr Devil. Now, so we don't forget. And now we can go to our that end and creates our secret over here. This can be actually anything you want. My secret keys. Fine. This is particular to your application and is used to send to sign You're talking over him . So our fig secrets secrets credibility secret. Okay. And now we created this token. So we just need to return this information and call this an engineer. Its function. That's for starving. They sign up, use this controller, get used a great user when they use their sign up, and then we save it. If it's everything successful, we can Mom actually call that function user dot generate. I need to put this in, Ah, variable. Because you need to use it now on the response over here. As I mentioned, the talking is gonna be passed on every request. So we need to respond with that token down here. And this is how you do it. You have. You send your status and you send the information. You can also send a Heathers the response that tethers so that. And here you have the information, the name of the talkin. He can be anything if you take a look in the your vacation here, I'm on the first time this server running. I'm on Firefox. So I have this little thing over here that comes Boutin. So if you go Heather's, you can see all this stuff over here. Cook them type. These are the basic ones and those that meet over I mentioned before, only resource me the where this one here helmet is gonna set some of that stuff for you. Which is this one's in here. This middle is gonna add stuff to your heather over here. And this one there was that started with X, their custom. And this one is probably added by the express framework somewhere. So we're gonna add, Want to hear for our authentication? And here you can pass the name anything like when I call it assess broken and it takes the name and also the token. That's why you creating their the constant here toe hold them, generated token. So when you save it, that's, uh, Ron. It's so we can see what happened. So it's a post request toe sign up. Post just got great. Recused or him No press enter. We're getting on their own. And that's because I made a mistake. We call it off token years and just put generated token if I run it again. Got a replicated there. I'm just dropped. Quick. My database. Over here, we'll run it. And here's our assess token. The user was created. We will buzzwords hushed, and I got my token on the heather 26. 6.2 Authentication: So now let's continue it far. User authentication. We're gonna create a signing function, you see, requested in the response. So what we need to do over here? We first need to check if the user exists. Then we need to decode it. Half bus words. We also going to create a new talking. He says token. And then we're gonna returned a user and they're talking. All right, so let's start by checking the user exists, create a viable toe, store it and await user dot Find one. And here we're going to pass the email you because that's what the information we're going to get from the signing. Like you're gonna ask the user for the 1,000,000 of US board and then it's gonna come from the body. You may. You. So now we need to check if there is no use air in here. So you not user. We're gonna send era. We call returns so we can close the function. Stop stopping it from running any further. You say stop to us for four and then sends invalid passwords, e mail. And this is a good breaking here because present for you don't want to say like out our user with this made it doesn't exist because people might just be fishing. If there have, they have they use the right made to use for that user. So just say either it's involved. So you don't actually given information for any malicious user Toby performing around. So now what they call the passwords and here we're gonna use our function from the crypt called decodes. So viable toe Hold the passwords. That's important. But crypt will be clipped. Js So you're gonna call await and we cannot use be crypt the crypt. And when you don't dot you can see all the methods they has. So here, we're gonna use compare. It's going to take the user inputs passport. They want that the signing with. So we get that from the body, same as we do. They make your passwords, and then we used a one that is stored in our database, which is the hashed passwords. So now if the password is wrong bus words his room, we can send the back error message for hundreds time sense Samos this message in here so they won't know which one is wrong so they can be fishing for information. Now we created talking. You remember We have the user generated talking from the model here this month. That's what you're going to use over here Now we're gonna start it broken, so we cannot send it back and just called user doctor in the rape. Now we just need to send it back. So the talking we're gonna put in the header, remember? We call it assessed open in here. The second part is they're talking itself no statues. 200 was good stuff we can send back to the user. So let's that I don't, uh Let's first create do they're else. So it's going to be here. We have this signing the gets signing, so we can That's their own first sign me. So this is what we're getting over here now. We need to create opposed, so it's gonna copy Nissan changed to get to post and here instead of dysfunction, I'm gonna pass the user controller and then called the signing function. So save it. And last time here it's supposed upto First of all, a creator user. Good. No consigning. So here supposed son. There you go. Successfully 100 back. We got our token are password was the coded and it returned successfully to us 27. 6.3 Authorization: so know that you can sign in the user and we're getting back there talking. We need a way to verify if the stock it is valid if he's not expired, and then we need to save the user into the request so we can use that in our application. So that's great to me. The way that's been under that for us. Canada will delete this longer We created before and first. And we'll import your things because you're going to be using this JWT lie, Marie. So we need to import. They convict and the Jason Webb talking library to convict. It's no in that bath anymore. This in the same level of us, the middle where so this middleware is going toe validate our assess token. You can call it what? Every life in chocolate authorization. And, uh, he gets requests, response and the next. And so here is what we're going to go. We're gonna first get the request. The token from here from there. Heathers. So that's great. A viable toe. Hold it. And, uh, it's going to be equal the request header. They need to pass the name off the token. I insist. Oaken right now, I need to check if these are actual talkin. It is The user is not signing or his stocking using violence. So here it is not the talk. If there's no talking, we can risk sending back. I stuck doze off for three for one which is think is the nine door not authorize something that so you must signing first if they don't weigh can now create Did I catch and doted Decoding the verification off the token So dry touch Here it is. The token is not correct. We're going to return for hundreds So here we're gonna very fight a token. And we were looking for this information here which we added toe our token. So when you the secrets and the token which are getting from here. So when you create how viable we started user info which you're going to be getting so g double t very fine. You can see if you're president. You have a few we used assigned to get toe get the token itself to create the token and now we need to verify which is gonna do the opposite. And here a passive token and also the secret case off the library can decode it. Secret off secrets, the ability Secret. Okay, now we need toe Add this user info to their request user. So we have access to that user inside the request just like that. And, uh, if O is done correctly, we should be ableto do the next ends it we were, and that's it. So let's try it out inside in our one off our routes here in the user's controllers, we created the dashboard for the user. So let's document these Now that you cannot have access to the user as we're setting up the user over here, you're gonna be able to assess it over here. So now you need this anymore, just past the user. Now let's create the route, and we're good to go. So this dashboard route, you can add anywhere you like here on the user's if you want it in here, is gonna have his last year's in. Slash me. Old rather putting the route in the roots router so we can just have your, uh is lashed me. It's a simpler route. So here, I'm gonna call roger duck gets, which is a get request on me and then, uh, firstly called authorization. And then we cannot if it's authorize, we can call the dashboards. So from left to right, you want to rise first, and then you do whatever else. So let's sign me again. Get the new spoken in for here speaker for when you are near term. Now it's gonna do this again because when you're copying from the term, now is not so nice. So it's gonna get at some spaces in there. So it's in my, uh, go wrong when you're doing that. So let's do Ah, htp requests to them slash me. And here we need to pass the access token. And that's this answer. There you go. We get our user back. So here in the me on this authorization me the where we're asking for the token and that's it's toe assess it. This we're passing over here. So if there is no token, just do our HDP call today his last me. We get that you must signing first. And if there is a token, we get the user information. We set it as a request that user 28. 6.4 Role Based Authorization: Now let's do our role. Base authorization. So far, only talking. We're getting this user info and we're passing it inside our request. Accuser and these, uh, user info contains that user I d and they if the user is at me or not. So we're going to use that toe checking the user. It's me. So we're going toe create a new you know where which is Just gonna check User. It's on me. So here's same sport. I'm calling it at me, but in time, however you like So here. Just need to check if that's a request. That user, there is an ad me in it. And if it's true, So I'm gonna do you because the user it's at me if there is, it is not fun at me. It's going to return a status response Stuck whose far? 03 And we're going to send that Ah, any message? No. And if the user is at me, you just call it next. So for that to work, let's drop the database first. And then I'm going toe inside. The user wrote here on the right. I'm gonna important that at me and also the organization and the organization is because for dysfunction to run, we need the user from the request. And, uh, we're setting the request up user here on the authorization. So we need to run the authorization and then add me on that route. So let's go on the lips authorization and then they at me. And then we can do the delete if the user is authorized and if he has a valid talking, we saved the their information. You save his information inside the request, the admin you use that requests both user and check if it's at me and if it's not, is gonna say no. And if he's it's gonna go for the next the next. And then it's gonna bust. So this village user function. So if it's oh, good, we can try it out, and it should work. So let's just call close everything we need to create a new user. June uses. Actually, yes, I'm going to start a server. If you ever get this or in use and you know it's not use, you can use a command any UNIX at least calls to do so. That's that. This will check. The network starts And then that's the and be. And this is gonna give you all the Mississippi parts of open. And here you have unknown somewhere here, that's the 88 ports that's being taken by. No, you can do Ah que 28 to 51 Which the big number. It is the process i d. So we just killed that box. If you run that function again, you see that there's no more no older here. It's just so I can clear up them court in case you get stuck any. There you go. So let's create some users the most, or sign up it was created was gonna create anyone. So know that we'll have to users. You go first and second I'm going toe change this users Toby at me. So we do, uh, post a put request so that users So we cannot indented best ipi but to get its idea. And here let's change is at me equals two and bring Look, now it's admissions through, so we can actually continue and thats out around. So first I'm gonna Simon signing so I can get, uh, that's okay. Someone assigning together talking and then here in Ghana use the idea for that user digits H b the lids users. He said it was last with him, and now I can pass the token. So assess okay, it close here is not equal is a cola and you need protection. This in case you're basing on the terminal you my breakdown shorelines, which is should not be using toe clear out there next this police So when you do that, it's got the letters. Now, if you check our database there you go. Let's create a new user And now we can passed without the token so we can see them creates a new one. Now what? I tried to delete the user without a token. So when I got the idea, you must signing first. We're just coming from this middle where? Because first time it was signing and then I can actually delete. It's not even getting toe this check over here. If the user is Adami or not, our first I need to signing. So are our function is working and now we can think like, for example, this is we're using it for deleting on. You can use this kind off role based authentication for a lot of stuff, or is that belief here on the shots, for example, on the roster you just want and signing people that is already register people something so we can use that Me the were here. And if you also want only people toe the leads post that is at me like or moderator, you can create new your fields over here on the model, like it's that mean it's moderator or whatever, and then you create a me the works similar to this one. You can also pass the information in the token black with over here and then use amid the worst. Some liken this to create the logic required to block the user toe to use that resource. 29. 6.5 Refactoring Code: So before we finish with far authentication, let's do a bit off. Kenya wouldn't remove this comments that we don't need it anymore. No, he was there pretty here for matter. So now in the model, I'm gonna do the same for the importance you should always try to keep like third part libraries and then your application stop separated so you can have a 90 years just about campaigns. So here have the user model on the top. This is not necessarily, but it's nice to keep it organized so we can easily see what's going on in your application . This one is fine. It's also okay here in the middle where Just have a comment for this one explaining what it does, what they think. Errors the farm Validators has talking and check if he was up. Me. So here the main route we have our first Let's fix this, you bars. Here we are importing the controller from the user and from the user route over here so we can do something different. Let's do on the controller instead of exporting the default. Yeah, we just wanna export that controller from here on the top, Export like less that's here exporting by this as well. And on the roster like that, so we can create index file over here Next o J s and we can go Export star from Is there model Procter and Controllers. So now here it's gonna open the term now so we can see the errors coming up. It's for defaulting. Muzzle, Yes, six. And it's because here's a default export without them curly braces. So what? You can go because you create the index here on the routes. We can remove these user so we can just call the users over there and this were work. Now we can do the same footed users called Roller, but we can add it inside of here and remove this one. So, like this, we can keep our imports much more organized here, exporting everything from these mothers and controllers. Use the router dot Js Norris complaining on welter. Things were fixed over there, but we do not fix over here so we can just imported like this and always running again. So remember, with curly braces we do this type of import exports and then if you don't want to add the curly brace you need to do at the fault, Export. So let's continue. Now that you have this index, we can just go back. We're going toe army. The wares were done. The routers. Now we have this user and user controlling the shot. Rose, it's okay like this. You have our and the authentication, and we have this user route over here. So let's move it down so you can put the sign up together with the signing, and here I'm gonna create one more because I have, ah, get requests for signing. We need to get request for this sign up so we can display a form when you're going to be doing the front end sign up. So signing for the function that's gonna run that for sign up form and the function that runs the form. And then we have our user, which were actually using the authorization amid aware toe, allow only that user toe see their doctor, and the function is self gets whoever signings information. So this one is a external library. So I'm gonna put up here on top and now we have our obligation. We can do the same for dish for the shot can create the index so we can remove this bit over here. So let's do that right now. Indexed O J s in your export Everything. Controller welter and model. I was gonna get enough alphabetic order. So now here we can remove here. The last bit's an issue, and it should work. So rather is done. Me the words down. No list. Taco are controllers unit export. And in the end, we need to remove this default. I was gonna crash and hear it say is in the router. So here, when you are the curly braces everywhere, everything else is fine. And in models, losing parts are fine. Okay, for user, have these controllers controllers. Okay, Now use their model. Everything's inspired erotic. We just did. So our resources already has Check it out. Our application. Okay, so now I have this database function. Let's, uh, re factor this database function to use a sinker weight. So all of this is gonna be the same. Remember, every function that returns. Ah, promise you can make it a sink. Await. So here it's gonna call a sink, and then I'm gonna create a track catch. So we can get there. Zero Just in case this year, I'm gonna move over here removing this Koch. So he just wants a lot left. And here, this two of along, move it inside, Try. Which is he said off the return. I'm gonna wait connected with the base. And then if it's all right, you just cannot console of that. So is quite similar. A little bit better now I can instead of exporting my days, you can exported the thought. Because this is the only thing we're creating on this function on this fire. So export default. But the base connects. No need to fix this. Important it at the base because we were factored Toby a default. So we need to remove the calibrates. Stop here now. When you do that, everything is running as it was before. Let's commit everything to get so we can move on, get status, have junior flies the index that we create. So let's get commits with a message. You're factor close plus cleanup