From 71053a9c48e98b9798b4c199838b691f6176a232 Mon Sep 17 00:00:00 2001 From: Peter Karman Date: Fri, 3 Mar 2017 11:27:42 -0600 Subject: [PATCH] Add :ttl configuration option **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 84f40af..e8d1fbc 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,8 @@ In your Rails app, throw in an initializer with the following contents: My::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://host:12345/2', } diff --git a/lib/redis-session-store.rb b/lib/redis-session-store.rb index a6805d2..564ce41 100644 --- a/lib/redis-session-store.rb +++ b/lib/redis-session-store.rb @@ -115,7 +115,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 @@ -128,6 +128,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 94396b4..19c3ff6 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 {