Created a middleware function which intercepts all incoming requests and verifies user access
This function decodes a JWT token acquired from the requests header under the "Authorization" key. It throws proper errors depending on whether the token is expired or just invalid.
Decoding the JWT token gives you access to the "uid" (userid) field. Using the uid, we can track if the user has authorization to the things they are trying to access.
Authorization schema currently following:
allow all get requests
allow a user to PUT (update) or DELETE their own user collection entry
allow a user to POST (create) a new post
allow a user to PUT (update) or DELETE a post ONLY if they are the author of that post
User does not have access if they try to do anything outside of this schema. For example, user 2 created post 1, and user 1 is trying to update post 1, they will be given an "Unauthorized access" message along with a 403 Forbidden error code.
I imported the JWT package as it is necessary to do the above actions
I wrote a helper function for the middleware function called check_user_existence() which simply checks if the user exists in the database and returns True or False based on the result.
I added HTTP status codes 401 (Unauthorized) and 403 (Forbidden)
How to Test
Create a valid JWT token by logging into the app after starting the frontend server.
Start the backend server by running python server.py
Navigate to Postman and give it any route, for example: http://localhost:5000/api/posts/Kr40Rksk4XI4qauBkpYb with PUT
In the 'Headers' tab, add the Authorization key and include your JWT token created in Step 1
Click send, and given that your decoded JWT token ["uid"] doesn't have access to that post, meaning that user_id did not create the post at that post_id, you will receive a "Unauthorized access" message along with a 403 Forbidden error code.
In the above, my user_id was 'user_2cwMgsX7SwXnnnYJ2piefltKxLO' and I only have access to post 'Kr40Rksk4XI4qauBkpYb'. Trying to update the post '1Pz2MQzjlJ9yW5BuWcbc' I received an "Unauthorized access" message as expected!
Checklist
[ ] I have added/updated relevant documentation, and I have followed the coding style guidelines.
[ ] I have checked for any potential conflicts with other branches and fixed any merge conflicts.
[ ] I have verified that any user can do any GET request.
[ ] I have verified that a user is only allowed to PUT (update) or DELETE their own user collection entry.
[ ] I have verified that a user is allowed to create a new post.
[ ] I have verified that a user cannot PUT (update) or DELETE a post they do not own.
[ ] I have verified that a user can PUT (update) or DELETE a post that they own.
This is related to issue #15
Description / Changes Made
How to Test
python server.py
http://localhost:5000/api/posts/Kr40Rksk4XI4qauBkpYb
with PUTAuthorization
key and include your JWT token created in Step 1Checklist