Module: CipherAble

Extended by:
ActiveSupport::Concern
Defined in:
lib/app/models/concerns/cipher_able.rb

Overview

A mixin to help with encrypting data in a secure way

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Add to the model



7
8
9
10
11
12
13
14
# File 'lib/app/models/concerns/cipher_able.rb', line 7

def self.included(base)
  base.class_eval do
    #
    # Fields
    #
    field :secret_key, type: BSON::Binary
  end
end

Instance Method Details

#cipherObject

Get the cipher directly



39
40
41
42
# File 'lib/app/models/concerns/cipher_able.rb', line 39

def cipher
  generate_key if secret_key.blank?
  ActiveSupport::MessageEncryptor.new(secret_key.data)
end

#decrypt(text) ⇒ Object

Decrypt the given text



29
30
31
32
33
34
# File 'lib/app/models/concerns/cipher_able.rb', line 29

def decrypt(text)
  cipher.decrypt_and_verify(text)
rescue StandardError => error
  App47Logger.log_warn("Unable to decrypt text for #{inspect}", error)
  nil
end

#encrypt(text) ⇒ Object

Encrypt the given text



19
20
21
22
23
24
# File 'lib/app/models/concerns/cipher_able.rb', line 19

def encrypt(text)
  cipher.encrypt_and_sign(text)
rescue StandardError => error
  App47Logger.log_error("Unable to encrypt text for #{inspect}", error)
  nil
end