class APIGeoloc::Phpipam

This is a PHPIPAM requester class.

Public Class Methods

new(apiurl, subnet, opts) click to toggle source

Class constructor method

# File lib/apigeoloc/phpipam.rb, line 24
def initialize(apiurl, subnet, opts)
  cidr_regex = '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}' \
    '([0-9]|[1-9][0-9]|1[0-9]\{2\}|2[0-4][0-9]|25[0-5])' \
    '(\/([0-9]|[1-2][0-9]|3[0-2]))$'
  raise 'Invalid cidr subnet format' \
    unless subnet.match(Regexp.new(cidr_regex))
  @apiurl = apiurl.sub(%r{/^(.*)\/$/}, '\1')
  @subnet = subnet
  @opts = opts
  @opts['header'] = "TOKEN:#{receive_user_token}"
end

Public Instance Methods

check_subnet_data(data) click to toggle source

Raise error if the data or location id doesn’t exist.

# File lib/apigeoloc/phpipam.rb, line 54
def check_subnet_data(data)
  raise 'Subnet not found' if data.nil?
  raise 'Location unknown' if data[0]['location'].nil?
end
format_location(data) click to toggle source

Transform json to a human readable string.

# File lib/apigeoloc/phpipam.rb, line 69
def format_location(data)
  name = data['name']
  address = data['address']
  lat = data['lat']
  long = data['long']
  "#{name}, #{address}, [#{lat}, #{long}]"
end
location_data(id) click to toggle source

Get the location data.

# File lib/apigeoloc/phpipam.rb, line 60
def location_data(id)
  loc_req_path = "#{@apiurl}/tools/locations/#{id}/"
  loc_res = APIGeoloc::Requester.new('GET', loc_req_path, @opts).request
  loc_body = JSON.parse(loc_res.body)
  raise 'Location not found' if loc_body['data'].nil?
  format_location(loc_body['data'])
end
match() click to toggle source

Match the subnet with a location if possible.

# File lib/apigeoloc/phpipam.rb, line 78
def match
  location = location_data(subnet_loc_id)
  puts location
end
receive_user_token() click to toggle source

Set the user token.

# File lib/apigeoloc/phpipam.rb, line 37
def receive_user_token
  res = APIGeoloc::Requester.new('POST', "#{@apiurl}/user/", @opts).request
  body = JSON.parse(res.body)
  raise 'Invalid username or password' unless body['code'] == 200
  body['data']['token']
end
subnet_loc_id() click to toggle source

Get Subnet location id.

# File lib/apigeoloc/phpipam.rb, line 45
def subnet_loc_id
  sn_req_path = "#{@apiurl}/subnets/cidr/#{@subnet}"
  sn_res = APIGeoloc::Requester.new('GET', sn_req_path, @opts).request
  sn_body = JSON.parse(sn_res.body)
  check_subnet_data(sn_body['data'])
  sn_body['data'][0]['location']
end