Sha256: f408d21e8ffcb1e1d269bf52bf4d1d101f9e92a98b6a3a9d5b631624801a843e

Contents?: true

Size: 1.82 KB

Versions: 5

Compression:

Stored size: 1.82 KB

Contents

# frozen_string_literal: true

require 'active_support/json'
require 'chamber'

module  Chamber
begin
  require 'active_record/type/value'

  CHAMBER_TYPE_VALUE_SUPERCLASS = ActiveRecord::Type::Value
rescue LoadError # rubocop:disable Lint/SuppressedException
end

begin
  require 'active_model/type/value'

  CHAMBER_TYPE_VALUE_SUPERCLASS = ActiveModel::Type::Value
rescue LoadError # rubocop:disable Lint/SuppressedException
end

module  Types
class   Secured < CHAMBER_TYPE_VALUE_SUPERCLASS
  attr_accessor :decryption_keys,
                :encryption_keys

  def initialize(decryption_keys: ::Chamber.configuration.decryption_keys,
                 encryption_keys: ::Chamber.configuration.encryption_keys)
    self.decryption_keys = decryption_keys
    self.encryption_keys = encryption_keys

    super()
  end

  def type
    :jsonb
  end

  def cast(value)
    case value
    when Hash
      value
    when String
      ::JSON.parse(value)
    when NilClass
      nil
    else
      fail ArgumentError, 'Any attributes encrypted with Chamber must be either a Hash or a valid JSON string'
    end
  end
  alias type_cast_from_user cast

  def deserialize(value)
    value = cast(value)

    return if value.nil?

    Chamber.decrypt(value,
                    decryption_keys: decryption_keys,
                    encryption_keys: encryption_keys)
  end
  alias type_cast_from_database deserialize

  def serialize(value)
    fail ArgumentError, 'Any attributes encrypted with Chamber must be a Hash' unless value.is_a?(Hash)

    ::JSON.dump(
      ::Chamber.encrypt(value,
                        decryption_keys: decryption_keys,
                        encryption_keys: encryption_keys),
    )
  end
  alias type_cast_for_database serialize

  def changed_in_place?(raw_old_value, new_value)
    deserialize(raw_old_value) == new_value
  end
end
end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
chamber-3.1.1 lib/chamber/types/secured.rb
chamber-3.1.0 lib/chamber/types/secured.rb
chamber-3.0.1 lib/chamber/types/secured.rb
chamber-3.0.0 lib/chamber/types/secured.rb
chamber-3.0.0rc2 lib/chamber/types/secured.rb