Class: Unimatrix::Authorization::ClientCredentialsGrant

Inherits:
Object
  • Object
show all
Defined in:
lib/unimatrix/authorization/client_credentials_grant.rb

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ ClientCredentialsGrant

Returns a new instance of ClientCredentialsGrant.



7
8
9
10
# File 'lib/unimatrix/authorization/client_credentials_grant.rb', line 7

def initialize( args )
  @client_id = args[ :client_id ]
  @client_secret = args[ :client_secret ]
end

Instance Method Details

#request_tokenObject



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
# File 'lib/unimatrix/authorization/client_credentials_grant.rb', line 12

def request_token
  uri      = URI.parse( "#{ Unimatrix.configuration.authorization_url }/token" )
  params   = { "grant_type" => "client_credentials" }
  http     = Net::HTTP.new( uri.host, uri.port )
  request  = Net::HTTP::Post.new( uri.request_uri )

  http.use_ssl = true if uri.scheme == 'https'

  request.basic_auth( @client_id, @client_secret )
  request.set_form_data( params )

  begin
    response = http.request( request )

    if response.code == '200'
      body = JSON.parse( response.body )
      body = body[ 'token' ] if body[ 'token' ].present?

      body[ 'access_token' ] rescue nil
    else
      puts "ERROR: #{ response.body }"
    end
  rescue => e
    puts "REQUEST FAILED: #{ e }"
  end
end