zuora_connect 2.0.60r → 2.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a6b7949598476b39650e1fb8b5f4c0940715a4fd7ceea1945b5049f93a468d41
4
- data.tar.gz: 8505c3ee1339e3ce136424898b8202466c3264391e5920c0107f706927edae15
3
+ metadata.gz: 0342c5ac7396b4e8ba75aff8dbab5d579fa6d0ad04a421b7d1d809ab3abbd90a
4
+ data.tar.gz: 70f7277a93fec8e481f63e56f85e466b5e0b4d1307e2413e4f8da9497e980be2
5
5
  SHA512:
6
- metadata.gz: c89370d8c846ace233b99f76ef6ee53aa0ec54deb4a7005457b154ae2597c2f6f8e9120816eb47a99083acf1429d770d6b01406af3f58b0f1e29904bfca54988
7
- data.tar.gz: 20214d6197712b2aaf380535fbb2e635b0296cd8271c85f1bac28e3bacbb1587eea40542b4ac9a93c1f55ab71788c9b9c0a3eb424eee1d9d53f79042f3811c65
6
+ metadata.gz: eb6497a343dde2b4a3edfe470c8e5a44eb37ff99b75ed434138c280e8ac25bf36806d58fbb477772182596917f1c37c0e237bd55e88f646e149743477fba2f15
7
+ data.tar.gz: f0b1f8b6f647f204ce8c4bfed7a8e77b49f3aada0faf6a0c31fc47675f5bfca67feb464692006bcb490977a577d1d5a3feab53886815f4c6472023e9ade6823b
@@ -1,11 +1,10 @@
1
1
  module ZuoraConnect
2
2
  class StaticController < ApplicationController
3
- before_action :authenticate_connect_app_request, :except => [:metrics, :health, :initialize_app, :provision, :instance_user]
4
- before_action :clear_connect_app_session, :only => [:metrics, :health, :initialize_app, :provision, :instance_user]
5
- after_action :persist_connect_app_session, :except => [:metrics, :health, :initialize_app, :provision, :instance_user]
6
-
7
- skip_before_action :verify_authenticity_token, :only => [:initialize_app, :provision]
8
- http_basic_authenticate_with name: ENV['PROVISION_USER'], password: ENV['PROVISION_SECRET'], :only => [:provision, :instance_user]
3
+ before_action :authenticate_connect_app_request, :except => [:metrics, :health, :initialize_app]
4
+ before_action :clear_connect_app_session, :only => [:metrics, :health, :initialize_app]
5
+ after_action :persist_connect_app_session, :except => [:metrics, :health, :initialize_app]
6
+
7
+ skip_before_action :verify_authenticity_token, :only => [:initialize_app]
9
8
 
10
9
  def metrics
11
10
  type = params[:type].present? ? params[:type] : "versions"
@@ -14,11 +13,11 @@ module ZuoraConnect
14
13
 
15
14
  def health
16
15
  if params[:error].present?
17
- begin
16
+ begin
18
17
  raise ZuoraConnect::Exceptions::Error.new('This is an error')
19
18
  rescue => ex
20
19
  case params[:error]
21
- when 'Log'
20
+ when 'Log'
22
21
  Rails.logger.error("Error in Health", ex)
23
22
  when 'Exception'
24
23
  raise
@@ -35,13 +34,11 @@ module ZuoraConnect
35
34
  def initialize_app
36
35
  begin
37
36
  authenticate_connect_app_request
38
- unless performed?
39
- @appinstance.new_session(:session => @appinstance.data_lookup(:session => session))
40
- render json: {
41
- message: 'Success',
42
- status: 200
43
- }, status: 200
44
- end
37
+ @appinstance.new_session(:session => @appinstance.data_lookup(:session => session))
38
+ render json: {
39
+ message: "Success",
40
+ status: 200
41
+ }, status: 200
45
42
  rescue => ex
46
43
  Rails.logger.error("Failed to Initialize application", ex)
47
44
  if performed?
@@ -55,74 +52,6 @@ module ZuoraConnect
55
52
  end
56
53
  end
57
54
 
58
- def provision
59
- create_new_instance
60
- unless performed?
61
- render json: {
62
- status: 200,
63
- message: 'Success',
64
- app_instance_id: @appinstance.id
65
- }, status: 200
66
- end
67
- rescue StandardError => e
68
- message = 'Failed to provision new instance'
69
- if performed?
70
- Rails.logger.error("#{message}: #{performed?}", e)
71
- else
72
- Rails.logger.error(message, e)
73
- render json: {
74
- status: 500,
75
- message: message
76
- }, status: 500
77
- end
78
- end
79
-
80
- def instance_user
81
- ZuoraConnect::AppInstance.read_master_db do
82
- ZuoraConnect.logger.with_fields = {} if ZuoraConnect.logger.is_a?(Ougai::Logger)
83
- Rails.logger.with_fields = {} if Rails.logger.is_a?(Ougai::Logger)
84
-
85
- if defined?(ElasticAPM) && ElasticAPM.running? && ElasticAPM.respond_to?(:set_label)
86
- ElasticAPM.set_label(:trace_id, request.uuid)
87
- end
88
-
89
- unless params[:id].present?
90
- render json: {
91
- status: 400,
92
- message: 'No app instance id provided'
93
- }, status: :bad_request
94
- return
95
- end
96
-
97
- @appinstance = ZuoraConnect::AppInstance.find(params[:id]).new_session
98
- end
99
-
100
- zuora_client = @appinstance.send(ZuoraConnect::AppInstance::LOGIN_TENANT_DESTINATION).client
101
- client_describe, = zuora_client.rest_call(
102
- url: zuora_client.rest_endpoint('genesis/user/info').gsub('v1/', ''),
103
- session_type: zuora_client.class == ZuoraAPI::Oauth ? :bearer : :basic
104
- )
105
-
106
- render json: {
107
- status: 200,
108
- message: 'Success',
109
- user_id: client_describe['coreUserId'],
110
- username: client_describe['username'],
111
- email: client_describe['workEmail']
112
- }, status: 200
113
- rescue ActiveRecord::RecordNotFound
114
- render json: {
115
- status: 400,
116
- message: 'No app instance found'
117
- }, status: :bad_request
118
- rescue StandardError => e
119
- Rails.logger.error('Error occurred getting user details', e)
120
- render json: {
121
- status: 500,
122
- message: 'Failed to get user details'
123
- }, status: 500
124
- end
125
-
126
55
  private
127
56
 
128
57
  def clear_connect_app_session
@@ -11,7 +11,7 @@ module ZuoraConnect
11
11
  before_destroy :prune_data
12
12
 
13
13
  self.table_name = "zuora_connect_app_instances"
14
- attr_accessor :options, :mode, :logins, :task_data, :last_refresh, :username, :password, :s3_client, :api_version, :drop_message, :new_session_message, :connect_user, :logitems, :user_timezone
14
+ attr_accessor :options, :mode, :logins, :task_data, :last_refresh, :username, :password, :s3_client, :api_version, :drop_message, :new_session_message, :connect_user, :logitems
15
15
  @@telegraf_host = nil
16
16
  REFRESH_TIMEOUT = 2.minute #Used to determine how long to wait on current refresh call before executing another
17
17
  INSTANCE_REFRESH_WINDOW = 1.hours #Used to set how how long till app starts attempting to refresh cached task connect data
@@ -21,10 +21,6 @@ module ZuoraConnect
21
21
  HOLDING_PATTERN_SLEEP = 5.seconds
22
22
  CONNECT_APPLICATION_ID = 0
23
23
  CONNECT_COMMUNICATION_SLEEP = Rails.env.test? ? 0.seconds : 5.seconds
24
- CATALOG_LOOKUP_PAGE_SIZE = 10_000
25
- CATALOG_LOOKUP_CACHE_TIME_KEY = 'CatalogCachedAt'
26
- CATALOG_LOOKUP_TTL = 60.seconds
27
- CATALOG_LOOKUP_CACHE_RESULT_KEY = 'CatalogCache'
28
24
  IGNORED_LOCALS = ['fr', 'ja', 'es', 'zh', 'de']
29
25
  INTERNAL_HOSTS = []
30
26
  LOGIN_TENANT_DESTINATION = 'target_login'
@@ -244,50 +240,7 @@ module ZuoraConnect
244
240
  rescue I18n::InvalidLocale => ex
245
241
  ZuoraConnect.logger.error(ex) if !IGNORED_LOCALS.include?(ex.locale.to_s.downcase)
246
242
  end
247
-
248
- begin
249
- sql = <<-eos
250
- SELECT zuora_users.zuora_identity_response
251
- FROM "#{self.id}".zuora_users
252
- ORDER BY zuora_users.updated_at DESC
253
- LIMIT 1;
254
- eos
255
- user = ActiveRecord::Base.connection.execute(sql).to_a.first
256
-
257
- if user.present?
258
- zuora_identity_response = JSON.parse(user.fetch('zuora_identity_response', '{}'))
259
- self.user_timezone = zuora_identity_response.values.first&.dig('timeZone')
260
- end
261
- rescue => ex
262
- Rails.logger.error('Failed to get users while setting app instance timezone', ex)
263
- end
264
-
265
- if self.user_timezone.present?
266
- # connect instance which has a custom timezone
267
- if !self.auto_deployed? && (
268
- ActiveSupport::TimeZone[self.task_data.dig('user_settings', 'timezone') || '']&.utc_offset !=
269
- ActiveSupport::TimeZone[self.user_timezone]&.utc_offset
270
- )
271
- if self.environment == 'Production'
272
- ZuoraConnect.logger.error(
273
- "Instance and user timezones are different. User has '#{self.user_timezone}' and " \
274
- "instance has '#{self.task_data.dig('user_settings', 'timezone')}'",
275
- app_instance_id: self.id
276
- )
277
- end
278
- self.user_timezone = nil
279
- Time.zone = self.timezone
280
- else
281
- begin
282
- Time.zone = self.user_timezone
283
- rescue ArgumentError
284
- Time.zone = self.timezone
285
- end
286
- end
287
- else
288
- Time.zone = self.timezone
289
- end
290
-
243
+ Time.zone = self.timezone
291
244
  if self.task_data.present?
292
245
  tenants = self.task_data.fetch('tenant_ids', [])
293
246
  organizations = self.task_data.fetch('organizations', [])
@@ -319,10 +272,6 @@ module ZuoraConnect
319
272
  end
320
273
  end
321
274
 
322
- def auto_deployed?
323
- self.id >= 25000000
324
- end
325
-
326
275
  def refresh(session: {})
327
276
  refresh_count ||= 0
328
277
  skip_connect ||= false
@@ -389,10 +338,6 @@ module ZuoraConnect
389
338
  raise
390
339
  end
391
340
 
392
- def aws_secrets
393
- (Rails.application.secrets.aws || {}).transform_keys { |key| key.to_s }
394
- end
395
-
396
341
  #### START KMS ENCRYPTION Methods ####
397
342
  def zuora_logins=(val)
398
343
  write_attribute(:zuora_logins, kms_encrypt(val.to_json))
@@ -405,7 +350,7 @@ module ZuoraConnect
405
350
 
406
351
  def kms_decrypt(value)
407
352
  kms_tries ||= 0
408
- kms_client = Aws::KMS::Client.new({region: aws_secrets['AWS_REGION'], credentials: self.aws_auth_client}.delete_if { |k, v| v.blank? })
353
+ kms_client = Aws::KMS::Client.new({region: Rails.application.secrets.aws['AWS_REGION'], credentials: self.aws_auth_client}.delete_if { |k, v| v.blank? })
409
354
  resp = kms_client.decrypt({ciphertext_blob: [value].pack("H*") })
410
355
  return resp.plaintext
411
356
  rescue *AWS_AUTH_ERRORS => ex
@@ -420,7 +365,7 @@ module ZuoraConnect
420
365
 
421
366
  def kms_encrypt(value)
422
367
  kms_tries ||= 0
423
- kms_client = Aws::KMS::Client.new({region: aws_secrets['AWS_REGION'], credentials: self.aws_auth_client}.delete_if {|k,v| v.blank? })
368
+ kms_client = Aws::KMS::Client.new({region: Rails.application.secrets.aws['AWS_REGION'], credentials: self.aws_auth_client}.delete_if {|k,v| v.blank? })
424
369
 
425
370
  resp = kms_client.encrypt({key_id: kms_key, plaintext: value})
426
371
  return resp.ciphertext_blob.unpack('H*').first
@@ -435,12 +380,12 @@ module ZuoraConnect
435
380
  end
436
381
 
437
382
  def kms_key
438
- return ENV['AWS_KMS_ARN'] || aws_secrets['AWS_KMS_ARN']
383
+ return ENV['AWS_KMS_ARN'] || Rails.application.secrets.dig(:aws,'AWS_KMS_ARN')
439
384
  end
440
385
 
441
386
  def aws_auth_client
442
387
  if Rails.env.to_s == 'development'
443
- return Aws::Credentials.new(aws_secrets['AWS_ACCESS_KEY_ID'], aws_secrets['AWS_SECRET_ACCESS_KEY'])
388
+ return Aws::Credentials.new(Rails.application.secrets.aws['AWS_ACCESS_KEY_ID'], Rails.application.secrets.aws['AWS_SECRET_ACCESS_KEY'])
444
389
  else
445
390
  return nil
446
391
  end
@@ -457,7 +402,7 @@ module ZuoraConnect
457
402
  end
458
403
 
459
404
  def self.write_to_telegraf(*args)
460
- if ZuoraConnect.configuration.enable_metrics && !defined?(Prometheus)
405
+ if ZuoraConnect.configuration.enable_metrics
461
406
  @@telegraf_host = ZuoraConnect::Telegraf.new() if @@telegraf_host == nil
462
407
  unicorn_stats = self.unicorn_listener_stats() if defined?(Unicorn) && Unicorn.respond_to?(:listener_names)
463
408
  @@telegraf_host.write(direction: 'Raindrops', tags: {}, values: unicorn_stats) unless unicorn_stats.blank?
@@ -1010,81 +955,13 @@ module ZuoraConnect
1010
955
  # object_id: The id or id's of the object/objects to be returned.
1011
956
  # child_objects: Whether to include child objects of the object in question.
1012
957
  # cache: Store individual "1" object lookup in redis for caching.
1013
- def catalog_lookup(entity_id: nil, object: :product, object_id: nil, child_objects: false, cache: false, source: 'DB')
958
+ def catalog_lookup(entity_id: nil, object: :product, object_id: nil, child_objects: false, cache: false)
1014
959
  entity_reference = entity_id.blank? ? 'Default' : entity_id
1015
960
 
1016
961
  if object_id.present? && ![Array, String].include?(object_id.class)
1017
962
  raise "Object Id can only be a string or an array of strings"
1018
963
  end
1019
964
 
1020
- if source == 'API'
1021
- catalog_container = {}
1022
-
1023
- if (Redis.current.hget(CATALOG_LOOKUP_CACHE_TIME_KEY, self.id).to_i + CATALOG_LOOKUP_TTL.to_i) > Time.now.to_i
1024
- begin
1025
- catalog_container = JSON.parse(Redis.current.hget(CATALOG_LOOKUP_CACHE_RESULT_KEY, self.id))
1026
- rescue JSON::ParserError => ex
1027
- Rails.logger.warn('Failed to parse catalog cache', ex)
1028
- end
1029
- else
1030
- zuora_login = self.login_lookup(type: 'Zuora').first
1031
- login = zuora_login.client(entity_reference)
1032
-
1033
- response = {
1034
- 'nextPage' => login.rest_endpoint("catalog/products?pageSize=#{CATALOG_LOOKUP_PAGE_SIZE}")
1035
- }
1036
-
1037
- while response['nextPage'].present?
1038
- url = login.rest_endpoint(response['nextPage'].split('/v1/').last)
1039
- output_json, response = login.rest_call(debug: false, url: url, timeout_retry: true)
1040
-
1041
- case object
1042
- when :product
1043
- output_json.fetch('products', []).each do |product|
1044
- rate_plans = {}
1045
- product['productRatePlans'].each do |rate_plan|
1046
- charges = {}
1047
- rate_plan['productRatePlanCharges'].each do |charge|
1048
- charges[charge['id']] = charge.merge(
1049
- {
1050
- 'productId' => product['id'],
1051
- 'productName' => product['name'],
1052
- 'productRatePlanId' => rate_plan['id'],
1053
- 'productRatePlanName' => rate_plan['name'],
1054
- }
1055
- )
1056
- end
1057
-
1058
- rate_plan['productRatePlanCharges'] = charges
1059
- rate_plans[rate_plan['id']] = rate_plan.merge(
1060
- {
1061
- 'productId' => product['id'],
1062
- 'productName' => product['name']
1063
- }
1064
- )
1065
- end
1066
-
1067
- product['productRatePlans'] = rate_plans
1068
- catalog_container[product['id']] = product
1069
- end
1070
- else
1071
- raise "Available objects include [:product]"
1072
- end
1073
- end
1074
-
1075
- Redis.current.hset(CATALOG_LOOKUP_CACHE_RESULT_KEY, self.id, catalog_container.to_json)
1076
- Redis.current.hset(CATALOG_LOOKUP_CACHE_TIME_KEY, self.id, Time.now.to_i)
1077
- end
1078
-
1079
- if object_id.nil?
1080
- catalog_container.transform_values! { |v| v.except('productRatePlans') }
1081
- elsif object_id.is_a?(String)
1082
- catalog_container = catalog_container[object_id]
1083
- end
1084
-
1085
- return catalog_container
1086
- end
1087
-
1088
965
  if defined?(Redis.current) && object_id.present? && object_id.class == String && object_id.present?
1089
966
  stub_catalog = cache ? decrypt_data(data: Redis.current.get("Catalog:#{self.id}:#{object_id}:Children:#{child_objects}")) : nil
1090
967
  object_hierarchy = decrypt_data(data: Redis.current.get("Catalog:#{self.id}:#{object_id}:Hierarchy"))
@@ -2,6 +2,6 @@ module ZuoraConnect
2
2
  class ZuoraUser < ActiveRecord::Base
3
3
  self.table_name = "zuora_users"
4
4
  attr_accessor :session
5
- cattr_accessor :current_user_id
5
+
6
6
  end
7
7
  end
@@ -1,15 +1,9 @@
1
1
  module ActiveRecord
2
2
  module ConnectionAdapters
3
3
  class PostgreSQLAdapter < AbstractAdapter
4
-
5
- SCHEMA_ADDITIONAL_TYPES = 'SchemaAdditionalTypes'.freeze
6
-
7
4
  private
8
- def load_additional_types_latest(oids = nil)
5
+ def load_additional_types(type_map, oids = nil)
9
6
  initializer = OID::TypeMapInitializer.new(type_map)
10
-
11
- return if loaded_from_cache?(initializer)
12
-
13
7
  if supports_ranges?
14
8
  query = <<-SQL
15
9
  SELECT DISTINCT on (t.typname) t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
@@ -30,73 +24,9 @@ module ActiveRecord
30
24
  end
31
25
 
32
26
  execute_and_clear(query, "SCHEMA", []) do |records|
33
- cache_additional_types(records)
34
27
  initializer.run(records)
35
28
  end
36
29
  end
37
-
38
- def load_additional_types_deprecated(type_map, oids = nil)
39
- initializer = OID::TypeMapInitializer.new(type_map)
40
-
41
- return if loaded_from_cache?(initializer)
42
-
43
- if supports_ranges?
44
- query = <<-SQL
45
- SELECT DISTINCT on (t.typname) t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
46
- FROM pg_type as t
47
- LEFT JOIN pg_range as r ON oid = rngtypid
48
- SQL
49
- else
50
- query = <<-SQL
51
- SELECT DISTINCT on (t.typname) t.oid, t.typname, t.typelem, t.typdelim, t.typinput, t.typtype, t.typbasetype
52
- FROM pg_type as t
53
- SQL
54
- end
55
-
56
- if oids
57
- query += "WHERE t.oid::integer IN (%s)" % oids.join(", ")
58
- else
59
- query += initializer.query_conditions_for_initial_load(type_map)
60
- end
61
-
62
- execute_and_clear(query, "SCHEMA", []) do |records|
63
- cache_additional_types(records)
64
- initializer.run(records)
65
- end
66
- end
67
-
68
- def loaded_from_cache?(initializer)
69
- if defined?(Redis.current)
70
- begin
71
- if Redis.current.exists(SCHEMA_ADDITIONAL_TYPES)
72
- initializer.run(JSON.parse(Redis.current.get(SCHEMA_ADDITIONAL_TYPES)))
73
- return true
74
- end
75
- rescue => ex
76
- Rails.logger.warn('Exception occurred while loading additional types', ex)
77
- end
78
- end
79
-
80
- false
81
- end
82
-
83
- def cache_additional_types(records)
84
- if defined?(Redis.current)
85
- begin
86
- Redis.current.setex(SCHEMA_ADDITIONAL_TYPES, 1.hour.to_i, records.to_json)
87
- rescue => ex
88
- Rails.logger.warn('Exception occurred while caching additional types', ex)
89
- end
90
- end
91
- end
92
-
93
-
94
- rails_version = Rails.version.split('.').map { |x| x.to_i }
95
- if (rails_version <=> [5, 2, 0]) >= 1
96
- alias :load_additional_types :load_additional_types_latest
97
- else
98
- alias :load_additional_types :load_additional_types_deprecated
99
- end
100
30
  end
101
31
  end
102
32
  end