debian-mirror-gitlab/app/models/concerns/sensitive_serializable_hash.rb

38 lines
1.3 KiB
Ruby
Raw Normal View History

2022-05-07 20:08:51 +05:30
# frozen_string_literal: true
module SensitiveSerializableHash
extend ActiveSupport::Concern
included do
class_attribute :attributes_exempt_from_serializable_hash, default: []
end
class_methods do
def prevent_from_serialization(*keys)
self.attributes_exempt_from_serializable_hash ||= []
2022-07-23 23:45:48 +05:30
self.attributes_exempt_from_serializable_hash += keys
2022-05-07 20:08:51 +05:30
end
end
# Override serializable_hash to exclude sensitive attributes by default
#
# In general, prefer NOT to use serializable_hash / to_json / as_json in favor
# of serializers / entities instead which has an allowlist of attributes
def serializable_hash(options = nil)
options = options.try(:dup) || {}
options[:except] = Array(options[:except]).dup
options[:except].concat self.class.attributes_exempt_from_serializable_hash
2023-04-23 21:23:45 +05:30
if self.class.respond_to?(:attr_encrypted_attributes)
options[:except].concat self.class.attr_encrypted_attributes.keys
2022-05-07 20:08:51 +05:30
# Per https://github.com/attr-encrypted/attr_encrypted/blob/a96693e9a2a25f4f910bf915e29b0f364f277032/lib/attr_encrypted.rb#L413
2023-04-23 21:23:45 +05:30
options[:except].concat self.class.attr_encrypted_attributes.values.map { |v| v[:attribute] }
options[:except].concat self.class.attr_encrypted_attributes.values.map { |v| "#{v[:attribute]}_iv" }
2022-05-07 20:08:51 +05:30
end
super(options)
end
end