Class: Headquarters::API::OAuthAuthenticator

Inherits:
Object
  • Object
show all
Defined in:
lib/headquarters/api/oauth_authenticator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id: nil, client_secret: nil) ⇒ OAuthAuthenticator

Returns a new instance of OAuthAuthenticator.



4
5
6
7
8
# File 'lib/headquarters/api/oauth_authenticator.rb', line 4

def initialize(client_id: nil, client_secret: nil)
  @client_id = client_id
  @client_secret = client_secret
  authenticate!
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



10
11
12
# File 'lib/headquarters/api/oauth_authenticator.rb', line 10

def access_token
  @access_token
end

#client_idObject (readonly)

Returns the value of attribute client_id.



10
11
12
# File 'lib/headquarters/api/oauth_authenticator.rb', line 10

def client_id
  @client_id
end

#client_secretObject (readonly)

Returns the value of attribute client_secret.



10
11
12
# File 'lib/headquarters/api/oauth_authenticator.rb', line 10

def client_secret
  @client_secret
end

Instance Method Details

#authenticate!Object



20
21
22
23
24
25
26
# File 'lib/headquarters/api/oauth_authenticator.rb', line 20

def authenticate!
  return if client_id.nil? || client_secret.nil?

  response = Request.perform(:post, Endpoints::OAUTH_TOKEN, body: authentication_body)

  @access_token = Hash(response).fetch('access_token', nil)
end

#authentication_bodyObject



28
29
30
31
32
33
34
# File 'lib/headquarters/api/oauth_authenticator.rb', line 28

def authentication_body
  {
    grant_type: 'client_credentials',
    client_id: client_id,
    client_secret: client_secret
  }
end

#headersObject



12
13
14
15
16
17
18
# File 'lib/headquarters/api/oauth_authenticator.rb', line 12

def headers
  if access_token
    { 'Authorization' => "Bearer #{access_token}" }
  else
    {}
  end
end