Module: Legion::Data::Encryption::SequelPlugin::ClassMethods

Defined in:
lib/legion/data/encryption/sequel_plugin.rb

Instance Method Summary collapse

Instance Method Details

#encrypted_column(name, key_scope: :default) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/legion/data/encryption/sequel_plugin.rb', line 15

def encrypted_column(name, key_scope: :default)
  col_scope = key_scope
  encrypted_columns[name] = { key_scope: col_scope }

  define_method(name) do
    raw = super()
    return nil if raw.nil?

    provider = self.class.encryption_key_provider
    tenant = col_scope == :tenant ? self[:tenant_id] : nil
    key = provider.key_for(tenant_id: tenant)
    aad = "#{self.class.table_name}:#{pk}:#{name}"
    begin
      Legion::Data::Encryption::Cipher.decrypt(raw.b, key: key, aad: aad)
    rescue StandardError => e
      Legion::Logging.warn "Decrypt failed for #{self.class.table_name}##{pk} column #{name}: #{e.message}" if defined?(Legion::Logging)
      raise
    end
  end

  define_method(:"#{name}=") do |value|
    if value.nil?
      super(nil)
    else
      provider = self.class.encryption_key_provider
      tenant = col_scope == :tenant ? self[:tenant_id] : nil
      key = provider.key_for(tenant_id: tenant)
      aad = "#{self.class.table_name}:#{pk || 0}:#{name}"
      encrypted = Legion::Data::Encryption::Cipher.encrypt(value.to_s, key: key, aad: aad)
      super(Sequel.blob(encrypted))
    end
  end
end

#encrypted_columnsObject



11
12
13
# File 'lib/legion/data/encryption/sequel_plugin.rb', line 11

def encrypted_columns
  @encrypted_columns ||= {}
end

#encryption_key_providerObject



49
50
51
# File 'lib/legion/data/encryption/sequel_plugin.rb', line 49

def encryption_key_provider
  @encryption_key_provider ||= KeyProvider.new
end