Sha256: 54b4308447cfa9c9b6be1f1092694fc501ba6cf49c60cfa437bd9660ea3ceb65

Contents?: true

Size: 1.29 KB

Versions: 10

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

require 'ipaddr'

# looks up institution ID(s) by IP address
class Keycard::InstitutionFinder
  IDENTITY_ATTRS = %i[dlpsInstitutionId].freeze

  INST_QUERY = <<~SQL
      SELECT inst FROM aa_network WHERE
              ? >= dlpsAddressStart
          AND ? <= dlpsAddressEnd
          AND dlpsAccessSwitch = 'allow'
          AND dlpsDeleted = 'f'
          AND inst is not null
    AND inst NOT IN
        ( SELECT inst FROM aa_network WHERE
          ? >= dlpsAddressStart
          AND ? <= dlpsAddressEnd
          AND dlpsAccessSwitch = 'deny'
          AND dlpsDeleted = 'f' )
  SQL

  def initialize(db: Keycard::DB.db)
    @db = db
    @stmt = @db[INST_QUERY, *[:$client_ip] * 4].prepare(:select, :unused)
  end

  def identity_keys
    IDENTITY_ATTRS
  end

  def attributes_for(request)
    return {} unless (numeric_ip = numeric_ip(request.client_ip))

    insts = insts_for_ip(numeric_ip)

    if !insts.empty?
      { dlpsInstitutionId: insts }
    else
      {}
    end
  end

  private

  attr_reader :stmt

  def insts_for_ip(numeric_ip)
    stmt.call(client_ip: numeric_ip).map { |row| row[:inst] }
  end

  def numeric_ip(dotted_ip)
    return unless dotted_ip

    begin
      IPAddr.new(dotted_ip).to_i
    rescue IPAddr::InvalidAddressError
      nil
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
keycard-0.3.4 lib/keycard/institution_finder.rb
keycard-0.3.3 lib/keycard/institution_finder.rb
keycard-0.3.2 lib/keycard/institution_finder.rb
keycard-0.3.1 lib/keycard/institution_finder.rb
keycard-0.3.0 lib/keycard/institution_finder.rb
keycard-0.2.4 lib/keycard/institution_finder.rb
keycard-0.2.3 lib/keycard/institution_finder.rb
keycard-0.2.2 lib/keycard/institution_finder.rb
keycard-0.2.1 lib/keycard/institution_finder.rb
keycard-0.2.0 lib/keycard/institution_finder.rb