Protecting Resources with Authorization in MEAN Stack
In our previous section, we successfully added the creator Id to our posts. In simple words, we added our connection between users and posts, and we are returning that data to the frontend. In this section, we will utilize this connection to deny requests for deleting or editing posts if they are made by a user who did not create the Post. We will use the following steps to do that:
1) We will go back to our posts.js file, where we have the router's put and delete method. In the put method, we ensure that only the user who created the Post can edit it. Here, we call the Post.updateOne() method only when the Post is created by that user who logged in. The simple way to do that is we will add another argument to the condition we have. We will check for the creator field here. The creator field should be equal to the userId of our userData in the request.
2) The updateOne() method returns the result, and this result contains a property, i.e., nModified. This property returns the count of updated records. So, we will use this variable to check whether the Post will be successfully updated or not. If its value is greater than zero, then we will return our old response. Else we will send a different response, i.e., 401 status code, to indicate the user is not authorized to perform this action.
Now, we will save all the files and go back to our angular app. If we try to update the Saakshi's Post from a different account, we will get the Not Authorized error.
4) We will simply copy the result handling of our update method and paste it in the delete method because here, we also get the nModified property that stores the count of the Post, which will be deleted.
We save all the files and go back to our app to check it is working or not.
Everything is working well. In the section, we will pass the userId to the frontend to use it on the frontend too.