Created
July 27, 2020 20:10
-
-
Save trobrock/b3304b8552cb04f842f0b85d85266806 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module EncryptedAttribute | |
extend ActiveSupport::Concern | |
class_methods do | |
def attr_encrypted(attr) | |
define_method(attr) do | |
value = instance_variable_get("@#{attr}") | |
return value if value | |
instance_variable_set "@#{attr}", | |
encryptor.decrypt_and_verify(public_send("encrypted_#{attr}".to_sym)) | |
end | |
define_method("#{attr}=") do |new_value| | |
value = encryptor.encrypt_and_sign(new_value) | |
instance_variable_set("@#{attr}", new_value) | |
public_send("encrypted_#{attr}=", value) | |
end | |
end | |
end | |
private | |
def encryptor | |
@encryptor = ActiveSupport::MessageEncryptor.new(encryptor_key) | |
end | |
def encryptor_key | |
ENV['RAILS_MASTER_KEY'] || File.read(Rails.application.config.credentials.key_path) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment