2

I want to install the following gem https://github.com/attr-encrypted/attr_encrypted to encrypt some fields of the existing models I have. For example, a User model with first_name, last_name, etc. My app is already deployed, so I don't want to make any stupid mistakes.

I understood how to process is with a new model through this link (https://qiita.com/alokrawat050/items/ff6dceec32baa0c8fa57), but how should I process with an existing db et models?

I was thinking about doing the following steps:

  1. Install the gem.
  2. Adding the following lines in my model:

    class User < ActiveRecord::Base
      secret_key = ENV['DB_COL_ENCRYPTED_KEY']
      attr_encrypted :first_name, :key => secret_key
      attr_encrypted :last_name, :key => secret_key
      [...]
    end
    
  3. Create a new migration:

    rails g migration AddEncryptedColumnsToUser encrypted_first_name:string encrypted_last_name:string encrypted_first_name_iv:string encrypted_last_name_iv:string 
    
  4. rake db:migrate


(Edited)

Following the above steps, when I look at the db in the console, I still have the first_name and last_name fields:

<User id: 2, first_name: "John", last_name: "Doe", 
encrypted_first_name: nil, encrypted_last_name: nil, 
encrypted_first_name_iv: nil, encrypted_last_name_iv: nil>

If I do:

User.update first_name: "John", last_name: "Doe"

It encrypts it correctly.

Next step is to remove the columns with first_name and last_name:

rails generate migration RemoveNonEncryptedDateFromUser first_name:string last_name:string

Is there a way to copy the non-encrypted fields first_name and last_name from the model and encrypt them directly, or do I have to do it manually for all of them?

Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
Djodjo
  • 95
  • 10
  • 2
    I've never used this before, but you might just be able to `User.all.each(&:save)` inside of a migration. – Josh Brody Jul 24 '18 at 19:35
  • 1
    @JoshBrody use `User.find_each(&:save)` - loading every record will exhaust the memory given a non-trivial amount of records. https://api.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-find_each – max Jul 24 '18 at 20:16
  • @max it could also screw up his callbacks. What if he posts to an external API after each save? Maybe he sends an email after each save in the foreground, what then? There are a million other things that could bottleneck his app. My response implied that he should merely be able to merely save the record and the rest will take care of itself. While educating is nice, if we all nit-pick we'll be here all day. – Josh Brody Jul 24 '18 at 21:29
  • Thanks for your replies. Are my steps correct at least? – Djodjo Jul 28 '18 at 15:28

0 Answers0