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
Reply

The same thing also be done using an authorisation gem like Pundit, if anyone already has that integrated into their app.

Reply

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 :)

Reply

great catch @Marc Köhlbrugge

Reply

Pundit is my go-to app when it comes to features like these. I have implemented the tutorial's suggested rules for posting and comments by pundits. Pundit gets an extra point:)

Reply
Join the discussion
Create an account Log in

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

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

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.