mongo_session_store
mongo_session_store copied to clipboard
Added support for running custom code before save session
A nice feature missing is to customize the Session class, adding attributes, indexes and another stuff useful to the application.
To do this you can simply add code to the class Session inside ActionDispatch::Session::MongoidStore (or the others stores available). But inside this class you can use almost nothing of your app, like the environment or the session data (before it's converted to binary).
A simple solution is in this pull request: Add a call to a method called "before_save_session" passing the major variables availables: "env", "sid", "session_data" and "options". This method is suposed to be implemented by the application using this gem.
Now you can do this (if you're using warden) to save the user_id in the session:
module ActionDispatch
module Session
class MongoidStore < MongoStoreBase
class Session
field :user_id, :type => Moped::BSON::ObjectId
index({ user_id: 1 })
def before_save_session(env, sid, session_data, options)
puts "before_save_session"
if !self.user_id && env['warden'] && env['warden'].user
self.user_id = env['warden'].user._id
end
end
end
end
end
end
With the user_id in the session (in database) you can do fun things like remove all sessions from a specific user.
Cheers
Why would you do it here rather than at the controller level?
The rails model callbacks aren't supposed to be in the model?
I think it would be neat to mess with one and only one file to do this kind of change. In this case it will be one file called mongoid_store.rb that could be saved in the lib folder, or in the config/initializers folder, because it's necessary to add one attribute and one index at the Session model. Something like occurs in the ActiveRecord Store. The difference is that we need the enviroment stuff in this "distant" model that cannot access anything useful.
But I'll be glad to hear another solution in the controller level.
Thanks for the reply and for keeping this repo.