Skip to content

Instantly share code, notes, and snippets.

@sheenobu
Created November 23, 2012 21:00
Show Gist options
  • Select an option

  • Save sheenobu/4137302 to your computer and use it in GitHub Desktop.

Select an option

Save sheenobu/4137302 to your computer and use it in GitHub Desktop.
module AuthenticateBeforeRequests
def self.append_features mod
Aquarium::Aspects::Aspect.new :around, :type => mod,
:methods => [:create_dns_entry,:create_arpa,:exists?,:zone],
:method_options => [:exclude_ancestor_methods] do |jp, object, *args|
object.authenticate
jp.proceed
end
end
end
class DnsClient
def initialize(options)
@session = Patron::Session.new
@session.timeout = 10
@session.insecure = true
@session.base_url = options[:url]
@session.headers['User-Agent'] = "dnsclient/..."
@session.headers.delete('x-authentication-token')
@options = options
end
def self.stub
require 'mocha_standalone'
st = DnsClient.new({})
st.stubs(:create_dns_entry).returns(true)
st.stubs(:create_arpa).returns(true)
st.stubs(:exists).returns(false)
st.stubs(:exists?).returns(false)
st.stubs(:zone).returns(true)
st.stubs(:authenticate).returns(true)
st.stubs(:authenticate!).returns(true)
st
end
def create_dns_entry(type, zone, addr,name)
body = { :records =>
[{:name => "#{name}.#{zone}", :type => type, :content => address}]
}
resp = @session.put("/zone/#{zone}",body.to_json)
if resp.status != 200 or resp.body != 'true'
#TODO: handle error
end
end
def create_arpa(name,zone,addr)
body = { :reverse_dns => "#{name}.#{zone}" }
resp = @session.put("/arpa/#{addr}",body.to_json)
if resp.status != 200 or resp.body != 'true'
#TODO: handle error
end
end
def exists?(zone,entry)
body = self.zone(zone)
return false if body.nil? or body.empty? or body.class == Array or body == '' or body['records'].nil?
body['records'] \
.map { |x| x['name'] }
.reduce(false) do |exists,name|
name == entry or exists
end
end
def zone(zone)
resp = @session.get("/zone/#{zone}")
resp = JSON.parse(resp.body)
resp
end
def authenticate
if @session.headers['x-authentication-token'].nil?
self.authenticate!
end
end
def authenticate!
body = {
:username => @options[:username],
:password => @options[:password]
}
response = @session.put(@options[:auth_url], body.to_json)
if response.status == 200
@session.headers['x-authentication-token'] = JSON.parse(response.body)['token']
else
@session.headers.delete('x-authentication-token')
end
end
include AuthenticateBeforeRequests
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment