Class: ManagementAPIV2::Client

Inherits:
Object
  • Object
show all
Defined in:
app/services/management_api_v2/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root_url, security_configuration) ⇒ Client

Returns a new instance of Client.



10
11
12
13
# File 'app/services/management_api_v2/client.rb', line 10

def initialize(root_url, security_configuration)
  @root_api_url = root_url
  @security_configuration = security_configuration
end

Instance Attribute Details

#actionObject

Returns the value of attribute action.



8
9
10
# File 'app/services/management_api_v2/client.rb', line 8

def action
  @action
end

Instance Method Details

#build_path(path) ⇒ Object



33
34
35
# File 'app/services/management_api_v2/client.rb', line 33

def build_path(path)
  "api/v2/management/#{path}"
end

#generate_jwt(payload) ⇒ Object



65
66
67
# File 'app/services/management_api_v2/client.rb', line 65

def generate_jwt(payload)
  JWT::Multisig.generate_jwt(payload, keychain(:value), keychain(:algorithm))
end

#http_clientObject



37
38
39
40
41
42
43
# File 'app/services/management_api_v2/client.rb', line 37

def http_client
  Faraday.new(url: @root_api_url) do |conn|
    conn.request :json
    conn.response :json
    conn.adapter Faraday.default_adapter
  end
end

#keychain(field) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'app/services/management_api_v2/client.rb', line 45

def keychain(field)
  {}.tap do |h|
    @security_configuration[:keychain].each do |id, key|
      next unless action
      next unless id.in?(action[:required_signatures])
      h[id] = key[field]
    end
  end
end

#payload(data = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'app/services/management_api_v2/client.rb', line 55

def payload(data = {})
  {
    data: data,
    iat:  Time.now.to_i,
    exp:  Time.now.to_i + ENV.fetch('JWT_EXPIRE_DATE', 60).to_i,
    jti:  SecureRandom.hex(12),
    iss:  'applogic'
  }
end

#request(request_method, request_path, request_parameters, options = {}) ⇒ Object

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'app/services/management_api_v2/client.rb', line 15

def request(request_method, request_path, request_parameters, options = {})
  options = { jwt: false }.merge(options)
  raise ArgumentError, "Request method is not supported: #{request_method.inspect}." unless request_method.in?(%i[post put])

  request_parameters = generate_jwt(payload(request_parameters)) unless options[:jwt]

  begin
    http_client
      .public_send(request_method, build_path(request_path), request_parameters)
      .tap { |response| raise ManagementAPIV2::Exception.new(response) unless response.success? }
      .body
      .symbolize_keys

  rescue Faraday::Error => e
    raise ManagementAPIV2::Exception.new
  end
end