Enforcing Ownership in the Delete Operation
Initially, the endpoint fetched a post by its ID without verifying whether the current user was the owner:owner_id matches the current user’s ID.
Below is the improved delete endpoint with the ownership check implemented:
The code first fetches the post for deletion. If the post is not found, the endpoint returns a 404 error. Then, it verifies that the post belongs to the current user before allowing deletion.
Enforcing Ownership in the Update Operation
The same ownership verification logic applies to the update operation. Before processing an update, we ensure that the post exists and that the logged-in user is its owner. Below is the updated endpoint for modifying a post:In the update endpoint, after ensuring the existence of the post, we check if the
current_user.id matches the post.owner_id. Only when this condition is met does the update proceed.Testing the Endpoints
When testing these endpoints, consider the following scenarios:-
Listing Posts
Sending a GET request to the posts endpoint returns a list of posts. For example: -
Authentication Token
The authentication token indicates the current logged-in user. For example:In tests, assume that the user represented by this token has an ID of 23. -
Unauthorized Delete Attempt
If the logged-in user (ID 23) tries to delete a post owned by another user (e.g., owner_id 21), the endpoint correctly responds with a 403 Forbidden error. -
Successful Deletion and Update
When the logged-in user attempts to delete or update a post they own (owner_id 23), the operation is successful. For instance, deleting a post with ID 8 (where owner_id is 23) returns a 204 status code. Similarly, updating the post modifies its content correctly.
Recap
In summary, both the delete and update endpoints now include the following safeguards:- They initially verify whether the specified post exists.
- They check if the authenticated user is the owner of the post.
- A 403 Forbidden error is returned when a user attempts an unauthorized operation.
- Only when these conditions are met does the operation proceed.