From cb1e1d3a94d9d586cb58be4b3b00e0dea8068cd7 Mon Sep 17 00:00:00 2001 From: evazion Date: Thu, 6 Oct 2016 09:12:23 +0000 Subject: [PATCH] Prevent commenting on nonexistent posts (#2704). --- app/models/comment.rb | 5 +++++ test/functional/comments_controller_test.rb | 5 +++++ test/unit/comment_test.rb | 7 +++++++ 3 files changed, 17 insertions(+) diff --git a/app/models/comment.rb b/app/models/comment.rb index 30afa6ff1..088580b07 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -1,6 +1,7 @@ class Comment < ActiveRecord::Base include Mentionable + validate :validate_post_exists, :on => :create validate :validate_creator_is_not_limited, :on => :create validates_format_of :body, :with => /\S/, :message => 'has no content' belongs_to :post @@ -148,6 +149,10 @@ class Comment < ActiveRecord::Base User.id_to_name(updater_id) end + def validate_post_exists + errors.add(:post, "must exist") unless Post.exists?(post_id) + end + def validate_creator_is_not_limited if creator.is_comment_limited? && !do_not_bump_post? errors.add(:base, "You can only post #{Danbooru.config.member_comment_limit} comments per hour") diff --git a/test/functional/comments_controller_test.rb b/test/functional/comments_controller_test.rb index 52d27b853..a98ef8d85 100644 --- a/test/functional/comments_controller_test.rb +++ b/test/functional/comments_controller_test.rb @@ -65,6 +65,11 @@ class CommentsControllerTest < ActionController::TestCase comment = Comment.last assert_redirected_to post_path(comment.post) end + + should "not allow commenting on nonexistent posts" do + post :create, {:comment => FactoryGirl.attributes_for(:comment, :post_id => -1)}, {:user_id => @user.id} + assert_response :error + end end end end diff --git a/test/unit/comment_test.rb b/test/unit/comment_test.rb index 46ec5f858..616462044 100644 --- a/test/unit/comment_test.rb +++ b/test/unit/comment_test.rb @@ -101,6 +101,13 @@ class CommentTest < ActiveSupport::TestCase assert(comment.errors.empty?, comment.errors.full_messages.join(", ")) end + should "not validate if the post does not exist" do + comment = FactoryGirl.build(:comment, :post_id => -1) + + assert_not(comment.valid?) + assert_equal(["must exist"], comment.errors[:post]) + end + should "not bump the parent post" do post = FactoryGirl.create(:post) comment = FactoryGirl.create(:comment, :do_not_bump_post => true, :post => post)