Skip to content
Permalink
Browse files Browse the repository at this point in the history
FIX: Validate number of votes allowed per poll per user (stable) (#15158
)

Backport of 1d0faed
  • Loading branch information
davidtaylorhq committed Dec 1, 2021
1 parent 982f23e commit 0c6b9df
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
8 changes: 8 additions & 0 deletions plugins/poll/config/locales/server.en.yml
Expand Up @@ -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."

Expand Down
21 changes: 21 additions & 0 deletions plugins/poll/plugin.rb
Expand Up @@ -85,6 +85,7 @@ def vote(post_id, poll_name, options, user)
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|
Expand Down Expand Up @@ -119,6 +120,26 @@ def vote(post_id, poll_name, options, user)
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)
Expand Down

0 comments on commit 0c6b9df

Please sign in to comment.