All threads / Nested Comment Threads in Rails - Part 2 Discussion

Ask A Question

Notifications

You’re not receiving notifications from this thread.

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 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.

Reply

great catch @Marc Köhlbrugge

Reply
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 34,885+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.