FIX: Validate number of votes allowed per poll per user (stable) (#15158)

Backport of 1d0faedfbc3a8b77b971dc70d25e30791dbb6e0b
This commit is contained in:
David Taylor 2021-12-01 16:42:39 +00:00 committed by GitHub
parent 982f23e1f2
commit 0c6b9df77b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View File

@ -48,6 +48,14 @@ en:
topic_must_be_open_to_vote: "The topic must be open to vote."
poll_must_be_open_to_vote: "Poll must be open to vote."
one_vote_per_user: "Only 1 vote is allowed for this poll."
max_vote_per_user:
one: Only %{count} vote is allowed for this poll.
other: A maximum of %{count} votes is allowed for this poll.
min_vote_per_user:
one: A minimum of %{count} vote is required for this poll.
other: A minimum of %{count} votes is required for this poll.
topic_must_be_open_to_toggle_status: "The topic must be open to toggle status."
only_staff_or_op_can_toggle_status: "Only a staff member or the original poster can toggle a poll status."

View File

@ -85,6 +85,7 @@ after_initialize do
available_options = poll.poll_options.map { |o| o.digest }.to_set
options.select! { |o| available_options.include?(o) }
self.validate_votes!(poll, options)
raise StandardError.new I18n.t("poll.requires_at_least_1_valid_option") if options.empty?
new_option_ids = poll.poll_options.each_with_object([]) do |option, obj|
@ -119,6 +120,26 @@ after_initialize do
end
end
def validate_votes!(poll, options)
num_of_options = options.length
if poll.multiple?
if num_of_options < poll.min
raise StandardError.new(I18n.t(
"poll.min_vote_per_user",
count: poll.min
))
elsif num_of_options > poll.max
raise StandardError.new(I18n.t(
"poll.max_vote_per_user",
count: poll.max
))
end
elsif num_of_options > 1
raise StandardError.new(I18n.t("poll.one_vote_per_user"))
end
end
def toggle_status(post_id, poll_name, status, user, raise_errors = true)
Poll.transaction do
post = Post.find_by(id: post_id)