Class: Rage::SidekiqSession

Inherits:
Object
  • Object
show all
Defined in:
lib/rage/sidekiq_session.rb

Overview

Used specifically for compatibility with Sidekiq's Web interface. Remove once we have real sessions or once Sidekiq's author decides they don't need cookie sessions to protect against CSRF.

Constant Summary collapse

KEY =
Digest::SHA2.hexdigest(ENV["SECRET_KEY_BASE"] || File.read("Gemfile.lock") + File.read("config/routes.rb"))
SESSION_KEY =
"rage.sidekiq.session"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ SidekiqSession

Returns a new instance of SidekiqSession.



32
33
34
35
36
# File 'lib/rage/sidekiq_session.rb', line 32

def initialize(env)
  @env = env
  session = Rack::Utils.parse_cookies(@env)[SESSION_KEY]
  @data = decode_session(session)
end

Instance Attribute Details

#changedObject (readonly)

Returns the value of attribute changed.



30
31
32
# File 'lib/rage/sidekiq_session.rb', line 30

def changed
  @changed
end

Class Method Details

.with_session(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rage/sidekiq_session.rb', line 15

def self.with_session(env)
  env["rack.session"] = session = new(env)
  response = yield

  if session.changed
    Rack::Utils.set_cookie_header!(
      response[1],
      SESSION_KEY,
      { path: env["SCRIPT_NAME"], httponly: true, same_site: true, value: session.dump }
    )
  end

  response
end

Instance Method Details

#[](key) ⇒ Object



38
39
40
# File 'lib/rage/sidekiq_session.rb', line 38

def [](key)
  @data[key]
end

#[]=(key, value) ⇒ Object



42
43
44
45
# File 'lib/rage/sidekiq_session.rb', line 42

def[]=(key, value)
  @changed = true
  @data[key] = value
end

#dumpObject



51
52
53
54
55
56
# File 'lib/rage/sidekiq_session.rb', line 51

def dump
  encoded_data = Marshal.dump(@data)
  signature = OpenSSL::HMAC.hexdigest("SHA256", KEY, encoded_data)

  Base64.urlsafe_encode64("#{encoded_data}--#{signature}")
end

#to_hashObject



47
48
49
# File 'lib/rage/sidekiq_session.rb', line 47

def to_hash
  @data
end