Node.js & Express From Scratch [Part 11] – Access Control
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703050372_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: Node.js & Express From Scratch [Part 11] – Access Control
Hey guys welcome back this is episode 11 and in the last episode we created our login functionality so we can now log in but we’re not really doing anything else you know in terms of access control or functionality so what we’re going to do
First is make it so that when we add an article whatever user we’re logged in as that the ID is going to go into this author field so we want to remove this this form field we don’t want to manually type in the author anymore so
Let’s go to add article and just get rid of this form group here alright save that then we’re going to go to the route that we submit this to so let’s go to articles J s and routes and go to this post request and I’m just going to
Comment this out because we don’t need the author validation anymore all right now we’re going to go down here and instead of specifying the author as request body author from the form we’re going to say request dot user because remember when we’re logged in we have
The request dot user object and we want the ID which is going to be dot underscore ID okay so it will automatically put that users ID as the author so let’s go ahead and save that and then if we go over here and reload let’s actually delete these guys here
All right so let’s login so say Brad and let’s add an article and we’ll say article 1 this is article number 1 and submit article added now if we go to article 1 you’ll see it in houses written by and then our ID okay because that’s what we’re storing now so what we
Want to do is add an extra query to find the user and then I’ll put the name here so let’s go to the single article route right here and let’s first of all actually let me put that back let’s bring in the user model just like we did
The article model okay we’ll just say article model and then this is going to be user and then we’re going to change this to user and then we can access the model so we’ll go back down here and once we fetch the article here it’s
Going to give us all the the data so what we’ll do is we’ll say user dot find by ID and pass in article dots author because that’s going to hold the user ID all right then we want our function and this is going to have error and user
It’s going to give us the user back so what we need to do is just grab the render cut it and let’s put it inside here and then we’re going to set let’s see we still want the article of course and then we’re going to set author as
User dot name okay because we’re getting the user object here we want the name we’re going to put it in its author so we can access this inside the template so we’ll save that and go to article dot pug and instead of doing article Daath or we do
One author all right let’s go back and reload and now we get the name so now what I want to do is make it so that we can’t add an article if we’re not logged in alright we’re not logged in now we just got booted out because I reset the server
Let’s look we want to hide the link from people that aren’t logged in but we also don’t want people to go to the URL manually so let’s first take care of hiding the link so we’ll go to our layout and just like we did here we’re
Just going to go right above the add article list item and let’s say if let’s do if not user know if user that’s correct and then we’re just going to tab this over and now we’re not logged in if we reload it’s gone but we can still
Access this page so what we can do is we can create a special function for access control so let’s go into our articles routes and down at the bottom here say access control and we’re going to create a function and let’s call it ensure authenticated alright so ensure authenticated and
That’s going to take requests or sponsz next and we can say if since we’re using passport now we can say if request dot is authenticated then we want to just return next so we just want to move on else okay if they’re not authenticated we want to send a message and redirect
So request dot flash and this is going to be danger because we want to be read and then we’ll say please login all right we’ll redirect to the login page so res dot redirect and it’s going to go to slash users slash login all right now
What we can do is we can add this to any route that we want to protect so for instance the ad article page if we go up here we can add it in as a second parameter so it’s saying sure authenticated and now if we save and we
Go back and reload we get booted out ok if we log in not only does it show now but if we click on it we can actually visit the route alright we also want to put this into the edit form which is right here ok any route you want to
Protect you can now just add that too which is really nice so it’s save now we also don’t want the this edit and delete to show if we’re not logged in you can see we’re not logged in and it’s showing so let’s go to our article dot plug
Where we have the edit and delete and we want to check for two things here one we want to make sure that the user is logged in so just if user but we also want to make sure that the person can only see these if it’s if they own the
Article so what we can do is we can say if user dot ID because remember users an object and then we want to say equals article dot author because the author field has the ID user ID all right then we’ll just tab this over and save and if
We reload it’s not there now if we log in you’ll see it is there and now what I’ll do is log out and register a new account let’s say John Doe I’ll just say J Doe at gmail user name we’ll say John and password let’s submit and now we can login as
John and now if we go to article one you’ll see even though we’re logged in we can’t see the edit and delete because we don’t own that article alright but if we were to go to articles slash edit slash and then the ID we can that we can
Go to the edit page and we don’t want that so what we’ll have to do is go back to our articles routes and let’s go to the edit where the Edit form is loaded ok so we’re finding the article by ID then what we want to do is just put an
If statement right here and we’ll say if article if article dot author is not equal to request dot user dot underscore ID then we want to send a message and redirect okay so this will be danger and let’s say we’ll just say not authorized okay and then we’ll redirect and let’s
Just redirect to the home page all right so if we go back here and we reload we get booted out because we’re not actually let’s just log back in as John alright and we still shouldn’t be able to go to articles slash edit / ID not
Authorized okay but if we log in as Brad click on edit and we can edit okay now for the delete this is going to work a little differently because we’re making an AJAX request and sending a response back to the client so if we go down to
Our delete right here we’re going to first make sure that though the user is logged in so we’re going to check for the ID so go above the query here and let’s say if if not request dot user dot underscore ID then we want to send a
Response okay now this is sending a 200 response which is everything’s okay what we’ll do is we’ll say res dot status in passing 500 okay we’ll send a 500 error and then say dot send oops all right and then also we don’t want to just make sure the users logged in but
We want to make sure that they that they own that that articles so let’s go see we’ll go right below the query and I’m going to say article dot find by ID okay and then we’re going to pass in request stop params ID so that’s coming from the
URL and then function so this will have error and it also give us the article and then we want to do an if statement here and we want to say if article dot author is not equal to request dot user dot underscore ID then we want to send a
500 our just like we did here okay and then we’ll put an else and then what I’ll do is just grab the remove right here all this and we’ll cut and we’ll go in here and paste it in alright so let’s see should do here the only way that we
Can test this is if I put these buttons back so let’s just temporarily go to article pug and we’ll just get rid of that just for now oops so that should be on the same level all right so right now I’m log I’m not logged in so let’s try that delete and
If we look down here we’re getting the 500-hour okay so that’s not going to work and if we log in as John and click delete again we get a 500 down here and if we logout and log in as Brad and we click delete it works okay we want to
Make sure that we do hide these though because there’s no special error message for that I mean we could somehow get the message from the from the error response and put it in the app but I’m just going to make sure that these are hidden all right so let’s add another article is
John so let’s say article 1 this is John’s article ok and now we can see edit and delete alright so that works so we have full crud functionality we have a complete user registration and login system with password hashing we have access control we can add articles
Without being logged in we can only edit and delete the the current users articles so we’ve done quite a bit here and it’s it’s but it’s all been from scratch so hopefully you guys like the series now I’m not exactly sure where I’m going to go from here just like with
A lot of the series that I do because a lot of it depends on the response from you guys I would like to deploy it so I don’t know that might be the next one it might even be the last one I’m not exactly sure but I would like to do that I
Usually like to deploy apps to digitalocean I think it’s that it’s pretty easy to work with very cheap and also they give you a lot of freedom with your server with your VPS okay so hopefully you guys can use some of the skills that you learned in this
Course to create your own applications but that’s going to be it for now guys thank you for watching please subscribe please leave a like if you liked it also if you’re feeling extra generous go ahead and visit the patreon link that’s in the description and you can support
The channel directly so thanks for watching guys I will see you next time
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
When i login and view the article,I don't see the edit and delete buttons, and instead of the logout option in navbar, i get the login and register options. I have checked my code thrice now and can't seem to find the error. Can someone please help me with this?
the best tutorial, really help
super series bro…..
why delete requests are handled differently?
One bug in this program in if we edit the author section and put random numbers then our app crashes / lets remove the author section from ui
At first I thought why was Brad keeping delete logic even I dont get delete button in UI . But later I thought that what if some one edited in Client side our UI and bring delete button? If that is the case then sure our data is gonna be in loss . So such idea was implemented.
Yeah Traversy! It's amazing that you reached 1M subscribers.. Kudos🥳
why everytime I delete articles, my app crashes?
hi i wonder why we cant redirect in a delete request?
Hi, absolutely love your vids! I need help with one concept that I'm trying to wrap my head around…. so you have middleware that checks if the user is authenticated, then there's middleware to check if it's the correct user. If someone nefarious was trying to post something as someone else, would it still be possible for them to sign in with one account, get authenticated as having a valid web token, but then in a Restful API client, supply a different user._id in the header to make it look like they were the correct user (assuming they figured out the id of that user)?
This was an incredible incredible help to me. Since you wrote it, there have been some deprecations (of course), and the nav sample from bootstrap has changed slightly, but it was not anything that I couldn't overcome. You taught me a whole bunch. you are a great presenter.
great work. thanks brad
How about securing those POST routes? With the current state anyone can edit any article or add an article using POST requests. Great series though, thumbs up +1
How can I set up access so only I can post new articles? Also, only logged in users can comment on said article.
Thanks a lot Brad
is it possible to make a user permission management based on roles with this kind of backend?
why not directly access the req.user.name? the object is already passed the time you loggged in that's why you can access the id using req.user._id
Thanks a lot)))
Thank you bro :)))
You're the best!!!!!!
Thanks so much for these vids. Your tutorials are really great at balancing the what, why, and how, and I'm coming away from them with a much better understanding.
Just finished this one up today, and have my app running, except that every other time I click on an article title to view the individual article (and get to Edit and Delete), the app crashes. I'm trying to debug but getting a vague error:
events.js:167
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'name' of undefined
If you have any idea/clue you can throw my way, I'm sure it'll help lessen the de-bug time, but I'm determined to get it.
I know this isn't StackOverflow, but if you see this and are familiar with the error, def appreciate a heads up. Thanks again!