Currently our Rails application has a session cookie saved at as a www. level cookie. (ie www.example.com), as we are now using multiple subdomains I'm trying to find a way to essentially copy the www.example.com cookie and save the data from it in *.example.com
I'm ideally looking for a solution that requires no additional action from the user (such as forcing everyone to log out and log back in again)
We're using Ruby 2.7.4 and Rails 5.2.6
CodePudding user response:
One way would be to have a transition period:
Period A (now):
Always read and write a cookie on www.
Period B (now):
If the user doesn't have the *.
cookie, read the www.
and write in a cookie *.
, delete the www.
one.
Period C (after):
You're reading and writing a cookie on *.exemple.com
CodePudding user response:
A simple before_action
copying all values should work:
# in app/controllers/application_controller.rb
before_action :copy_cookie_values_to_root_domain
private
def copy_cookie_values_to_root_domain
cookies.each do |(key, value)|
cookies[key] = { value: value, domain: :all }
end
end
Internally the cookie is prepared and processed on each request anyway. Therefore I would not optimize this method any further. Please keep in mind that you need to have a similar block for signed
cookies too then you use them. See docs for Cookies in Rails.