Sha256: b7aeb1e7345a44ab5c838b3968356a586a0c34ea32a217567f675789ae3029cb

Contents?: true

Size: 982 Bytes

Versions: 2

Compression:

Stored size: 982 Bytes

Contents

module Vidibus
  module Secure
    module Mongoid
      extend ActiveSupport::Concern
      module ClassMethods

        # Sets encrypted attributes.
        def attr_encrypted(*args)
          key = ENV["VIDIBUS_SECURE_KEY"]
          options = args.extract_options!
          for field in args

            # Define Mongoid field
            encrypted_field = "#{field}_encrypted"
            self.send(:field, encrypted_field, type: BSON::Binary)

            # Define setter
            class_eval <<-EOV
              def #{field}=(value)
                self.#{encrypted_field} = value ?
                  Vidibus::Secure.encrypt(value, "#{key}") :
                  nil
              end
            EOV

            # Define getter
            class_eval <<-EOV
              def #{field}
                Vidibus::Secure.decrypt(#{encrypted_field}.data, "#{key}") if #{encrypted_field}
              end
            EOV
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
vidibus-secure-4.0.1 lib/vidibus/secure/mongoid.rb
vidibus-secure-4.0.0 lib/vidibus/secure/mongoid.rb