Change session store in Rails without logging users out
We just switched to cookie store from a Redis session store, and wanted to make sure no one got logged out in the process. This method should be easy to modify for any session store transition.
1) Change the cookie name
For me, the cookie name was specified in config/initializers/session_store.rb
Simply replace _old_cookie_name with a new name for the cookie. Not changing the cookie name when you switch session stores will result in exceptions being thrown when you access the session object. You could catch those exceptions and deal with that, but I think it is easier to change the name.
2) Change the session store
The cookie store has been the Rails default for a while now, so I just removed the line we had setting ActionController::Base.session_store.
3) Add code to migrate users from the old session store to the new one
I have an authenticate method that is a before filter set in my application controller. Everyone will hit this method, so it is an easy place to stick this code. You will want to modify this code for your situation and place it somewhere where it will be run for anyone accessing your site.
This checks if the old cookie exists for the user, and if there is a value in Redis. It then fetches the session contents from Redis and copies everything into the users new session. It finishes by deleting the old cookie to keep this code from running multiple times for a user and potentially overwriting newer session data. I also have it increment a key in Redis so I can appease my curiosity and see that all of the users currently browsing Ride with GPS have been migrated over to their new cookie-based session.
Modifying this code should be straightforward. Instead of pulling the session content out of Redis, you can pull it out of your database if you were using an ActiveRecord store, or out of Memcache, etc.
4) Optional: Cleanup
Once you are happy with the number of users that have been migrated to the new session store, you can remove the session-migrating code from your application and delete the old sessions from your prior session store.
If you have any questions, feel free to comment or contact me at zackham@gmail.com


Comments 2 Comments