1

I'm using Devise with token Authentication and, now, I want to encrypt the token in the Database. Can anyone give me a hint where devise does the storing/retrieving of the token from the DB?

I'm also using the attr_encrypted gem with which the whole encryption should be rather easy once the right location is found.

Edit:

I have implemented token authentication like it is described here: http://zyphdesignco.com/blog/simple-auth-token-example-with-devise

I added the following line in the user model, which should encrypt the authentication_token

attr_encrypted :authentication_token, :key => 'a secret key', :attribute => 'authentication_token'

When I run it and try to login, I get following error message:

Completed 500 Internal Server Error in 364ms

SystemStackError - stack level too deep:
(gem) actionpack-3.2.13/lib/action_dispatch/middleware/reloader.rb:70:in `'

It seems there is a conflict with devise and attr_encrypted and that both are fighting over redefinition of the authentication_token method (thx for the hint @sbfaulkner)

Maybe someone had a similar problem and knows a solution?

chris h.
  • 265
  • 1
  • 4
  • 18

2 Answers2

0

The important bits about the Token Authenticable strategy are in the Devise::Models:: TokenAuthenticatable module - it works with a set of simple methods:

  • The find_for_token_authentication is used to authenticate the resource
  • ensure_authentication_token/ensure_authentication_token! should be used to generate a token for a fresh resource - Devise won't call it by itself.

If the attr_encrypted gem is compatible with AR models then I believe that you won't have any problems with Devise, but the best way to be sure of that is to trying it out.

Lucas
  • 1,190
  • 8
  • 13
  • Thanks Lucas! I tried to implement a solution, but i run into some trouble. Maybe someone can give me a hint. I created **/config/initializers/token_authenticable.rb** with the original content and then I tried to add the line **attr_encrypted :authentication_token, :key => 'a secret encryption key', :attribute => 'authentication_token'** The error I get when starting the rails server is **/config/initializers/token_authenticatable.rb:44:in `': undefined method `attr_encrypted' for Devise::Models::TokenA uthenticatable:Module (NoMethodError)**. I'm stuck here. – chris h. Apr 03 '13 at 12:28
0

Here is how I did it, on my User model:

before_save :ensure_authentication_token

attr_encrypted :authentication_token, :key => 'my key'

def ensure_authentication_token
  if authentication_token.blank?
    self.authentication_token = generate_authentication_token
  end
end

private

def generate_authentication_token
  loop do
    token = User.encrypt_authentication_token(Devise.friendly_token)
    break token unless User.where(encrypted_authentication_token: token).first
  end
end

The secret is in this method: encrypt_authentication_token that attr_encrypted creates.

Cassio Cabral
  • 2,652
  • 3
  • 23
  • 37