Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 Qeurying the database encrypted with attr_encrypted gem (where clause on encrypted fields)

I have encrypted a field in the table using the attr_encrypted gem. Now I want to query on that particular field comparing it with a value I am retrieving from a form. How can I do this?

EDIT : I need to query on a number of encrypted fields. Eg: searching on encrypted_email, encrypted_name etc. (using OR condition in where clause)

like image 584
phoenixwizard Avatar asked Jan 16 '12 04:01

phoenixwizard


2 Answers

attr_encrypted intercepts find_by methods, so you should be able to do this:

class User < ActiveRecord::Base
  attr_encrypted :email, :key => 'a secret key'
  attr_encrypted :password, :key => 'some other secret key'
end

User.find_by_email_and_password('[email protected]', 'testing')

This is rewritten as

User.find_by_encrypted_email_and_encrypted_password('ENCRYPTED EMAIL', 'ENCRYPTED PASSWORD')
like image 64
Sergio Tulentsev Avatar answered Sep 28 '22 10:09

Sergio Tulentsev


class User < ActiveRecord::Base 
  attr_encrypted :email, :key => 'a secret key'
end

If you want to write a query to retrieve user whose email is '[email protected]' then you can do either

User.where(encrypted_email: User.encrypt_email('[email protected]'))

or

User.scoped_by_email('[email protected]') # works only for dynamic scope methods
like image 38
vitthal-gaikwad Avatar answered Sep 28 '22 12:09

vitthal-gaikwad