Class: MultiSession::Session
- Inherits:
-
Object
- Object
- MultiSession::Session
- Defined in:
- lib/multi_session/session.rb
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #clear ⇒ Object
-
#initialize(cookies) ⇒ Session
constructor
A new instance of Session.
- #update_expiration ⇒ Object
Constructor Details
#initialize(cookies) ⇒ Session
Returns a new instance of Session.
3 4 5 |
# File 'lib/multi_session/session.rb', line 3 def initialize @cookies = end |
Instance Method Details
#[](key) ⇒ Object
7 8 9 10 11 |
# File 'lib/multi_session/session.rb', line 7 def [] key return nil unless @cookies[key.to_s].present? session = ActiveSupport::JSON.decode encryptor(key.to_s).decrypt_and_verify(@cookies[key.to_s]) session['value'] # TODO: add ability to let developer retrieve the session_id end |
#[]=(key, value) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/multi_session/session.rb', line 13 def []= key, value previous_session = self[key] session_id = if previous_session && previous_session['session_id'].present? previous_session['session_id'] else SecureRandom.hex(16).encode Encoding::UTF_8 end new_session = {'session_id' => session_id, 'value' => value} enc = encryptor key.to_s if enc.method(:encrypt_and_sign).arity > 1 # check number of arguments for encrypt_and_sign (more than 1 means we're in Rails 5.2+ and can have expirable messages) = MultiSession.expires.present? ? {expires_at: Time.now + MultiSession.expires} : {} encrypted_and_signed_value = enc.encrypt_and_sign ActiveSupport::JSON.encode(new_session), else encrypted_and_signed_value = enc.encrypt_and_sign ActiveSupport::JSON.encode(new_session) end raise ActionDispatch::Cookies::CookieOverflow if encrypted_and_signed_value.bytesize > ActionDispatch::Cookies::MAX_COOKIE_SIZE = { value: encrypted_and_signed_value } .merge!({ expires: MultiSession.expires}) if MultiSession.expires.present? .merge!({ domain: MultiSession.domain }) if MultiSession.domain.present? @cookies[key.to_s] = nil end |
#clear ⇒ Object
38 39 40 |
# File 'lib/multi_session/session.rb', line 38 def clear @cookies.clear end |
#update_expiration ⇒ Object
42 43 44 45 46 |
# File 'lib/multi_session/session.rb', line 42 def update_expiration multi_session_keys.each_key do |key| self[key] = self[key] # decrypt and re-encrypt to force expires_at to update end end |