Class: APIGeoloc::Phpipam

Inherits:
Object
  • Object
show all
Defined in:
lib/apigeoloc/phpipam.rb

Overview

This is a PHPIPAM requester class.

Instance Method Summary collapse

Constructor Details

#initialize(apiurl, subnet, opts) ⇒ Phpipam

Class constructor method



24
25
26
27
28
29
30
31
32
33
34
# 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

Instance Method Details

#check_subnet_data(data) ⇒ Object

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



54
55
56
57
# 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) ⇒ Object

Transform json to a human readable string.



69
70
71
72
73
74
75
# 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) ⇒ Object

Get the location data.



60
61
62
63
64
65
66
# 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

#matchObject

Match the subnet with a location if possible.



78
79
80
81
# File 'lib/apigeoloc/phpipam.rb', line 78

def match
  location = location_data(subnet_loc_id)
  puts location
end

#receive_user_tokenObject

Set the user token.



37
38
39
40
41
42
# 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_idObject

Get Subnet location id.



45
46
47
48
49
50
51
# 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