summaryrefslogtreecommitdiff
path: root/lib/ats/amp4e/api.rb
blob: d6d00b5ca0d8b46f3291eae3a0a8c53d39f003b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
module ATS
  module AMP4E
    class API
      HEADERS = {
        'Content-Type' => 'application/json',
        'Accept' => 'application/json',
        'User-Agent' => "RubyGems/ATS #{ATS::VERSION}",
      }.freeze

      attr_reader :http, :port, :host, :scheme
      attr_reader :bearer_token, :client_id, :client_secret

      def initialize(configuration:, debug: false)
        @http = Net::Hippie::Client.new(headers: HEADERS, verify_mode: debug ? OpenSSL::SSL::VERIFY_NONE : nil)
        @configuration = configuration
        @port = configuration[:port]
        @scheme = configuration[:scheme]
        @host = configuration[:host]
        @bearer_token = configuration[:bearer_token]
        @client_id = configuration[:client_id]
        @client_secret = configuration[:client_secret]
      end

      def computers
        ATS::AMP4E::Computers.new(self)
      end

      def events
        ATS::AMP4E::Events.new(self)
      end

      def groups
        ATS::AMP4E::Groups.new(self)
      end

      def policies
        ATS::AMP4E::Policies.new(self)
      end

      def get(url, params: {}, version: 1)
        http.get(build_uri(url, version: version), headers: headers, body: params) do |request, response|
          JSON.parse(response.body, symbolize_names: true)
        end
      end

      private

      def build_uri(relative_url, version:)
        URI::Generic.build(host: host, port: port, scheme: scheme, path: "/v#{version}/#{relative_url}")
      end

      def headers
        if bearer_token
          { AUTHORIZATION: "Bearer #{bearer_token}" }
        else
          { AUTHORIZATION: "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}" }
        end
      end
    end
  end
end