Class: ChangeHealth::Authentication

Inherits:
Object
  • Object
show all
Defined in:
lib/change_health/authentication.rb

Constant Summary collapse

AUTH_ENDPOINT =
'/apip/auth/v2/token'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAuthentication

Returns a new instance of Authentication.



9
10
11
12
# File 'lib/change_health/authentication.rb', line 9

def initialize
  @response     = nil
  @request_time = nil
end

Instance Attribute Details

#responseObject

Returns the value of attribute response.



5
6
7
# File 'lib/change_health/authentication.rb', line 5

def response
  @response
end

Instance Method Details

#access_headerObject



62
63
64
65
66
# File 'lib/change_health/authentication.rb', line 62

def access_header
  {
    'Authorization' => "Bearer #{access_token}"
  }
end

#access_tokenObject



40
41
42
# File 'lib/change_health/authentication.rb', line 40

def access_token
  @response['access_token'] if @response
end

#authenticate(base_uri: nil) ⇒ Object



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
# File 'lib/change_health/authentication.rb', line 14

def authenticate(base_uri: nil)
  if expires?
    base_uri ||= Connection.base_uri
    request = {
      body: {
        client_id: ChangeHealth.configuration.client_id,
        client_secret: ChangeHealth.configuration.client_secret,
        grant_type: ChangeHealth.configuration.grant_type
      },
      endpoint: AUTH_ENDPOINT
    }

    response = Connection.new.request(**request, auth: false, base_uri: base_uri)

    if false == response.ok?
      @response = nil
      raise ChangeHealthException.from_response(response, msg: 'Authentication')
    else
      @request_time = Time.now
      @response = response
    end
  end

  self
end

#expire!Object



68
69
70
# File 'lib/change_health/authentication.rb', line 68

def expire!
  @response = nil
end

#expires?(seconds_from_now = 60) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
59
60
# File 'lib/change_health/authentication.rb', line 56

def expires?(seconds_from_now = 60)
  return expiry.utc <= (Time.now + seconds_from_now).utc if expiry

  true
end

#expires_inObject



44
45
46
# File 'lib/change_health/authentication.rb', line 44

def expires_in
  @response['expires_in'].to_i if @response
end

#expiryObject



52
53
54
# File 'lib/change_health/authentication.rb', line 52

def expiry
  @request_time + expires_in if @request_time && expires_in
end

#token_typeObject



48
49
50
# File 'lib/change_health/authentication.rb', line 48

def token_type
  @response['token_type'] if @response
end