Git Product home page Git Product logo

redis-session-store's Introduction

Redis Session Store

Code Climate Gem Version

A simple Redis-based session store for Rails. But why, you ask, when there's redis-store? redis-store is a one-size-fits-all solution, and I found it not to work properly with Rails, mostly due to a problem that seemed to lie in Rack's Abstract::ID class. I wanted something that worked, so I blatantly stole the code from Rails' MemCacheStore and turned it into a Redis version. No support for fancy stuff like distributed storage across several Redis instances. Feel free to add what you see fit.

This library doesn't offer anything related to caching, and is only suitable for Rails applications. For other frameworks or drop-in support for caching, check out redis-store.

Installation

For Rails 3+, adding this to your Gemfile will do the trick.

gem 'redis-session-store'

Configuration

See lib/redis-session-store.rb for a list of valid options. 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,  # cookie expiration
    ttl: 120.minutes,           # Redis expiration, defaults to 'expire_after'
    key_prefix: 'myapp:session:',
    url: 'redis://localhost:6379/0',
  }

Redis unavailability handling

If you want to handle cases where Redis is unavailable, a custom callable handler may be provided as on_redis_down:

Rails.application.config.session_store :redis_session_store,
  # ... other options ...
  on_redis_down: ->(e, env, sid) { do_something_will_ya!(e) }
  redis: {
    # ... redis options ...
  }

Serializer

By default the Marshal serializer is used. With Rails 4, you can use JSON as a custom serializer:

  • :json - serialize cookie values with JSON (Requires Rails 4+)
  • :marshal - serialize cookie values with Marshal (Default)
  • :hybrid - transparently migrate existing Marshal cookie values to JSON (Requires Rails 4+)
  • CustomClass - You can just pass the constant name of any class that responds to .load and .dump
Rails.application.config.session_store :redis_session_store,
  # ... other options ...
  serializer: :hybrid
  redis: {
    # ... redis options ...
  }

Note: Rails 4 is required for using the :json and :hybrid serializers because the Flash object doesn't serialize well in 3.2. See Rails #13945 for more info.

Session load error handling

If you want to handle cases where the session data cannot be loaded, a custom callable handler may be provided as on_session_load_error which will be given the error and the session ID.

Rails.application.config.session_store :redis_session_store,
  # ... other options ...
  on_session_load_error: ->(e, sid) { do_something_will_ya!(e) }
  redis: {
    # ... redis options ...
  }

Note The session will always be destroyed when it cannot be loaded.

Other notes

It returns with_indifferent_access if ActiveSupport is defined.

Rails 2 Compatibility

This gem is currently only compatible with Rails 3+. If you need Rails 2 compatibility, be sure to pin to a lower version like so:

gem 'redis-session-store', '< 0.3'

Contributing, Authors, & License

See CONTRIBUTING.md, AUTHORS.md, and LICENSE, respectively.

redis-session-store's People

Contributors

bbatsov avatar biinari avatar bmarini avatar cosine avatar dplummer avatar goncalossilva avatar iggant avatar jesterovskiy avatar jjeb avatar jpawlyn avatar larouxn avatar leastbad avatar meatballhat avatar michaelxavier avatar n-rodriguez avatar nebolsin avatar olek avatar olleolleolle avatar ollie-nye avatar pkarman avatar quarklemotion avatar roidrage avatar tlossen avatar todd avatar y-yagi avatar yykamei avatar zachmargolis avatar zbelzer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

redis-session-store's Issues

Add adapter to support java spring session(saved session values as hash)

though pulled it, i don't make sure whether this function fit for this gem or not
pull request

sample config:
Rails.application.config.session_store :redis_session_store, { key: 'SESSION', redis: { expire_after: 30.minutes, key_prefix: 'spring:session:sessions:', hashkey_prefix: 'sessionAttr:', client: $redis, }, serializer: :json, adapter: :java_spring }

Issue with loading session values after upgrading to 0.11.4

Hi, I've recently updated to ruby 3.1.0 and rails 7.0.4 and as part of that upgraded from version 0.11.3 to 0.11.4
When I try to load a session value now, a NoMethod error is being raised like so:
NoMethodError: undefined method '>' for true:TrueClass

Example code which blows up:

session[:random_value] = 3 
session[:random_value].present?
Gemfile: 

ruby '3.1.0'

gem 'aws-sdk-s3'
gem 'bcrypt'
gem 'browser'
gem 'elasticsearch'
gem 'email_validator'
gem 'friendly_id'
gem 'haml'
gem 'jbuilder'
gem 'jwt'
gem 'typhoeus', '~> 1.4'
gem 'openid_connect', '~> 1.1'
gem 'pg'
gem 'puma'
gem 'rack-attack'
gem 'rails', '~> 7.0.4'
gem 'rails-i18n'
gem 'redis'
gem 'rest-client'
gem 'ruby-saml'
gem 'sidekiq'
gem 'faraday'
gem 'redis-session-store', '~>0.11.4'

group :development, :test do
  gem 'byebug'
  gem 'dotenv-rails'
  gem 'guard'
  gem 'guard-minitest'
  gem 'priscilla'
end

group :development do
  gem 'brakeman'
  gem 'listen'
  gem 'rubocop'
  gem 'spring'
  gem 'spring-watcher-listen'
  gem 'web-console'
end

group :test do
  gem 'factory_bot_rails'
  gem 'fakeredis'
  gem 'minitest-spec-rails'
  gem 'mocha'
  gem 'webmock'
end

Hook / event for on create?

In our application we currently use rails cookie store, and a customized version of it. Looking to move to this, but we need a way to hookup code on create event. Ideally its a post create, so we get passed the session id or entire object being put into redis. Is that available or suggestion where/how to do it?

Any help much appreciated, thanks!

Support for connection pooling

We're using the gem by passing in our own instance of a redis client (so as to get TLS support), but we use a connection pool for this in prod.

Would be fantastic if the gem supported the Redis' gem's interface for this if the client responds to with and then.

How to use this with Rediscloud/Heroku?

Can't seem to figure this out. Heroku Redis providers give you an URL in the following format:

redis://{user}:{pass}@{domain}.com

What is the proper method to put this info into the session_store config?

Possible rails 4 regression with destroy_session

Am checking out v0.6 with Rails 4 and I think #destroy_session has a problem:

     Failure/Error: And I sign in with the correct credentials
     NoMethodError:
       undefined method `merge' for #<ActionDispatch::Request::Session::Options:0x0000000a377530>
     # /home/dplummer/.rvm/gems/ruby-2.1.1/gems/redis-session-store-0.6.0/lib/redis-session-store.rb:129:in `destroy_session'
     # /home/dplummer/.rvm/gems/ruby-2.1.1/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:332:in `commit_session'
     # /home/dplummer/.rvm/gems/ruby-2.1.1/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:226:in `context'
     # /home/dplummer/.rvm/gems/ruby-2.1.1/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:220:in `call'
     # /home/dplummer/.rvm/gems/ruby-2.1.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/cookies.rb:486:in `call'

How to load session from id?

With the activerecord-session_store gem, when I want to manipulate the session on the server's side I used to call ActiveRecord::SessionStore::Session.find_by_session_id. What's the equivalent with redis-session-store?

Is redis gem v5 actually a blocker?

Hey gang,

gem.add_runtime_dependency 'redis', '>= 3', '< 5'

v5 of the redis gem has emerged, so this is starting to cause grief for Gemfile(s) that don't specify a version for the redis gem (eg. all Rails 6.1 rails new apps!)

Locking versions until major dependencies can be tested is a reasonable strategy, but v5 has been out for a while now. Are there actually any blocking changes?

v0.11.2 actionpack dependency incompatible with rails 6

Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    rails (~> 6) was resolved to 6.0.1.rc1, which depends on
      actionpack (= 6.0.1.rc1)

    redis-session-store (~> 0.11.2) was resolved to 0.11.2, which depends on
      actionpack (~> 3)

Documentation enhancement

Please put redis://localhost:6379/0 on the first page.
Not: redis://host:12345/2'

With Rails.application not My::Application using has been even easier.

Race condition handling

I've been investigating problems with flashes and figured out that redis-session-store doesn`t provide any handling of concurrent session changes. The problem is overviewed well here: https://paulbutcher.com/2007/05/01/race-conditions-in-rails-sessions-and-how-to-fix-them/
The solution from this article is outdated.
We use redis-session-store and we like it, but in case we have a lot of AJAX there are some problems. I think, if it's a common issue, I could work on improving this gem using concepts from outdated solution. There is no problem without concurrents requests, so such behaviour could be optional for gem user.

Flash messages not working in test environment

Switching over from the default session store to redis-session-store seems to disable flash messages in only the test environment. When using the development environment, flash messages are displayed as expected, but all Capybara tests with expectations for flash messages fail. When using logging and enabling show_browser I can see that the flash message is properly set #<ActionDispatch::Flash::FlashHash:0x0000000118ce3c18 @discard=#<Set: {}>, @flashes={"success"=>"Some Flash Message"}, @now=nil>, but is not displayed. Switching back to the default session store, everything appears the same but the flash message displays in the test environment.

How/when to clear old sessions?

How would we go about clearing out old session data from Redis so the db doesn't grow too large? Also, when would you recommend we do that?

Can't initialiaze

Hey,
I was looking for a gem like this.
Unfortunately I get the following error while starting my server
I'm running rails 3.2.13

/usr/local/rvm/gems/ruby-1.9.3-p194/gems/redis-session-store-0.2.1/lib/redis-session-store.rb:16:in `<top (required)>': uninitialized constant ActionController::Session (NameError)

What could be wrong? thx

JSON serializer does not serialize value properly

Hello,

I have this in my config:

MyApp::Application.config.session_store :redis_session_store, {
    key: 'myapp_session',
    redis: {
        db: CONFIG[:session_store_db],
        expire_after: 120.minutes,
        key_prefix: 'myapp:session:',
        serializer: :json,
        host: CONFIG[:session_store_host], # Redis host name, default is localhost
        port: CONFIG[:session_store_port] # Redis port, default is 6379
    }
}� �

And this is what I see in my Redis store as a value:
{�I"�_csrf_token�:�EFI"1sV2Ao8KNqSaZqNxGZYiXO9dEvSZQ+mtFC6yPgbiCaI0=�;

It is invalid JSON. My actual CSRF value is:
sV2Ao8KNqSaZqNxGZYiXO9dEvSZQ+mtFC6yPgbiCaI0=

I am using Rails 4.

Support Rails 6

I believe this may be as simple as just releasing a new version as the problematic upper dependency for ActionPack was already removed in fac8243.

Adding a password to session_store.rb

How do you add a password to the redis host? I'm currently passing in a password parameter, but I don't see that in the docs. Surprisingly, it's working, but that makes me worry a little bit. Is password a parameter you can pass in as part of the parameter?

Session destroy?

I was getting errors about session destroy not existing, which I fixed with

require 'redis-session-store'

class RedisSessionStore
  def destroy_session(env, sid, options)
    redis.del(prefixed(sid))
    generate_sid
  end
end

any ideas?

Update readme for Ruby 3

Recent changes (Ruby 3) to keyword arguments causes this line to fail:

Rails.application.config.session_store :redis_session_store, {key: 'foo', redis: {}}

With a rather misleading error:

gems/railties-6.1.3.2/lib/rails/application/configuration.rb:304:in `session_store': wrong number of arguments (given 2, expected 0..1) (ArgumentError)

The correct syntax is:

Rails.application.config.session_store :redis_session_store, key: 'foo', redis: {}

when and where the cookie will be reset when server restart

I want to migrate the session data from the cookies to the redis. I decode and get the session data from cookie, then I store it with the key of session_id at redis. But, when the server restart under the config of redis_session_store, the cookie is reset by a new session_id。I don't know when and where the cookie was reset. How to keep the resetting cookie with the same session_id?

Multi domain cookie

Is there a way I can issue a multi domain cookie (for sub-domains) using this store?

Use redis.exist? in session_exists?

https://github.com/roidrage/redis-session-store/blob/master/lib/redis-session-store.rb#L70

Redis warns:

Redis#exists(key)will return an Integer in redis-rb 4.3.exists?returns a boolean, you should use it instead. To opt-in to the new behavior now you can set Redis.exists_returns_integer = true. To disable this message and keep the current (boolean) behaviour of 'exists' you can setRedis.exists_returns_integer = false, but this option will be removed in 5.0. (/app/vendor/bundle/ruby/2.6.0/gems/redis-session-store-0.11.1/lib/redis-session-store.rb:70:in session_exists?

Nomimate myself to join committer team

Hey gang,

I recently created a PR to support redis-rb v5. It's been pretty quiet since that PR was accepted. I am going to speculate that your team could use some new blood.

I'm a core team member of the StimulusReflex project. We actively push our users towards this gem, both in the installation system and in our docs.

I'm quite proficient with Redis and reasonably familiar with both this gem and also Kredis. I am soon to release a gem called All Futures, which is a Redis-backed ORM that quacks like Active Record.

Please, let me help make sure this gem kicks ass for the next decade.

Need to share session with java spring mvc

In our project, we need to share session between rails and spring. So I modified some code to adapt to other framework. May I pull them to this repo or build a new one?

Bigger TTL for signed in users

For our app, we have about 2.5M session keys in redis. All of them has fixed (1 week) TTL.
I was thinking if it's a good idea to make TTL smaller for guests and bigger for signed in users.

Any thoughts?

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can imagine, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

VERSION = '0.9.1'.freeze <- 0.9.2 ?

Hey,

i wanted to upgrade my project to rails 5.1 but the bundler came up with a version conflict.

Is it correct that the VERSION is still set to 0.9.1?
There is a release for 0.9.2 https://github.com/roidrage/redis-session-store/releases/tag/v0.9.2
So far i changed my Gemfile to load the gem from github. It is still shown as 0.9.1 but has all the changes for 0.9.2.

What can i do to get the 0.9.2 release from rubygems.org?
Would rubygems.org automatically update to 0.9.2 after VERSION ist set to 0.9.2?

Best regards
Eric

SAVE or BGSAVE?

It might be useful if there was a gem option that would cause it to issue a SAVE or a BGSAVE command to Redis. Then session (and all other data) could be recovered in case of a crash.

Example:
> save

or

> save 60 # saves every sixty seconds

or

> save 60 100 # save once a minute if at least a hundred keys have been changed

Redis persistence: http://redis.io/topics/persistence

Regression in 0.11.4?

In 0.11.4 the following change was introduced:

3ee0426

I'm seeing this exception raised in Rack v2.2.3.1:

NoMethodError:
       undefined method `cookie_value' for "e1af07cec3cbb9aade2800550652e7bc":String

This can be traced to this line:

https://github.com/rack/rack/blob/925a4a6599ab26b4f3455b525393fe155d443655/lib/rack/session/abstract/id.rb#L482-L484

It seems that the data returned by set_session is a simple string, but a different data structure is expected:

def set_session(env, sid, session_data, options = nil)
expiry = get_expiry(env, options)
if expiry
redis.setex(prefixed(sid), expiry, encode(session_data))
else
redis.set(prefixed(sid), encode(session_data))
end
sid
rescue Errno::ECONNREFUSED, Redis::CannotConnectError => e
on_redis_down.call(e, env, sid) if on_redis_down
false
end
alias write_session set_session

If you dig into ActionDispatch::Session::CookieStore we can see that it's write_session implementation return a Rack::Session::SessionId instance (albeit decorated):

https://github.com/rails/rails/blob/04972d9b9ef60796dc8f0917817b5392d61fcf09/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb#L104-L107

If one returns an appropriately crafted instance this package works again.

redis-rb 3.1.0

With the latest version of the redis ruby client doesn't seem to work with the options specified in the README. I keep on getting the following:

/usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/redis-3.1.0/lib/redis/client.rb:370:in `_parse_options': invalid url (ArgumentError)

Digging through the redis client source I've had to switch to using a redis URL scheme:

Rails.application.config.session_store :redis_session_store, {
  key: "_#{Rails.application.class.parent_name}_session_#{Rails.env}",
  redis: {
    expire_after: 7.days,
    url: "redis://localhost:6379/0"
  }
}

I believe this maybe because of changes to _parse_options in the redis client. https://github.com/redis/redis-rb/blob/7c4a95413009cefa0c74d8d320f1ae90a1c953c2/lib/redis/client.rb

Delete session in rack 2.0

error

I'm using this with devise 4.0 master and rails 5.0.0 master
Rack raised delete_session not implemented error. It seems it was destroy_session before.

Bare rescue in load_session_from_redis silently discards wide variety of exceptions

There is a bare rescue (which rescues all exceptions that inherit from StandardError) in RedisSessionStore#load_session_from_redis.

This is extremely bad practice, because it will cause a huge variety of exceptions to be silently ignored, including virtually all exceptions generated by any ruby library, including ThreadError, LocalJumpError, etc.

https://github.com/roidrage/redis-session-store/blame/bcf779297078db78d7e17b868c40b1ffd4dea243/lib/redis-session-store.rb#L106

This is just the built in tree of exceptions that would be silently swallowed:

StandardError
  FiberError
  ThreadError
  IndexError
    StopIteration
    KeyError
  Math::DomainError
  LocalJumpError
  IOError
    EOFError
  EncodingError
    Encoding::ConverterNotFoundError
    Encoding::InvalidByteSequenceError
    Encoding::UndefinedConversionError
    Encoding::CompatibilityError
  RegexpError
  SystemCallError
    Errno::ERPCMISMATCH
    # ... lots of system call errors ...
  RangeError
    FloatDomainError
  ZeroDivisionError
  RuntimeError
    Gem::Exception
      # ... lots of gem errors ...
  NameError
    NoMethodError
  ArgumentError
    Gem::Requirement::BadRequirementError
  TypeError

Incomplete fix to secure session store CVE-2019-16782

#125 switches to using the new ActionDispatch::Session::AbstractSecureStore but it does not change the key used to store sessions in redis. This means that there is still potentially a timing attack that could be used against looking up a session.

We should use the Rack::Session::SessionId#private_id as the key in redis storage and #public_id in the cookie.

It would seem reasonable to fallback to using the #public_id for sessions that have not yet been converted to use the #private_id for their key.

rails/activerecord-session_store#151 could be used for inspiration.

I've submitted on a PR for this and tested it out on our app.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.