File size: 1,600 Bytes
def1299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class SessionsController < ActionController::API
  before_action :verify_ip_address
  before_action :authenticate_request
  before_action :authorize_request, only: [:authorize]

  def authenticate
    head :ok
  end

  def authorize
    head :ok
  end

  private

  def verify_ip_address
    @@disallowed_ip_addresses ||= ENV['DISALLOW_IP'].to_s.split - ENV['ALLOW_IP'].to_s.split
    @@allowed_ip_addresses ||= ENV['ALLOW_IP'].to_s.split - ENV['DISALLOW_IP'].to_s.split
    head :forbidden if @@disallowed_ip_addresses.include?(request.remote_ip)
    head :forbidden if @@allowed_ip_addresses.present? && !@@allowed_ip_addresses.include?(request.remote_ip)
  end

  def authenticate_request
    head :unauthorized if safe_compare(Rails.application.secrets.authn_token, Rails.application.secrets.authn_header)
  end

  def authorize_request
    head :forbidden unless Rails.application.secrets.authz_token.present?
    head :forbidden if safe_compare(Rails.application.secrets.authz_token, Rails.application.secrets.authz_header)
  end

  def check_maintenance
    @@maintenance_message ||= ENV['MAINTENANCE_MESSAGE']
    if Config::MAINTENANCE_MODE
      render json: {
        error: @@maintenance_message
      }, status: :service_unavailable
    end
  end

  def safe_compare(token, header)
    token = token.to_s
    header = header.to_s
    return false unless token.present?
    provided_token = (request.headers[header] || params[header]).to_s
    token.split.each do |value|
      return false if ActiveSupport::SecurityUtils.secure_compare(value, provided_token)
    end
    true
  end
end