Nested Comment Threads in Rails - Part 2 Discussion
There's a security vulnerability in the code which allows any authenticated user to delete anyone else's comment. While there's a check in view (
if comment.user == current_user) for showing the deletion link, there's no such check when actually destroying the comment.
Relevant code from
def destroy @comment = @commentable.comments.find(params[:id]) @comment.destroy redirect_to @commentable end
There are a number of different ways to fix the security vulnerability. Here's one example:
def destroy @comment = @commentable.comments.where(user: current_user).find(params[:id]) @comment.destroy redirect_to @commentable end
If you're planning to also add editing/updating of comments, you might want to turn this into a reusable helper method like so:
def destroy user_comment.destroy redirect_to @commentable end private def user_comment @user_comment =|| @commentable.comments.where(user: current_user).find(params[:id]) end
The same thing also be done using an authorisation gem like Pundit, if anyone already has that integrated into their app.
Pundit is my preference for this type of functionality. I've followed this tutorial and added the appropriate pundit policies on posts and comments along the way. +1 to pundit :)