Skip to content

Instantly share code, notes, and snippets.

@iannono
Created November 1, 2014 08:58
Show Gist options
  • Save iannono/42eef5f376af960b737d to your computer and use it in GitHub Desktop.
Save iannono/42eef5f376af960b737d to your computer and use it in GitHub Desktop.
type:== rails
before_save :encrypt_note
def encrypt_note
salt = SecureRandom.random_bytes(64)
key = encrypt_key || ActiveSupport::KeyGenerator.new(ENV["SECRET_KEY"]).generate_key(salt)
crypt = ActiveSupport::MessageEncryptor.new(key)
%w(client_note food medicines hydration md_appointments activity mood positive_thinking positive_action listener_note).each_with_index do |att|
val = if !new_record? and send("#{att}_changed?")
read_attribute(att.to_sym)
else
send(att) || ""
end
send("#{att}=", crypt.encrypt_and_sign(val))
end
byebug
self.encrypt_key = key
end
%w(client_note food medicines hydration md_appointments activity mood positive_thinking positive_action listener_note).each do |attr|
define_method(attr) do
if is_encrypt?(attr)
crypt = ActiveSupport::MessageEncryptor.new(encrypt_key)
crypt.decrypt_and_verify(read_attribute(attr.to_sym))
else
read_attribute(attr.to_sym)
end
end
end
def is_encrypt?(attr)
if encrypt_key.present?
crypt = ActiveSupport::MessageEncryptor.new(encrypt_key)
crypt.decrypt_and_verify(read_attribute(attr.to_sym))
return true
else
return false
end
rescue ActiveSupport::MessageVerifier::InvalidSignature
false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment