Class: Rack::Session::File

Inherits:
Abstract::Persisted
  • Object
show all
Defined in:
lib/rack/session/file.rb

Overview

Rack::Session::File provides simple filed based session management. By default, the session is stored in /tmp while cookie holds only session id.

When the :secret key is set (recommended), cookie data is checked for data integrity. The :old_secret key is also accepted allowing smooth secret rotation.

Garbage collection is controlled via :gc_probability and :gc_maxlife. Every call to write_session, garbage collector is called with probability of :gc_probability. It scans :dir for sessions files and deletes ones with mtime older than :gc_maxlife.

Supported options for constructor are:

:dir            directory into which save sessions
:prefix         session file prefix
:key            under what cookie save the session_id
:domain         domain should the session_id cookie is valid for
:path           path the session_id cookie is valid for
:expire_after   session_id cookie expires after this seconds
:secret         secret to use for integrity check
:old_secret     secret previously used, allowing smooth secret rotation

:gc_probability probability of gc to run, in interval [0; 1]
:gc_maxlife     how old (in seconds) session files should be cleaned up

Default values:

:dir            File.join(Dir.tmpdir(), 'file-rack')
:prefix         'file-rack-session-'
:key            rack.session
:domain         nil
:path           nil
:expire_after   nil
:secret         nil
:old_secret     nil
:gc_probability 0.01
:gc_maxlife     1200

Example:

use Rack::Session::File, dir: '/tmp',
                         prefix: 'session-',

All parameters are optional.

Constant Summary collapse

SESSION_ID =
'session_id'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ File

Returns a new instance of File.



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/rack/session/file.rb', line 62

def initialize(app, options = {})
  @secrets = options.values_at(:secret, :old_secret).compact
  @hmac = options.fetch(:hmac, OpenSSL::Digest::SHA1)

  @dir = options[:dir] || ::File.join(Dir.tmpdir(), 'file-rack')
  @prefix = options[:prefix] || 'file-rack-session-'
  FileUtils.mkdir_p @dir

  @gc_probability = options[:gc_probability] || 0.01
  @gc_maxlife = options[:gc_maxlife] || 1200

  warn <<~MSG unless secure?(options)
    SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
    This poses a security threat. It is strongly recommended that you
    provide a secret to prevent exploits that may be possible from crafted
    cookies. This will not be supported in future versions of Rack, and
    future versions will even invalidate your existing user cookies.

    Called from: #{caller[0]}.
  MSG

  super(app, options.merge!(cookie_only: false))
end