Skip to main content

Nested Comment Threads in Rails - Part 2 Discussion

General • Asked by Chris Oliver

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 comments_controller.rb:

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.


great catch @Marc Köhlbrugge


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.