After_(read|find) callback?


#1

I am pondering the possibility of encrypting/decrypting some fields
in a SQLite backend on-the-fly.

The point of the message is not security, I know that’s broken, but
whether there’s a technique that provides on-the-fly save/read
filters. Of course the solution would need to work transparently in
joins, so

user.posts.last.title

would do the right thing if title was an encrypted field.

I see in the documentation of ActiveRecord::Callbacks there’s a
before_save callback that looks like going in the right direction,
but I don’t see the symmetric after_(read|find). Any ideas?

– fxn


#2

Why not just write a method that gives you the unencrypted password?

def clear_title
cool_unencryption_algorithm title
end


#3

On Feb 11, 2006, at 12:07, Pat M. wrote:

Why not just write a method that gives you the unencrypted password?

def clear_title
cool_unencryption_algorithm title
end

I would need to write too much code, and violate DRY. Roughly what I
have in mind is:

class RootModelClass < ActiveRecord::Base
  before_save do |obj|
    for all attributes in obj
      if attribute does not end with "id"
        encrypt attribute
      end
    end
  end

  after_read do |obj|
    for all attributes in obj
      if attribute does not end with "id"
        decrypt attribute
      end
    end
  end
end

And then all my models would inherit from RootModelClass.

– fxn


#4

On Feb 11, 2006, at 3:17 AM, Xavier N. wrote:

   for all attributes in obj
     if attribute does not end with "id"
       decrypt attribute
     end
   end
 end

end

And then all my models would inherit from RootModelClass.

Check out Sentry.


– Tom M.


#5

Hi Xavier,

On 11 Feb 2006, at 10:33, Xavier N. wrote:

would do the right thing if title was an encrypted field.

I see in the documentation of ActiveRecord::Callbacks there’s a
before_save callback that looks like going in the right direction,
but I don’t see the symmetric after_(read|find). Any ideas?

There is some code which does exactly what you are after, on pp.
268-270 (277-279 in the PDF) of Agile Development with Rails.

Too much to type out here, but basically you end up with a neat new
addition to ActiveRecord::Base that lets you do this:

class Order < ActiveRecord::Base
encrypt :name, :email
end

The callback methods you need to hook into are before_save,
after_save and after_find.

Jon


#6

On Feb 11, 2006, at 13:56, Jon Evans wrote:

The callback methods you need to hook into are before_save,
after_save and after_find.

Great. I readed the Agile from cover to cover, but had completely
forgottten that example. I’ll probably delegate this stuff to Sentry
(thank you Tom!), but nevertheless I wonder why after_find is not
listed in the left-bottom box of http://api.rubyonrails.org/.

– fxn