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

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top