Skip to content

Instantly share code, notes, and snippets.

@andrewgho
Created June 24, 2020 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgho/c3cbd0702750018fefca57832f9391d7 to your computer and use it in GitHub Desktop.
Save andrewgho/c3cbd0702750018fefca57832f9391d7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'uri'
require 'net/http'
require 'json'
require 'http-cookie'
module Uck
class Client
attr_reader :baseurl
attr_reader :uri
attr_reader :cookies
def initialize(baseurl)
self.baseurl = baseurl
end
def baseurl=(url)
@baseurl = url
self.uri = URI.parse(baseurl)
@cookies = nil
end
def uri=(uri)
@uri = uri
# TODO: resolve @uri.host via gateway if it does not resolve on its own
@http = Net::HTTP.new(@uri.host, @uri.port)
if @uri.scheme == 'https'
require 'net/https'
@http.use_ssl = true
@http.verify_mode = OpenSSL::SSL::VERIFY_NONE # TODO: make optional
end
end
def login(username, password)
uri = @uri.dup
uri.path = '/api/login'
data = { username: username, password: password }
request = Net::HTTP::Post.new(uri.path)
request['content-type'] = 'application/json'
request.body = data.to_json
response = @http.request(request)
if response.code != '200' || response.body.nil? || response.body.empty?
nil # TODO: flag error
else
data = JSON.parse(response.body) # TODO: catch exception
if data && data.key?('meta') && data['meta'].key?('rc') &&
data['meta']['rc'] == 'ok'
if response.key?('set-cookie')
jar = HTTP::CookieJar.new
jar.parse(response['set-cookie'], uri)
@cookies = HTTP::Cookie.cookie_value(jar.cookies(uri))
end
# TODO: flag error if no Set-Cookie header
end
# TODO: flag error if response body lacks meta.rc == ok
end
# Return true if cookies were successfully saved
!(@cookies.nil? || @cookies.empty?)
end
def get(endpoint)
uri = @uri.dup
uri.path = endpoint.match('\A/') ? endpoint : '/' + endpoint
request = Net::HTTP::Get.new(uri.request_uri)
request['cookie'] = @cookies if !(@cookies.nil? || @cookies.empty?)
response = @http.request(request)
# TODO: throw error for unsuccessful response
# TODO: catch and promote error if no cookies and permission denied
data = JSON.parse(response.body)
# TODO: catch parse exception and log body before re-throwing
data
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment