2

I'm using Rails 4 and would like to add more data to the Session that Devise/Warden creates when logging in.

The user_id is stored in ["warden.user.user.key"], but i'd like to add the user's email and username as well.

This is related, but the opposite of what I'd like to do: How to access session from Warden/Devise after_authentication callback in Rails

Community
  • 1
  • 1
jsurf
  • 575
  • 1
  • 8
  • 20

2 Answers2

4

I figured it out by adding this to my config/initializers/devise.rb file. Not sure if this is safe or the right way to go about it, but it works.

Warden::Manager.after_authentication do |user,auth,opts|
  auth.raw_session['warden.user.user.email'] = user.email
  auth.raw_session['warden.user.user.username'] = user.username
end
jsurf
  • 575
  • 1
  • 8
  • 20
3

Typically you would use the Warden serializer for this, as I mention in my Warden guide:

config.middleware.use Warden::Manager do |manager|
  manager.default_strategies :password

  manager.serialize_into_session do |user|
    user.id
  end

  manager.serialize_from_session do |id|
    User.find(id)
  end
end

Then when you want to get the user's information:

env['warden'].user.email
env['warden'].user.username

This also enables you to get more information, or to act on the object if you wanted to.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • First of all thanks for your reply Ryan! I'm not sure this will work for my purposes though. I am decrypting the session created in one rails application (lets call it app1), in a subdomain on another, app2. After decrypting app1's cookies["_app1_session"] I see that it only contains Warden's serialized user_id info. I followed this guide here to decrypt the session:http://big-elephants.com/2014-01/handling-rails-4-sessions-with-go/. I am referring to the application session, not the Devise session, sorry for the confusion. My answer above works but does it smell? – jsurf May 16 '14 at 01:53