From 428b57e17e5cfc6397ed39c83321ddd6e72dbe6d Mon Sep 17 00:00:00 2001 From: Peter Karman Date: Thu, 9 Aug 2018 07:52:52 -0500 Subject: [PATCH] Add :ttl configuration option (#84) **Why**: The :expire_after config option controls both the Redis session expiration and the expiration of the Rails session cookie. Adding a new config option :ttl allows those controls to be managed separately. The most common case would be if you wanted the Rails cookie to expire when the browser is closed, as it would if :expire_after were set to `nil`. --- README.md | 3 ++- lib/redis-session-store.rb | 7 ++++++- spec/redis_session_store_spec.rb | 23 +++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 71e7c63..fd3594c 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,8 @@ In your Rails app, throw in an initializer with the following contents: Rails.application.config.session_store :redis_session_store, { key: 'your_session_key', redis: { - expire_after: 120.minutes, + expire_after: 120.minutes, # cookie expiration + ttl: 120.minutes, # Redis expiration, defaults to 'expire_after' key_prefix: 'myapp:session:', url: 'redis://localhost:6379/0', } diff --git a/lib/redis-session-store.rb b/lib/redis-session-store.rb index b39ebe1..2a2b389 100644 --- a/lib/redis-session-store.rb +++ b/lib/redis-session-store.rb @@ -116,7 +116,7 @@ def decode(data) end def set_session(env, sid, session_data, options = nil) - expiry = (options || env.fetch(ENV_SESSION_OPTIONS_KEY))[:expire_after] + expiry = get_expiry(env, options) if expiry redis.setex(prefixed(sid), expiry, encode(session_data)) else @@ -129,6 +129,11 @@ def set_session(env, sid, session_data, options = nil) end alias write_session set_session + def get_expiry(env, options) + session_storage_options = options || env.fetch(ENV_SESSION_OPTIONS_KEY, {}) + session_storage_options[:ttl] || session_storage_options[:expire_after] + end + def encode(session_data) serializer.dump(session_data) end diff --git a/spec/redis_session_store_spec.rb b/spec/redis_session_store_spec.rb index 924b419..9fbc720 100644 --- a/spec/redis_session_store_spec.rb +++ b/spec/redis_session_store_spec.rb @@ -59,6 +59,29 @@ end end + describe 'when configured with both :ttl and :expire_after' do + let(:ttl_seconds) { 60 * 120 } + let :options do + { + key: random_string, + secret: random_string, + redis: { + host: 'hosty.local', + port: 16_379, + db: 2, + key_prefix: 'myapp:session:', + ttl: ttl_seconds, + expire_after: nil + } + } + end + + it 'assigns the :ttl option to @default_options' do + expect(default_options[:ttl]).to eq(ttl_seconds) + expect(default_options[:expire_after]).to be_nil + end + end + describe 'when initializing with top-level redis options' do let :options do {