Sha256: e7ec50f9a95a705ccefd1e25a0440555c59f4367ed811d625b60e69a6766e638

Contents?: true

Size: 1.37 KB

Versions: 7

Compression:

Stored size: 1.37 KB

Contents

require 'slosilo/symmetric'

module Slosilo
  # we don't trust the database to keep all backups safe from the prying eyes
  # so we encrypt sensitive attributes before storing them
  module EncryptedAttributes
    module ClassMethods
      def attr_encrypted *a
        # push a module onto the inheritance hierarchy
        # this allows calling super in classes
        include(accessors = Module.new)
        accessors.module_eval do 
          a.each do |attr|
            define_method "#{attr}=" do |value|
              super(EncryptedAttributes.encrypt value)
            end
            define_method attr do
              EncryptedAttributes.decrypt(super())
            end
          end
        end
      end
    end
    
    def self.included base
      base.extend ClassMethods
    end

    class << self
      def encrypt value
        return nil unless value
        cipher.encrypt value, key: key
      end
      
      def decrypt ctxt
        return nil unless ctxt
        cipher.decrypt ctxt, key: key
      end

      def key
        Slosilo::encryption_key || (raise "Please set Slosilo::encryption_key")
      end
      
      def cipher
        @cipher ||= Slosilo::Symmetric.new
      end
    end
  end
  
  class << self
    attr_writer :encryption_key
    
    def encryption_key
      @encryption_key
    end
  end
end

Object.send :include, Slosilo::EncryptedAttributes

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
slosilo-1.1.0 lib/slosilo/attr_encrypted.rb
slosilo-1.0.0 lib/slosilo/attr_encrypted.rb
slosilo-0.4.1 lib/slosilo/attr_encrypted.rb
slosilo-0.4.0 lib/slosilo/attr_encrypted.rb
slosilo-0.2.4 lib/slosilo/attr_encrypted.rb
slosilo-0.2.3 lib/slosilo/attr_encrypted.rb
slosilo-0.2.2 lib/slosilo/attr_encrypted.rb