FIX: Return error if new topic category not found take 2

FIX: Return error if new topic category not found take 2

If creating a topic via the api as an admin and the category you specify cannot be found an error will now be returned instead of just creating the topic with no category. This will prevent accidental public topic creation originally intended for a private category.

This commit is follow up to 535c594891ec703a3b2e57c1b1a3497373d2e1f6 and still allows for the creation of topics where the category param is blank.

diff --git a/lib/topic_creator.rb b/lib/topic_creator.rb
index 71655b0..db325d3 100644
--- a/lib/topic_creator.rb
+++ b/lib/topic_creator.rb
@@ -121,6 +121,8 @@ class TopicCreator
     category = find_category
     @guardian.ensure_can_create!(Topic, category) unless (@opts[:skip_validations] || @opts[:archetype] == Archetype.private_message)
 
+    raise Discourse::NotFound if @opts[:category] && !@opts[:category].blank? && category.nil?
+
     topic_params[:category_id] = category.id if category.present?
 
     topic_params[:created_at] = Time.zone.parse(@opts[:created_at].to_s) if @opts[:created_at].present?
diff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rb
index e07a238..73c863b 100644
--- a/spec/requests/posts_controller_spec.rb
+++ b/spec/requests/posts_controller_spec.rb
@@ -775,6 +775,34 @@ describe PostsController do
         }
         expect(response.status).to eq(403)
       end
+
+      it 'will raise an error if specified category cannot be found' do
+        user = Fabricate(:admin)
+        master_key = ApiKey.create_master_key.key
+
+        post "/posts.json", params: {
+          api_username: user.username,
+          api_key: master_key,
+          title: 'this is a test title',
+          raw: 'this is test body',
+          category: 'invalid'
+        }
+        expect(response.status).to eq(404)
+      end
+
+      it 'can create topics with an empty category param' do
+        user = Fabricate(:admin)
+        master_key = ApiKey.create_master_key.key
+
+        post "/posts.json", params: {
+          api_username: user.username,
+          api_key: master_key,
+          title: 'title for a topic without a category',
+          raw: 'body for my topic without a category',
+          category: ''
+        }
+        expect(response.status).to eq(200)
+      end
     end
 
     describe "when logged in" do

GitHub sha: d1dbafeb

1 Like

This can be shortened to

raise Discourse::NotFound if @opts[:category].present? && category.nil?
1 Like

REFACTOR: Shorten up category param check

DEV: Return the right response code and error message.