Class: LimitedSessions::Expiry

Inherits:
Object
  • Object
show all
Defined in:
lib/limited_sessions/expiry.rb

Overview

Rack middleware that should be installed after the session handling middleware

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :recent_activity => nil,  # eg: 2.hours
  :max_session => nil       # eg: 24.hours
}

Instance Method Summary collapse

Constructor Details

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



16
17
18
19
# File 'lib/limited_sessions/expiry.rb', line 16

def initialize(app, options={})
  @app = app
  @options = DEFAULT_OPTIONS.merge(options)
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/limited_sessions/expiry.rb', line 21

def call(env)
  @env = env
  if @options[:recent_activity]
    if session[:last_visit] && (session[:last_visit] + @options[:recent_activity]) < Time.now.to_i
      logger.info "Session expired: no recent activity"
      clear_session
    end
    if @options[:recent_activity] > 600
      # Rounds to the nearest 5 minutes to minimize writes when a DB is in use
      session[:last_visit] = (Time.now.to_f/300).ceil*300
    else
      session[:last_visit] = (Time.now.to_f/10).ceil*10
    end
  end
  if @options[:max_session]
    session[:first_visit] ||= Time.now.to_i
    if (session[:first_visit] + @options[:max_session]) < Time.now.to_i
      logger.info "Session expired: max session length reached"
      clear_session
      session[:first_visit] ||= Time.now.to_i
    end
  end
  @app.call(env)
end

#clear_sessionObject



49
50
51
# File 'lib/limited_sessions/expiry.rb', line 49

def clear_session
  @env['rack.session'].clear
end

#loggerObject



52
53
54
# File 'lib/limited_sessions/expiry.rb', line 52

def logger
  (Rails.logger rescue nil) || @env['rack.logger']
end

#sessionObject



46
47
48
# File 'lib/limited_sessions/expiry.rb', line 46

def session
  @env['rack.session'] || {}
end