1module BulkVerification
 
2  extend ActiveSupport::Concern
 
3
 
4  class InvalidBulkRequest < RuntimeError; end
 
5
 
6  included do
 
7    before_action :verify_bulk_request, if: :bulk_request?
 
8
 
 9    helper_method :bulk_verifier
 
 
11    rescue_from ActiveSupport::MessageVerifier::InvalidSignature do
 
12      raise BulkVerification::InvalidBulkRequest, "Invalid bulk request for #{selected_ids.inspect}"
 
13    end
 
14  end
 
 
16  private
 
  • Complexity 1 » saikuro
18  def bulk_request?
 
19    action_name =~ /\Abulk_/
 
20  end
 
  • Complexity 1 » saikuro
22  def bulk_verification_token
 
23    session[:_bulk_verification_token] ||= SecureRandom.base64(32)
 
24  end
 
  • Complexity 1 » saikuro
26  def bulk_verifier
 
27    @_bulk_verifer ||= ActiveSupport::MessageVerifier.new(bulk_verification_token, serializer: JSON)
 
28  end
 
  • Complexity 1 » saikuro
30  def selected_ids
 
31    @_selected_ids ||= params[:selected_ids].to_s.split(",").map(&:to_i).reject(&:zero?).take(50)
 
32  end
 
  • Complexity 1 » saikuro
34  def all_ids
 
35    @_all_ids ||= bulk_verifier.verify(params[:all_ids])
 
36  end
 
  • Complexity 1 » saikuro
38  def verify_bulk_request
 
39    selected_ids.all?(&method(:verify_bulk_request_id))
 
40  end
 
  • Complexity 1 » saikuro
42  def verify_bulk_request_id(id)
 
43    all_ids.include?(id) || raise_bad_request(id)
 
44  end
 
  • Complexity 1 » saikuro
46  def raise_bad_request(id)
 
47    raise BulkVerification::InvalidBulkRequest, "Invalid bulk request - #{id} not present in #{all_ids.inspect}"
 
48  end
 
49end