Skip to content

Commit 81ffaeb

Browse files
committed
Updated logging framework
1 parent 552b3d2 commit 81ffaeb

26 files changed

+543
-277
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ The CyberSource Ruby client provides convenient access to the [CyberSource REST
1212
* Ruby 2.5.0 or higher
1313
* [CyberSource Account](https://developer.cybersource.com/api/developer-guides/dita-gettingstarted/registration.html)
1414
* [CyberSource API Keys](https://prod.developer.cybersource.com/api/developer-guides/dita-gettingstarted/registration/createCertSharedKey.html)
15-
15+
1616
## Dependencies
1717

1818
* activesupport 6.0.3.2
@@ -37,9 +37,9 @@ Be sure to always use HTTPS rubygems source in your gemfile and include the cybe
3737

3838
Use of this SDK and the CyberSource APIs requires having an account on our system. You can find details of getting a test account and creating your keys [here](https://developer.cybersource.com/api/developer-guides/dita-gettingstarted/registration.html)
3939

40-
Once you have your keys, simply load them into the appropriate variables in your code, as per the below sample code dealing with the authentication part of the API request.
40+
Once you have your keys, simply load them into the appropriate variables in your code, as per the below sample code dealing with the authentication part of the API request.
4141

42-
Remember this SDK is for use in server-side Ruby applications that access the CyberSource REST API and credentials should always be securely stored and accessed appropriately.
42+
Remember this SDK is for use in server-side Ruby applications that access the CyberSource REST API and credentials should always be securely stored and accessed appropriately.
4343

4444
## SDK Usage Examples and Sample Code
4545

cybersource_rest_client.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Gem::Specification.new do |s|
2525
s.summary = "CyberSource Ruby SDK Gem"
2626
s.description = "Simple REST API for the CyberSource Global Payments Platform"
2727
s.license = "CyberSource"
28-
s.files = Dir.glob("{lib}/{cybersource_rest_client}/**/*") + Dir.glob("{lib}/{AuthenticationSDK}/authentication/**/*") + Dir.glob("{lib}/{AuthenticationSDK}/core/**/*") + Dir.glob("{lib}/{AuthenticationSDK}/util/**/*") + Dir.glob("{lib}/cybersource_rest_client.rb")
28+
s.files = Dir.glob("{lib}/{cybersource_rest_client}/**/*") + Dir.glob("{lib}/{AuthenticationSDK}/authentication/**/*") + Dir.glob("{lib}/{AuthenticationSDK}/core/**/*") + Dir.glob("{lib}/{AuthenticationSDK}/util/**/*") + Dir.glob("{lib}/{AuthenticationSDK}/logging/**/*") + Dir.glob("{lib}/cybersource_rest_client.rb")
2929
s.required_ruby_version = ">= 1.9"
3030

3131
s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1'
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
{
22
"moduleName" : "CyberSource",
3-
"gemName" : "cybersource_rest_client"
3+
"gemName" : "cybersource_rest_client"
44
}

generator/cybersource-ruby-template/api.mustache

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ module {{moduleName}}
1111

1212
def initialize(api_client = ApiClient.default, config)
1313
@api_client = api_client
14-
@api_client.set_configuration(config)
14+
@api_client.set_configuration(config)
1515
end
1616
{{#operation}}
1717
{{#summary}}
@@ -40,14 +40,14 @@ module {{moduleName}}
4040
{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}
4141
{{/required}}{{/allParams}} # @return [Array<({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Fixnum, Hash)>] {{#returnType}}{{{returnType}}} data{{/returnType}}{{^returnType}}nil{{/returnType}}, response status code and response headers
4242
def {{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
43-
44-
if @api_client.config.debugging
45-
begin
46-
raise
47-
@api_client.config.logger.debug 'Calling API: {{classname}}.{{operationId}} ...'
48-
rescue
49-
puts 'Cannot write to log'
50-
end
43+
44+
if @api_client.config.debugging
45+
begin
46+
raise
47+
@api_client.config.logger.debug 'Calling API: {{classname}}.{{operationId}} ...'
48+
rescue
49+
puts 'Cannot write to log'
50+
end
5151
end
5252
{{#allParams}}
5353
{{#required}}
@@ -189,13 +189,13 @@ module {{moduleName}}
189189
:auth_names => auth_names{{#returnType}},
190190
:return_type => '{{{returnType}}}'{{/returnType}})
191191
if @api_client.config.debugging
192-
begin
193-
raise
194-
@api_client.config.logger.debug "API called: {{classname}}#{{operationId}}\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
195-
rescue
196-
puts 'Cannot write to log'
197-
end
198-
end
192+
begin
193+
raise
194+
@api_client.config.logger.debug "API called: {{classname}}#{{operationId}}\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
195+
rescue
196+
puts 'Cannot write to log'
197+
end
198+
end
199199
return data, status_code, headers
200200
end
201201
{{/operation}}

generator/cybersource-ruby-template/api_client.mustache

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ module {{moduleName}}
2020
attr_accessor :default_headers
2121

2222
# Defines the client ID for the SDK
23-
attr_accessor :client_id
23+
attr_accessor :client_id
2424

2525
# Defines the user-defined Accept Header Type
2626
attr_accessor :accept_header
@@ -64,7 +64,7 @@ module {{moduleName}}
6464
raise
6565
@config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
6666
rescue
67-
puts 'Cannot write to log'
67+
puts 'Cannot write to log'
6868
end
6969
end
7070

@@ -162,7 +162,7 @@ module {{moduleName}}
162162
download_file(request) if opts[:return_type] == 'File'
163163
request
164164
end
165-
# set merchantConfig
165+
# set merchantConfig
166166
def set_configuration(config)
167167
require_relative '../AuthenticationSDK/core/MerchantConfig.rb'
168168
$merchantconfig_obj = Merchantconfig.new(config)
@@ -175,7 +175,7 @@ module {{moduleName}}
175175
request_target = get_query_param(path, query_params)
176176
# Request Type. [Non-Editable]
177177
request_type = http_method.to_s
178-
log_obj = Log.new $merchantconfig_obj.logDirectory, $merchantconfig_obj.logFilename, $merchantconfig_obj.logSize, $merchantconfig_obj.enableLog
178+
log_obj = Log.new $merchantconfig_obj.log_config, "ApiClient"
179179
# Set Request Type into the merchant config object.
180180
$merchantconfig_obj.requestType = request_type
181181
# Set Request Target into the merchant config object.
@@ -188,14 +188,13 @@ module {{moduleName}}
188188
$merchantconfig_obj.requestUrl = url
189189
# Calling APISDK, Apisdk.controller.
190190
gmtDateTime = DateTime.now.httpdate
191-
token = Authorization.new.getToken($merchantconfig_obj, gmtDateTime, log_obj)
191+
token = Authorization.new.getToken($merchantconfig_obj, gmtDateTime)
192192

193193
# Adding client ID header
194194
header_params['v-c-client-id'] = @client_id
195195

196196
# Adding solution ID header
197197
# header_params['v-c-solution-id'] = $merchantconfig_obj.solutionId if !$merchantconfig_obj.solutionId.nil? && !$merchantconfig_obj.solutionId.empty?
198-
199198
# HTTP header 'Accept' (if needed)
200199
if $merchantconfig_obj.authenticationType.upcase == Constants::AUTH_TYPE_HTTP
201200
# Appending headers for Get Connection
@@ -204,7 +203,7 @@ module {{moduleName}}
204203
header_params['Host'] = $merchantconfig_obj.requestHost
205204
header_params['Signature'] = token
206205
if request_type == Constants::POST_REQUEST_TYPE || request_type == Constants::PUT_REQUEST_TYPE || request_type == Constants::PATCH_REQUEST_TYPE
207-
digest = DigestGeneration.new.generateDigest(body_params, log_obj)
206+
digest = DigestGeneration.new.generateDigest(body_params)
208207
digest_payload = Constants::SHA256 + digest
209208
header_params['Digest'] = digest_payload
210209
end
@@ -231,7 +230,7 @@ module {{moduleName}}
231230
end
232231
request_target
233232
end
234-
233+
235234
# Check if the given MIME is a JSON MIME.
236235
# JSON MIME examples:
237236
# application/json

generator/cybersource-ruby-template/gem.mustache

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@ require 'AuthenticationSDK/util/Utility.rb'
77
require 'AuthenticationSDK/util/PropertiesUtil.rb'
88
require 'AuthenticationSDK/util/Constants.rb'
99
require 'AuthenticationSDK/util/Cache.rb'
10-
require 'AuthenticationSDK/util/ApiException.rb'
10+
require 'AuthenticationSDK/util/ExceptionHandler.rb'
1111
require 'AuthenticationSDK/core/MerchantConfig.rb'
12-
require 'AuthenticationSDK/core/Logger.rb'
1312
require 'AuthenticationSDK/core/ITokenGeneration.rb'
1413
require 'AuthenticationSDK/core/Authorization.rb'
14+
require 'AuthenticationSDK/logging/log_configuration.rb'
15+
require 'AuthenticationSDK/logging/log_factory.rb'
1516
require 'AuthenticationSDK/authentication/payloadDigest/digest.rb'
1617
require 'AuthenticationSDK/authentication/jwt/JwtToken.rb'
1718
require 'AuthenticationSDK/authentication/http/HttpSignatureHeader.rb'

generator/cybersource_ruby_sdk_gen.bat

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
@echo off
1+
@echo off
22

33
cd %~dp0
44

@@ -11,8 +11,8 @@ rd /s /q ..\spec
1111
del ..\lib\cybersource_rest_client.rb
1212

1313
REM Command to generate SDK
14-
15-
java -jar swagger-codegen-cli-2.2.3.jar generate -t cybersource-ruby-template -i cybersource-rest-spec.json -l ruby -o ../ -c %~dp0cybersource-ruby-config.json
14+
15+
java -jar swagger-codegen-cli-2.2.3.jar generate -t cybersource-ruby-template -i cybersource-rest-spec.json -l ruby -o ../ -c %~dp0cybersource-ruby-config.json
1616

1717
powershell -Command "(Get-Content ..\lib\cybersource_rest_client\api\secure_file_share_api.rb) | ForEach-Object { $_ -replace 'select_header_content_type\(\[''application/json;charset=utf-8', 'select_header_content_type([''*/*' } | Set-Content ..\lib\cybersource_rest_client\api\secure_file_share_api.rb"
1818

lib/AuthenticationSDK/authentication/http/GetSignatureParameter.rb

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
require_relative '../../util/Constants.rb'
22
require_relative '.././payloadDigest/digest.rb'
3+
require_relative '../../logging/log_factory.rb'
34
require 'openssl'
45
# This function returns value for paramter Signature which is then passed to Signature header
56
# paramter 'Signature' is calucated based on below key values and then signed with SECRET KEY -
@@ -13,20 +14,25 @@
1314
# v-c-merchant-id: set value to Cybersource Merchant ID
1415
# This ID can be found on EBC portal*/
1516
class SignatureParameter
16-
def generateSignatureParameter(merchantconfig_obj, gmtdatetime, log_obj)
17+
@log_obj
18+
def generateSignatureParameter(merchantconfig_obj, gmtdatetime)
19+
@log_obj = Log.new merchantconfig_obj.log_config, "GetSignatureParameter"
20+
1721
request_type = merchantconfig_obj.requestType.upcase
1822
merchantSecretKey = merchantconfig_obj.merchantSecretKey
23+
1924
signatureString = Constants::HOST + ': ' + merchantconfig_obj.requestHost
2025
signatureString << "\n"+ Constants::DATE + ': ' + gmtdatetime
2126
signatureString << "\n(request-target): "
27+
2228
if request_type == Constants::GET_REQUEST_TYPE || request_type == Constants::DELETE_REQUEST_TYPE
2329
targetUrl=gettargetUrlForGetDelete(request_type,merchantconfig_obj)
2430
signatureString << targetUrl + "\n"
2531
elsif request_type == Constants::POST_REQUEST_TYPE || request_type == Constants::PUT_REQUEST_TYPE || request_type == Constants::PATCH_REQUEST_TYPE
2632
targetUrl=gettargetUrlForPutPost(request_type,merchantconfig_obj)
2733
signatureString << targetUrl + "\n"
2834
payload = merchantconfig_obj.requestJsonData
29-
digest = DigestGeneration.new.generateDigest(payload, log_obj)
35+
digest = DigestGeneration.new.generateDigest(payload)
3036
digest_payload = Constants::SHA256 + digest
3137
signatureString << Constants::DIGEST + ': ' + digest_payload + "\n"
3238
end
@@ -40,10 +46,11 @@ def generateSignatureParameter(merchantconfig_obj, gmtdatetime, log_obj)
4046
base64EncodedSignature = Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', decodedKey, encodedSignatureString))
4147
return base64EncodedSignature
4248
rescue StandardError => err
43-
log_obj.logger.error(err.message)
44-
log_obj.logger.error(err.backtrace)
45-
puts 'Check log for more details.'
46-
exit!
49+
@log_obj.logger.error(err.message)
50+
@log_obj.logger.error(err.backtrace)
51+
raise err
52+
# puts 'Check log for more details.'
53+
# exit!
4754
end
4855
def gettargetUrlForGetDelete(request_type, merchantconfig_obj)
4956
targetUrlForGetDelete = ''

lib/AuthenticationSDK/authentication/http/HttpSignatureHeader.rb

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
require 'base64'
22
require_relative '../../core/ITokenGeneration.rb'
33
require_relative '../../util/Constants.rb'
4-
require_relative '../../util/ApiException.rb'
54
require_relative '.././payloadDigest/digest.rb'
65
require_relative '.././http/GetSignatureParameter.rb'
6+
require_relative '../../logging/log_factory.rb'
7+
require_relative '../../util/ExceptionHandler.rb'
78
public
89
# SignatureHeader return SignatureHeader Value that contains following paramters
910
# * keyid -- Merchant ID obtained from EBC portal
@@ -15,23 +16,30 @@
1516
# * signature -- Signature header has paramter called signature
1617
# Paramter 'Signature' must contain all the paramters mentioned in header above in given order
1718
class GenerateHttpSignature
19+
@log_obj
1820
# Generates Signature based on the requestType
19-
def getToken(merchantconfig_obj, gmtdatetime, log_obj)
21+
def getToken(merchantconfig_obj, gmtdatetime)
22+
@log_obj = Log.new merchantconfig_obj.log_config, "GenerateHttpSignature"
23+
2024
request_type = merchantconfig_obj.requestType.upcase
2125
signatureHeaderValue =''
2226
signatureHeaderValue << Constants::KEY_ID + merchantconfig_obj.merchantKeyId + "\""
27+
2328
# Algorithm should be always HmacSHA256 for http signature
2429
signatureHeaderValue << ', ' + Constants::ALGORITHM + Constants::SIGNATURE_ALGORITHM + "\""
30+
2531
# Headers - list is choosen based on HTTP method
2632
signatureheader=getsignatureHeader(request_type)
2733
signatureHeaderValue << ', ' + Constants::HEADERS_PARAM + signatureheader + "\""
34+
2835
# Get Value for parameter 'Signature' to be passed to Signature Header
29-
signature_value = SignatureParameter.new.generateSignatureParameter(merchantconfig_obj, gmtdatetime, log_obj)
36+
signature_value = SignatureParameter.new.generateSignatureParameter(merchantconfig_obj, gmtdatetime)
3037
signatureHeaderValue << ', ' + Constants::SIGNATURE_PARAM + signature_value + "\""
3138
return signatureHeaderValue
3239
rescue StandardError => err
33-
ApiException.new.apiexception(err,log_obj)
34-
exit!
40+
@log_obj.logger.error(ExceptionHandler.new.new_api_exception err)
41+
raise err
42+
# exit!
3543
end
3644
def getsignatureHeader(request_type)
3745
headers = ''

lib/AuthenticationSDK/authentication/jwt/JwtToken.rb

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,56 +5,71 @@
55
require 'active_support'
66
require_relative '../../core/ITokenGeneration.rb'
77
require_relative '../../util/Constants.rb'
8-
require_relative '../../util/ApiException.rb'
8+
require_relative '../../util/ExceptionHandler.rb'
99
require_relative '../../util/Cache.rb'
1010
require_relative '../../authentication/payloadDigest/digest.rb'
11+
require_relative '../../logging/log_factory.rb'
1112
public
12-
#JWT Token-generated based on the Request type
1313
class GenerateJwtToken
14-
def getToken(merchantconfig_obj,gmtDatetime,log_obj)
14+
@log_obj
15+
16+
#JWT Token-generated based on the Request type
17+
def getToken(merchantconfig_obj,gmtDatetime)
18+
@log_obj = Log.new merchantconfig_obj.log_config, "JwtToken"
19+
1520
jwtBody = ''
1621
request_type = merchantconfig_obj.requestType.upcase
1722
filePath = merchantconfig_obj.keysDirectory + '/' + merchantconfig_obj.keyFilename + '.p12'
23+
1824
if (!File.exist?(filePath))
1925
raise Constants::ERROR_PREFIX + Constants::FILE_NOT_FOUND + File.expand_path(filePath)
2026
end
27+
2128
p12File = File.binread(filePath)
22-
jwtBody=getJwtBody(request_type, gmtDatetime, merchantconfig_obj, log_obj)
29+
jwtBody=getJwtBody(request_type, gmtDatetime, merchantconfig_obj)
2330
claimSet = JSON.parse(jwtBody)
2431
p12FilePath = OpenSSL::PKCS12.new(p12File, merchantconfig_obj.keyPass)
32+
2533
# Generating certificate.
2634
cacheObj = ActiveSupport::Cache::MemoryStore.new
2735
x5Cert = Cache.new.fetchCachedCertificate(filePath, p12File, merchantconfig_obj.keyPass, cacheObj)
36+
2837
# Generating Public key.
2938
publicKey = OpenSSL::PKey::RSA.new(p12FilePath.key.public_key)
39+
3040
#Generating Private Key
3141
privateKey = OpenSSL::PKey::RSA.new(p12FilePath.key)
42+
3243
# JWT token-Generates using RS256 algorithm only
3344
x5clist = [x5Cert]
3445
customHeaders = {}
3546
customHeaders['v-c-merchant-id'] = merchantconfig_obj.keyAlias
3647
customHeaders['x5c'] = x5clist
48+
3749
# Generating JWT token
3850
token = JWT.encode(claimSet, privateKey, 'RS256', customHeaders)
3951
return token
4052
rescue StandardError => err
4153
if err.message.include? 'PKCS12_parse: mac verify failure'
42-
ApiException.new.customerror(Constants::ERROR_PREFIX + Constants::INCORRECT_KEY_PASS,log_obj)
43-
exit!
54+
@log_obj.logger.error(ExceptionHandler.new.new_custom_error Constants::ERROR_PREFIX + Constants::INCORRECT_KEY_PASS)
55+
# exit!
4456
else
45-
ApiException.new.apiexception(err,log_obj)
46-
exit!
57+
@log_obj.logger.error(ExceptionHandler.new.new_api_exception err)
58+
# exit!
4759
end
60+
raise err
4861
end
49-
def getJwtBody(request_type, gmtDatetime, merchantconfig_obj,log_obj)
62+
63+
def getJwtBody(request_type, gmtDatetime, merchantconfig_obj)
5064
if request_type == Constants::POST_REQUEST_TYPE || request_type == Constants::PUT_REQUEST_TYPE || request_type == Constants::PATCH_REQUEST_TYPE
5165
payload = merchantconfig_obj.requestJsonData
66+
5267
# Note: Digest is not passed for GET calls
53-
digest = DigestGeneration.new.generateDigest(payload, log_obj)
68+
digest = DigestGeneration.new.generateDigest(payload)
5469
jwtBody = "{\n \"digest\":\"" + digest + "\", \"digestAlgorithm\":\"SHA-256\", \"iat\":\"" + gmtDatetime + "\"}"
5570
elsif request_type == Constants::GET_REQUEST_TYPE || request_type == Constants::DELETE_REQUEST_TYPE
5671
jwtBody = "{\n \"iat\":\"" + gmtDatetime + "\"\n} \n\n"
57-
else
72+
else
5873
raise StandardError.new(Constants::ERROR_PREFIX + Constants::INVALID_REQUEST_TYPE_METHOD)
5974
end
6075
end

0 commit comments

Comments
 (0)