
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
By logging in, you'll unlock full access to this and other free tutorials on JSM Pro.
Why? Logging in lets us personalize your learning experience, track your progress, and keep you in the loop with new workshops, coding tips, and platform updates.
You'll also be the first to know about upcoming launches, events, and exclusive discounts.
No spam—just helpful content to level up your skills.
If that sounds fair, go ahead and log in to continue →
Enter your name and email to get instant access
##Looks like we found a thief monkey By the way, I liked the trick how you reached till here. You have a good sense of humor. You will improve a lot if you join our course with this passion.
var
(function-scoped, outdated)let
(block-scoped, modern and recommended)const
(block-scoped, cannot be reassigned)_
, or $
let let = 5;
is invalid)myVar
and myvar
are different)string
, number
, boolean
, null
, undefined
, bigint
, symbol
Objects
, Arrays
, Functions
Subscribing gives you access to a brief, insightful summary of each lecture to stay on track.
00:00:02 To authorize our users, let's create a new file right here within the controllers folder and let's call it user.controller.js.
00:00:12 Within here, we can import the user model coming from dot dot slash models user dot model dot JS.
00:00:19 and we can define two functions.
00:00:22 The first one will fetch all users, so we can say exportConst getUsers is equal to an asynchronous function, which accepts the request and the response
00:00:32 as the params, and we can open up a try and catch block.
00:00:37 In the catch, we get the error and we can simply forward it over to our error handling by saying next error and that next is coming as the third parameter
00:00:47 right here into this function.
00:00:48 But when it comes to what we'll actually try to do in this function, we can try to fetch the users by saying const users is equal to await user.find and
00:01:00 we'll simply find all the users like this.
00:01:03 Next, we can say res.status.200 And in the JSON, we can simply return a success is equal to true as well as data is equal to users.
00:01:15 And this is it.
00:01:16 This is a function that fetches all the users from the database.
00:01:19 We can duplicate it below and rename it to getUser, which will get a singular user.
00:01:26 In this case, we'll say user is equal to user.findById.
00:01:32 And to it, we can pass the rec.params.id and then also call the .select where we're going to select all the fields minus the password.
00:01:42 We just want to get the user info, but we don't care about the password.
00:01:46 We only care about that when logging in.
00:01:48 Finally, if there is no user that we're trying to fetch, we can create a new error by saying const error is equal to new error,
00:01:57 and we can say user not found.
00:01:59 We can also set the error.status code to 404 and throw it.
00:02:04 That way, we'll be able to catch it right within our error handling middleware.
00:02:09 Else, we'll simply say res.status200, JSON, success true, and data is equal to user.
00:02:16 Singular user now.
00:02:17 Great.
00:02:18 So now, let's put those two to use by heading over into our routes, specifically user routes.
00:02:26 We have a route that fetches all the users, so I can simply do it right here.
00:02:31 I'll call the getUsers.
00:02:33 There we go.
00:02:34 And then right below it, we have another one which fetches the users based on its ID.
00:02:39 So here we can call the getUser.
00:02:42 And make sure to import both of these coming from controllers, user.controller.js.
00:02:48 And this is a pretty cool thing.
00:02:49 See how we have this dynamic parameter of ID.
00:02:52 Now, how are we fetching it in the getUser?
00:02:55 Well, it's getting to us through recparams ID.
00:02:59 You know how through the POST requests, we can pass a request body, but through GET requests, we can also pass the data through the request parameters.
00:03:08 So in this case, since it's called the ID, we can extract that ID value right from RECPARAM's ID.
00:03:15 Now let's go ahead and test it out.
00:03:16 I'll open up our HTTP client and we want to target the API v1 and then users endpoint.
00:03:24 And this time we're making a GET request.
00:03:27 If you do this and click send, you'll be able to see create new user.
00:03:31 Oh, it looks like it didn't switch the request.
00:03:34 So if you do it one more time and click send, now you can see the only user that we created with our name, email, and password.
00:03:42 Now what we could do is maybe prevent regular users from making this call because it could expose all the users in the database.
00:03:49 I'll show you how to do that very soon.
00:03:51 But for now, let's grab this user's ID.
00:03:54 And let's make a request to the same URL, but append that ID right at the end, and make a request.
00:04:02 And now you can see the success true and data only for that user.
00:04:05 This time, no password.
00:04:07 But as I said, we need to be able to protect our routes.
00:04:10 For example, this user details page should be private.
00:04:14 And to do that, we can also use middleware.
00:04:16 This time, we can think of it as authentication middleware.
00:04:20 So right within middlewares, create a new file called auth.middleware.js and create a new function const authorize, which will be equal to an asynchronous
00:04:34 function that accepts the request, the response, and the next, and opens up a try and catch block.
00:04:40 In the catch, we can run res.status of 401, which means unauthorized, and return a JSON output with a message of unauthorized as well as pass some additional
00:04:53 error information in form of the error message.
00:04:57 But in the try, we can try to get access to the user's token by saying let token and then having an if statement where we check for rec.headers.authorization
00:05:10 and if rec.headers.authorization dot starts with bearer.
00:05:17 Typically, when you pass a token through the rec.headers, it starts with the word bearer.
00:05:22 It's just a protocol.
00:05:23 So if that is the case, then we know that the token will be there and we can say token is equal to rec.headers.authorization.split and we'll split the
00:05:33 word bearer and return just the second part of that string, which will be the actual token.
00:05:38 We can go outside of that if and check if there is no token.
00:05:43 In that case, we can return a rest.status of 401 and a message of unauthorized.
00:05:50 Else, if we do get the token, we have to verify it by saying const decoded is equal to jwt.verify.
00:05:59 And you have to pass the token and our JWT secret coming from our ENV config.
00:06:05 So make sure to import it from here and also make sure to import the JWT from JSON Web Token.
00:06:13 Once we decode it, we can check if the user still exists by fetching it from the database.
00:06:18 const user is equal to await user.findById and we'll use the decoded user.userId.
00:06:28 If it doesn't exist, we'll simply return once again a 401 of unauthorized.
00:06:34 And if it does exist, we'll attach the user to the request that is being made and then forward it over to the second part of the request.
00:06:42 So basically what this middleware is doing is it's trying to find the user based off of the token of the user that is trying to make the request.
00:06:51 It looks if it's there, it decodes it, verifies that that is the user that is currently logged in, and then it attaches it to the request.
00:06:59 So later on, when we're doing something, we can know who exactly is making that request because now we have this additional information.
00:07:07 So in simple words, let's say that somebody is trying to make a request.
00:07:12 making a request to example, get user details.
00:07:16 Then we call this authorized middleware.
00:07:20 We verify who is trying to do it.
00:07:23 And if they have permissions or if valid, then we go over to the next step and give access to the user details.
00:07:31 So how can we actually put this authorized middleware to use?
00:07:34 Well, let's head over into our user.route.js.
00:07:40 And remember what I told you will authorize the user details page.
00:07:45 So only the user that is currently logged in can see its own details.
00:07:49 No, no one else.
00:07:51 And the only thing you have to do to make it work is import that authorize.
00:07:58 from dot dot slash middlewares forward slash auth dot middleware dot js.
00:08:05 Oh, and I think I forgot to export it.
00:08:07 So this was supposed to be const authorized and we can run export default authorized.
00:08:13 And the only thing you have to do is add it right here after the path, but before the next function.
00:08:20 This is why it's called middleware because it is in the middle from when you start making a request to when you end it.
00:08:27 And in case you want to add a second middleware.
00:08:29 maybe like error handling middleware, you can add it right here as well, and you can keep chaining as many middlewares as you want,
00:08:36 as long as they all end in the next, because they'll forward it over to the next function.
00:08:42 But now, this getUser will actually have access to the user object, because we authorized it beforehand.
00:08:50 So, let's put it to the test.
00:08:51 If I retry the same request that we made not that long ago, where we got successful user details, Now, you'll see 401 unauthorized.
00:09:00 Okay, this is good.
00:09:01 We don't have a token and it's not working.
00:09:04 Exactly what we wanted.
00:09:05 But now to pass this authorization, we'll have to sign in to get a token.
00:09:09 To get it, you can just go to api v1 auth and then forward slash sign in and enter your email and password that you use at the start.
00:09:20 If you forgot it, you can just create a new account by going to sign up and passing over your email name and password.
00:09:27 So now I'll click sign in, and of course this is not a GET request, it's going to be a POST request.
00:09:33 So if I click it, there we go, user signed in successfully, and we got our token.
00:09:39 Before copying the token, first copy the user ID and add it right here to the request, where we're going to go for API V1 users and then user ID.
00:09:51 and also copy the bearer token, and make a GET request to this URL.
00:09:56 But now, within Auth, you can select a bearer token and paste that token right here.
00:10:01 This should allow you to fetch the details of this user.
00:10:04 So click Send, and we got unauthorized, but I think I know why that is.
00:10:09 It's because we haven't defined our user.
00:10:11 So if you head over to user middleware, I think we forgot to import this user right here.
00:10:17 It's supposed to be coming from dot dot slash models, user dot model dot JS.
00:10:22 So now that we fixed that issue, thankfully we have proper error handling here.
00:10:26 Let's try to remake that request, this time with a token.
00:10:30 And there we go, we get back the information.
00:10:33 But if we remove this token from there, you can see that we don't have the permission to access it.
00:10:39 So hopefully that makes sense.
00:10:41 That is how we authorize or protect certain routes by allowing only specific users to see them.
00:10:47 You can always extend this to add stricter rules.
00:10:50 For example, for only admins to be able to make requests to get all users.
00:10:55 The only thing you have to do is add a check if that user is an admin or a regular user.
00:11:00 You can do that using the same authorized middleware or you can create another piece of middleware only for that.
00:11:05 And talking about making stricter rules for your apps, Typically, there's always one or two nasty users that'll try to spam your APIs or websites by making
00:11:14 too many requests, one after another.
00:11:17 That's not good because it's slowing down your server and increasing the costs.
00:11:21 And right now, they can totally do that.
00:11:23 I mean, check me out.
00:11:24 I'm just making tons of requests right now.
00:11:26 And imagine if they coded a bot to just spam thousands of them.
00:11:30 So in the next lesson, I'll teach you how we can restrict the number of requests a user can make in a certain period of time.
00:11:37 Almost every production app does this.
00:11:40 So let me teach you how to do it.