Persistent session data in Rails without affecting the expiration of a regular session

I would like to keep some permanent data for each browser (user settings) and do not want to require a login to use the site. What is the way to achieve this?

I reviewed two approaches:

  • Store the information in a session cookie. The problem with this approach is that I will need to set the expiration time in the session cookie, which has the side effect that the user login session does not expire when the browser closes.
  • Store the information in the database and save the search key in a cookie on the client side. I am concerned about performance issues, as this will require additional queries and possibly some deserialization to retrieve the data. It seems that Rails disconnected from ActiveRecordStore by default due to performance reasons: http://ryandaigle.com/articles/2007/2/21/what-s-new-in-edge-rails-cookie-based-sessions

What is the recommended way to achieve this?

+3
source share
2 answers

Why not just use a session cookie? You can specify how long it will remain on the client, etc. See http://api.rubyonrails.org/classes/ActionController/Cookies.html

, cookie, cookie ( http://www.neeraj.name/blog/articles/834-how-cookie-stores-session-data-in-rails):

cookie_data = {:foo => "bar"}
digest = 'SHA1'
secret = 'my_encryption_secret'
data = ActiveSupport::Base64.encode64s(Marshal.dump(cookie_data))
digest_value = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(digest), secret, data)
escaped_data_value = Rack::Utils.escape(data)
final_output = "#{escaped_data_value}--#{digest_value}"
cookies[:user_data] = final_output

cookie:

Marshal.load(ActiveSupport::Base64.decode64(cookies[:user_data]))
0

cookie, ActiveRecord. , , , ActiveRecord - , . cookie , - -, . ActiveRecord - , , cookie, , ( ActiveRecord , session_id), .

, ActiveRecord . cookie , , , , , , , . , , , . , , , , , , db , .

cookie , , , , . , cookie , cookie, cookie db.

@joshsz cookie . , .

0

Source: https://habr.com/ru/post/1732711/


All Articles