Class: ZuoraAPI::Oauth

Inherits:
Login
  • Object
show all
Defined in:
lib/zuora_api_oauth_alpha/logins/oauth.rb

Constant Summary

Constants inherited from Login

Login::ENVIRONMENTS, Login::REGIONS

Instance Attribute Summary collapse

Attributes inherited from Login

#authentication_type, #current_error, #current_session, #entity_id, #environment, #errors, #password, #region, #status, #tenant_id, #tenant_name, #timeout_sleep, #url, #user_info, #username, #wsdl_number

Instance Method Summary collapse

Methods inherited from Login

#aqua_endpoint, #aqua_query, #checkJRStatus, #createJournalRun, #dateFormat, #describe_call, endpoints, environments, #fileURL, #getDataSourceExport, #getFileById, #get_catalog, #get_file, #get_session, #query, #raise_errors, regions, #rest_call, #rest_endpoint, #soap_call, #update_create_tenant, #update_environment

Constructor Details

#initialize(oauth_client_id: nil, oauth_secret: nil, z_session_token: nil, bearer_token: nil, oauth_session_expires_at: nil, **keyword_args) ⇒ Oauth

Returns a new instance of Oauth.



5
6
7
8
9
10
11
12
13
14
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 5

def initialize(oauth_client_id: nil, oauth_secret: nil, z_session_token: nil, bearer_token: nil, oauth_session_expires_at: nil,  **keyword_args)
  @supported_authentication_types = [:basic, :bearer]
  self.z_session_token = z_session_token if z_session_token.present?
  self.bearer_token = bearer_token if z_session_token.present?
  self.oauth_session_expires_at = oauth_session_expires_at if z_session_token.present?
  @oauth_client_id = oauth_client_id
  @oauth_secret = oauth_secret
  raise ZuoraAPI::Exceptions::ZuoraAPIAuthenticationTypeError.new("Request Oauth Login but either 'Oauth Client Id' or 'Oauth Secret' were not passed") if @oauth_client_id.blank? || @oauth_secret.blank?
  super
end

Instance Attribute Details

#authentication_order_preferenceObject

Returns the value of attribute authentication_order_preference.



3
4
5
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 3

def authentication_order_preference
  @authentication_order_preference
end

#bearer_tokenObject

Returns the value of attribute bearer_token.



3
4
5
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 3

def bearer_token
  @bearer_token
end

#oauth_client_idObject

Returns the value of attribute oauth_client_id.



3
4
5
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 3

def oauth_client_id
  @oauth_client_id
end

#oauth_secretObject

Returns the value of attribute oauth_secret.



3
4
5
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 3

def oauth_secret
  @oauth_secret
end

#oauth_session_expires_atObject

Returns the value of attribute oauth_session_expires_at.



3
4
5
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 3

def oauth_session_expires_at
  @oauth_session_expires_at
end

#stored_session_typeObject

Returns the value of attribute stored_session_type.



3
4
5
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 3

def stored_session_type
  @stored_session_type
end

#z_session_tokenObject

Returns the value of attribute z_session_token.



3
4
5
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 3

def z_session_token
  @z_session_token
end

Instance Method Details

#authentication_prefix(auth_type) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 36

def authentication_prefix(auth_type)
  if auth_type == :bearer
    return "Bearer " 
  elsif auth_type == :basic
    return "ZSession "
  else 
    raise ZuoraAPI::Exceptions::ZuoraAPIAuthenticationTypeError.new("Oauth Login, does not support Authentication of Type: #{auth_type}") if !@supported_authentication_types.include?(auth_type)
  end
end

#check_session(auth_type = :basic) ⇒ Object



46
47
48
49
50
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 46

def check_session(auth_type = :basic)
  raise ZuoraAPI::Exceptions::ZuoraAPIAuthenticationTypeError.new("Oauth Login, does not support Authentication of Type: #{auth_type}") if !@supported_authentication_types.include?(auth_type)
  return true if (auth_type != @stored_session_type || @stored_session_type.nil?)
  return false
end

#get_bearer_tokenObject



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 113

def get_bearer_token
  begin
    tries ||= 2
    if !oauth_expired?
      self.current_error = nil
      self.status = 'Active'
    else
      encoded_url = URI.encode(self.rest_endpoint.chomp('v1/').concat('oauth/token'))
      url = URI.parse(encoded_url)
      response = HTTParty.post(url,:headers => {:content_type => "application/x-www-form-urlencoded"}, :body => {:client_id=>@oauth_client_id, :client_secret=>@oauth_secret, :grant_type=>"client_credentials"})
      if JSON.parse(response.body)["error"].nil?
        @bearer_token = JSON.parse(response.body)["access_token"]
        @oauth_session_expires_at = Time.now.to_i + JSON.parse(response.body)["expires_in"].to_i
        @stored_session_type = :bearer
        self.current_error = nil
        self.status = 'Active'
      else 
        self.current_error = "Problem with the Credentials"
        self.status = 'Invalid'
      end
    end

    return @bearer_token
  rescue ZuoraAPI::Exceptions::ZuoraAPISessionError => ex
    if !(tries -= 1).zero? && z_session
      Rails.logger.debug {"Session Invalid"}
      self.new_session
      retry
    else
      if errors.include?(ex.class)
        raise ex
      else
        return [output_json, response]
      end
    end
  rescue ZuoraAPI::Exceptions::ZuoraAPIError, ZuoraAPI::Exceptions::ZuoraAPIRequestLimit, ZuoraAPI::Exceptions::ZuoraAPILockCompetition  => ex
    if errors.include?(ex.class)
      raise ex
    else
      return [output_json, response]
    end
  rescue Net::ReadTimeout, Net::OpenTimeout, Errno::EPIPE, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError => ex
    if !(tries -= 1).zero?
      Rails.logger.info {"#{ex.class} Timed out will retry after 5 seconds"}
      sleep(self.timeout_sleep)
      retry
    else
      self.current_error = "Request timed out. Try again"
      self.status = 'Timeout'
      return self.status
    end
  end
end

#get_z_session(debug = false) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 62

def get_z_session(debug = false)
  begin
    tries ||= 2
    get_bearer_token()
    if !@entity_id.nil?
      response = HTTParty.get(self.rest_endpoint("connections"),  headers: {:Authorization => "Bearer " + @bearer_token , :entityId => @entity_id })
    else 
      response = HTTParty.get(self.rest_endpoint("connections"),  headers: {:Authorization => "Bearer " + @bearer_token}) 
    end
    if JSON.parse(response.body)["success"] ##.to_bool
      @z_session_token = response.headers.to_h['set-cookie'][0].split(';')[0].split('=',2)[1]
      @stored_session_type = :basic
      self.current_error     = nil
      self.status            = 'Active'
    else 
      self.current_error = JSON.parse(response.body)["reasons"][0]["message"]
      self.status = "Invalid"
    end

    return @z_session_token
  rescue ZuoraAPI::Exceptions::ZuoraAPISessionError => ex
    if !(tries -= 1).zero? && z_session
      Rails.logger.debug {"Session Invalid"}
      self.new_session
      retry
    else
      if errors.include?(ex.class)
        raise ex
      else
        return [output_json, response]
      end
    end
  rescue ZuoraAPI::Exceptions::ZuoraAPIError, ZuoraAPI::Exceptions::ZuoraAPIRequestLimit, ZuoraAPI::Exceptions::ZuoraAPILockCompetition  => ex
    if errors.include?(ex.class)
      raise ex
    else
      return [output_json, response]
    end
  rescue Net::ReadTimeout, Net::OpenTimeout, Errno::EPIPE, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError => ex
    if !(tries -= 1).zero?
      Rails.logger.info {"#{ex.class} Timed out will retry after 5 seconds"}
      sleep(self.timeout_sleep)
      retry
    else
      self.current_error = "Request timed out. Try again"
      self.status = 'Timeout'
      return self.status
    end
  end
end

#new_session(auth_type = :basic) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 52

def new_session(auth_type = :basic)
  if auth_type == :basic
     return get_z_session()
  elsif auth_type == :bearer
    return get_bearer_token()
  else 
    raise ZuoraAPI::Exceptions::ZuoraAPIAuthenticationTypeError.new("Oauth Login, does not support Authentication of Type: #{auth_type}") if !@supported_authentication_types.include?(auth_type)
  end
end

#oauth_expired?Boolean

Returns:

  • (Boolean)


167
168
169
# File 'lib/zuora_api_oauth_alpha/logins/oauth.rb', line 167

def oauth_expired?
  return @oauth_session_expires_at.nil? ? true : (@oauth_session_expires_at < Time.now.to_i)
end