Module: Vidibus::Secure::Mongoid::ClassMethods
- Defined in:
- lib/vidibus/secure/mongoid.rb
Instance Method Summary collapse
-
#attr_encrypted(*args) ⇒ Object
Defines encrypted attributes.
Instance Method Details
#attr_encrypted(*args) ⇒ Object
Defines encrypted attributes. The encryption key is resolved on every read and write via Vidibus::Secure.current_key, so callers can swap keys per request (e.g. tenant-scoped DB context).
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/vidibus/secure/mongoid.rb', line 12 def attr_encrypted(*args) args. args.each do |attr| encrypted_field = "#{attr}_encrypted" field encrypted_field, type: BSON::Binary define_method("#{attr}=") do |value| if value.nil? self[encrypted_field] = nil else blob = Vidibus::Secure.encrypt( value, Vidibus::Secure.current_key ) self[encrypted_field] = BSON::Binary.new(blob) end end define_method(attr) do raw = self[encrypted_field] return nil unless raw data = raw.respond_to?(:data) ? raw.data : raw Vidibus::Secure.decrypt(data, Vidibus::Secure.current_key) end end end |