Commit 48d4c8e8 authored by Thong Kuah's avatar Thong Kuah

Provides a class level utility to prevent fields from serializable_hash

This allows us to exclude fields manually from serializable_hash /
to_json / as_json
parent 5d26f377
...@@ -3,6 +3,17 @@ ...@@ -3,6 +3,17 @@
module SensitiveSerializableHash module SensitiveSerializableHash
extend ActiveSupport::Concern 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 ||= []
self.attributes_exempt_from_serializable_hash.concat keys
end
end
# Override serializable_hash to exclude sensitive attributes by default # Override serializable_hash to exclude sensitive attributes by default
# #
# In general, prefer NOT to use serializable_hash / to_json / as_json in favor # In general, prefer NOT to use serializable_hash / to_json / as_json in favor
...@@ -13,6 +24,8 @@ module SensitiveSerializableHash ...@@ -13,6 +24,8 @@ module SensitiveSerializableHash
options = options.try(:dup) || {} options = options.try(:dup) || {}
options[:except] = Array(options[:except]).dup options[:except] = Array(options[:except]).dup
options[:except].concat self.class.attributes_exempt_from_serializable_hash
if self.class.respond_to?(:token_authenticatable_fields) if self.class.respond_to?(:token_authenticatable_fields)
options[:except].concat self.class.token_authenticatable_fields options[:except].concat self.class.token_authenticatable_fields
......
...@@ -3,6 +3,37 @@ ...@@ -3,6 +3,37 @@
require 'spec_helper' require 'spec_helper'
RSpec.describe SensitiveSerializableHash do RSpec.describe SensitiveSerializableHash do
describe '.prevent_from_serialization' do
let(:test_class) do
Class.new do
include ActiveModel::Serialization
include SensitiveSerializableHash
attr_accessor :name, :super_secret
prevent_from_serialization :super_secret
def attributes
{ 'name' => nil, 'super_secret' => nil }
end
end
end
it 'does not include the field in serializable_hash' do
model = test_class.new
expect(model.serializable_hash).not_to include('super_secret')
end
context 'unsafe_serialization_hash option' do
it 'includes the field in serializable_hash' do
model = test_class.new
expect(model.serializable_hash(unsafe_serialization_hash: true)).to include('super_secret')
end
end
end
describe '#serializable_hash' do describe '#serializable_hash' do
shared_examples "attr_encrypted attribute" do |klass, attribute_name| shared_examples "attr_encrypted attribute" do |klass, attribute_name|
context "#{klass.name}\##{attribute_name}" do context "#{klass.name}\##{attribute_name}" do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment