Module: AttrKeyring::ActiveRecord::ClassMethods
- Defined in:
- lib/attr_keyring/active_record.rb
Instance Method Summary collapse
- #attr_encrypt(*attributes, encode: true) ⇒ Object
- #attr_keyring(keyring, encryptor: Encryptor::AES128CBC) ⇒ Object
- #define_attr_encrypt_reader(attribute) ⇒ Object
- #define_attr_encrypt_writer(attribute) ⇒ Object
Instance Method Details
#attr_encrypt(*attributes, encode: true) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/attr_keyring/active_record.rb', line 8 def attr_encrypt(*attributes, encode: true) self.keyring_attrs ||= {} attributes.each do |attribute| keyring_attrs[attribute.to_sym] = {encode: encode} end attributes.each do |attribute| define_attr_encrypt_writer(attribute) define_attr_encrypt_reader(attribute) end end |
#attr_keyring(keyring, encryptor: Encryptor::AES128CBC) ⇒ Object
4 5 6 |
# File 'lib/attr_keyring/active_record.rb', line 4 def attr_keyring(keyring, encryptor: Encryptor::AES128CBC) self.keyring = Keyring.new(keyring, encryptor) end |
#define_attr_encrypt_reader(attribute) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/attr_keyring/active_record.rb', line 37 def define_attr_encrypt_reader(attribute) define_method(attribute) do encrypted_value = public_send("encrypted_#{attribute}") return unless encrypted_value = self.class.keyring_attrs.fetch(attribute) encrypted_value = Base64.strict_decode64(encrypted_value) if [:encode] keyring_id = public_send(keyring_column_name) value = self.class.keyring.decrypt(encrypted_value, keyring_id) value end end |
#define_attr_encrypt_writer(attribute) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/attr_keyring/active_record.rb', line 21 def define_attr_encrypt_writer(attribute) define_method("#{attribute}=") do |value| return attr_reset_column(attribute) if value.nil? = self.class.keyring_attrs.fetch(attribute) stored_keyring_id = public_send(keyring_column_name) keyring_id = stored_keyring_id || self.class.keyring.current_key&.id encrypted_value = self.class.keyring.encrypt(value, keyring_id) encrypted_value = Base64.strict_encode64(encrypted_value) if [:encode] public_send("#{keyring_column_name}=", keyring_id) unless stored_keyring_id public_send("encrypted_#{attribute}=", encrypted_value) attr_encrypt_digest(attribute, value) end end |