A platform for community discussion. Free, open, simple.
FIX: Cap watched words CSV uploads at the per-action word limit
Régis Hanol045ca5c1f919
diff --git a/app/controllers/admin/watched_words_controller.rb b/app/controllers/admin/watched_words_controller.rbindex 49ded3fc9a2..a25f1ef57d6 100644--- a/app/controllers/admin/watched_words_controller.rb+++ b/app/controllers/admin/watched_words_controller.rb@@ -59,13 +59,26 @@ class Admin::WatchedWordsController < Admin::StaffControllerhas_replacement = WatchedWord.has_replacement?(action_key)content = File.read(file.tempfile, encoding: "bom|utf-8")+ max_words = WatchedWord::MAX_WORDS_PER_ACTION++ rows =+ begin+ CSV.new(content).lazy.select { |row| row[0].present? }.first(max_words + 1)+ rescue CSV::MalformedCSVError => e+ return render_json_error(e.message, status: :unprocessable_entity)+ end++ if rows.size > max_words+ error = I18n.t("watched_words.upload_too_many_csv_entries", count: max_words)+ return render_json_error(error, status: :unprocessable_entity)+ endScheduler::Defer.later("Upload watched words") dobeginwords_updated = 0- CSV.parse(content) do |row|- if row[0].present? && (!has_replacement || row[1].present?)+ rows.each do |row|+ if !has_replacement || row[1].present?watched_word =WatchedWord.create_or_update_word(word: row[0],diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex ffe958cb0ba..b91332c7e93 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -6020,6 +6020,11 @@ en:initial_post_raw: This topic includes daily performance reports for your site.initial_topic_title: Website performance reports+ watched_words:+ upload_too_many_csv_entries:+ one: "Too many entries in the CSV file. Please provide a CSV file with no more than %{count} entry."+ other: "Too many entries in the CSV file. Please provide a CSV file with no more than %{count} entries."+tags:title: "Tags"groups:diff --git a/spec/requests/admin/watched_words_controller_spec.rb b/spec/requests/admin/watched_words_controller_spec.rbindex e271d41064f..c0097520731 100644--- a/spec/requests/admin/watched_words_controller_spec.rb+++ b/spec/requests/admin/watched_words_controller_spec.rb@@ -320,6 +320,23 @@ RSpec.describe Admin::WatchedWordsController doexpect(WatchedWord.count).to eq(6)end+ it "rejects a CSV with more entries than the maximum number of words" do+ stub_const(WatchedWord, "MAX_WORDS_PER_ACTION", 2) do+ post "/admin/customize/watched_words/upload.json",+ params: {+ action_key: "flag",+ file:+ Rack::Test::UploadedFile.new(file_from_contents("w1\nw2\nw3\n", "words.csv")),+ }+ end++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to eq(+ [I18n.t("watched_words.upload_too_many_csv_entries", count: 2)],+ )+ expect(WatchedWord.count).to eq(0)+ end+it "preserves non-ASCII words in a UTF-8 file without a BOM" docontent = (1..30).map { |i| "badword#{i}" }.join("\n") + "\nCafé"