From 72c4709a5ab26f00e32b65d874b3a206d679181e Mon Sep 17 00:00:00 2001 From: Osama Sayegh Date: Wed, 27 Mar 2024 12:56:21 +0300 Subject: [PATCH] FIX: Skip tags-related validations when the skip_validations option is present (#26379) The `TopicCreator` class has a `skip_validations` option that can force-create a topic without performing permission checks or validation rules. However, at the moment it doesn't skip validations that are related to tags, so topics that are created by the system or by some scrip can still fail if they use tags. This commit makes the `TopicCreator` class skip all tags-related checks if the `skip_validations` is specified. Internal topic: t/124280. --- lib/topic_creator.rb | 12 ++++++++---- spec/lib/topic_creator_spec.rb | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/lib/topic_creator.rb b/lib/topic_creator.rb index 8704fd3607a..559d3a45c76 100644 --- a/lib/topic_creator.rb +++ b/lib/topic_creator.rb @@ -181,10 +181,14 @@ class TopicCreator def setup_tags(topic) if @opts[:tags].present? - valid_tags = DiscourseTagging.tag_topic_by_names(topic, @guardian, @opts[:tags]) - unless valid_tags - topic.errors.add(:base, :unable_to_tag) - rollback_from_errors!(topic) + if @opts[:skip_validations] + DiscourseTagging.add_or_create_tags_by_name(topic, @opts[:tags]) + else + valid_tags = DiscourseTagging.tag_topic_by_names(topic, @guardian, @opts[:tags]) + unless valid_tags + topic.errors.add(:base, :unable_to_tag) + rollback_from_errors!(topic) + end end end diff --git a/spec/lib/topic_creator_spec.rb b/spec/lib/topic_creator_spec.rb index 556aa63a5f8..6eec7e9744d 100644 --- a/spec/lib/topic_creator_spec.rb +++ b/spec/lib/topic_creator_spec.rb @@ -150,6 +150,27 @@ RSpec.describe TopicCreator do end end + context "with skip_validations option" do + it "allows the user to add tags even if they're not permitted" do + SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:trust_level_2] + user.update!(trust_level: TrustLevel[1]) + Group.user_trust_level_change!(user.id, user.trust_level) + topic = + TopicCreator.create( + user, + Guardian.new(user), + valid_attrs.merge( + title: "This is a valid title", + raw: "Somewhat lengthy body for my cool topic", + tags: [tag1.name, tag2.name, "brandnewtag434"], + skip_validations: true, + ), + ) + expect(topic).to be_persisted + expect(topic.tags.pluck(:name)).to contain_exactly(tag1.name, tag2.name, "brandnewtag434") + end + end + context "with staff-only tags" do before { create_staff_only_tags(["alpha"]) }