Class: AdsCommon::Auth::OAuth2Handler

Inherits:
BaseHandler show all
Defined in:
lib/ads_common/auth/oauth2_handler.rb

Overview

Credentials class to handle OAuth2.0 authentication.

Constant Summary collapse

OAUTH2_CONFIG =
{
    :authorization_uri =>
      'https://accounts.google.com/o/oauth2/auth',
    :token_credential_uri =>
      'https://accounts.google.com/o/oauth2/token'
}
DEFAULT_CALLBACK =
'urn:ietf:wg:oauth:2.0:oob'

Instance Method Summary collapse

Constructor Details

#initialize(config, scope) ⇒ OAuth2Handler

Initializes the OAuthHandler2 with all the necessary details.

Args:

  • config: Config object with library configuration

  • scope: OAuth authorization scope



49
50
51
52
# File 'lib/ads_common/auth/oauth2_handler.rb', line 49

def initialize(config, scope)
  super(config)
  @scope, @client = scope, nil
end

Instance Method Details

#auth_string(credentials) ⇒ Object

Generates auth string for OAuth2.0 method of authentication.

Args:

  • credentials: credentials set for authorization

Returns:

  • Authentication string



76
77
78
79
80
# File 'lib/ads_common/auth/oauth2_handler.rb', line 76

def auth_string(credentials)
  token = get_token(credentials)
  return ::Signet::OAuth2.generate_bearer_authorization_header(
      token[:access_token])
end

#get_token(credentials = nil) ⇒ Object

Overrides base get_token method to account for the token expiration.



83
84
85
86
87
# File 'lib/ads_common/auth/oauth2_handler.rb', line 83

def get_token(credentials = nil)
  token = super(credentials)
  token = refresh_token! if !@client.nil? && @client.expired?
  return token
end

#handle_error(error) ⇒ Object



62
63
64
65
66
# File 'lib/ads_common/auth/oauth2_handler.rb', line 62

def handle_error(error)
  # TODO: Add support.
  get_logger().error(error)
  raise error
end

#property_changed(prop, value) ⇒ Object

Invalidates the stored token if the required credential has changed.



55
56
57
58
59
60
# File 'lib/ads_common/auth/oauth2_handler.rb', line 55

def property_changed(prop, value)
  oauth2_keys = [:oauth2_client_id, :oauth2_client_secret, :oauth2_token]
  if oauth2_keys.include?(prop)
    @token, @client = nil, nil
  end
end

#refresh_token!Object

Refreshes access token from refresh token.



90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/ads_common/auth/oauth2_handler.rb', line 90

def refresh_token!()
  return nil if @token.nil? or @token[:refresh_token].nil?
  begin
    if @client.issued_at.is_a?(String)
      @client.issued_at = Time.parse(@client.issued_at)
    end
    @client.refresh!
  rescue Signet::AuthorizationError => e
    raise AdsCommon::Errors::AuthError.new("OAuth2 token refresh failed",
        e, (e.response.nil?) ? nil : e.response.body)
  end
  @token = token_from_client(@client)
  return @token
end