Class: MultiSession::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/multi_session/session.rb

Instance Method Summary collapse

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
  @cookies = 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).decrypt_and_verify(@cookies[key])
  session['value'] # TODO: add ability to let developer retrieve the session_id
end

#[]=(key, value) ⇒ Object

Raises:

  • (ActionDispatch::Cookies::CookieOverflow)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 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
  }
  expiry_options = MultiSession.expires.present? ? {expires_at: Time.now + MultiSession.expires} : {}
  encrypted_and_signed_value = encryptor(key).encrypt_and_sign ActiveSupport::JSON.encode(new_session), expiry_options

  raise ActionDispatch::Cookies::CookieOverflow if encrypted_and_signed_value.bytesize > ActionDispatch::Cookies::MAX_COOKIE_SIZE

  @cookies[key.to_s] = {value: encrypted_and_signed_value}.merge(MultiSession.expires.present? ? {expires: MultiSession.expires} : {})
  nil
end

#clearObject



34
35
36
# File 'lib/multi_session/session.rb', line 34

def clear
  @cookies.clear
end

#update_expirationObject



38
39
40
41
42
# File 'lib/multi_session/session.rb', line 38

def update_expiration
  Rails.application.credentials[:multi_session_keys].each_key do |key|
    self[key] = self[key] # decrypt and re-encrypt to force expires_at to update
  end
end