Git Product home page Git Product logo

mongo_session_store's Introduction

MongoSessionStore Build Status Gem Version

This gem is for Rails 3 and 4. For Rails 5 and later, see mongoid/mongo_session_store.

Description

MongoSessionStore is a collection of Rails-compatible session stores for MongoMapper and Mongoid, but also included is a generic Mongo store that works with any (or no!) Mongo ODM.

MongoSessionStore is tested on Travis CI against Ruby 1.9.3, 2.0.0, 2.1.5, 2.2.0, and JRuby with Rails 3.1 through 4.2.

Mongoid users: This gem is compatible with both Mongoid 3 and 4.

If this gem doesn't work for you, you might next try mongo_sessions.

See the Changelog if you need support for an older version of Ruby, Rails, or Mongoid.

Usage

MongoSessionStore is compatible with Rails 3.1 through 4.2.

In your Gemfile:

gem "mongo_mapper"
# or gem "mongoid"
# or gem "mongo"
gem "mongo_session_store-rails4"
# or gem "mongo_session_store-rails3"

In the session_store initializer (config/initializers/session_store.rb):

# MongoMapper
MyApp::Application.config.session_store :mongo_mapper_store

# Mongoid
MyApp::Application.config.session_store :mongoid_store

# anything else
MyApp::Application.config.session_store :mongo_store
MongoStore::Session.database = Mongo::Client.new(["127.0.0.1:27017"], database: "my_app_development")

By default, the sessions will be stored in the "sessions" collection in MongoDB. If you want to use a different collection, you can set that in the initializer:

MongoSessionStore.collection_name = "client_sessions"

And if for some reason you want to query your sessions:

# MongoMapper
MongoMapperStore::Session.where(:updated_at.gt => 2.days.ago)

# Mongoid
MongoidStore::Session.where(:updated_at.gt => 2.days.ago)

# Plain old Mongo
MongoStore::Session.where("updated_at" => { "$gt" => 2.days.ago })

Changelog

6.0.0 supports the Mongo Ruby Driver 2.0 for the generic MongoStore. The other stores are unchanged. Tests added for Rails 4.2. Tests against MongoDB 3.0.1 on Travis CI.

5.1.0 generates a new session ID when a session is not found. Previously, when a session ID is provided in the request but the session was not found (because for example, it was removed from Mongo by a sweeper job) a new session with the provided ID would be created. This would cause a write error if two simultaneous requests both create a session with the same ID and both try to insert a new document with that ID.

5.0.1 suppresses a warning from Mongoid 4 when setting the _id field type to String.

5.0.0 introduces Rails 4.0 and 4.1 support and Mongoid 4 support alongside the existing Rails 3.1, 3.2, and Mongoid 3 support. Ruby 1.8.7 support is dropped. The database is no longer set automatically for the MongoStore when MongoMapper or Mongoid is present. You have to set the database manually whenever you choose to use the vanilla MongoStore.

The last version to support Ruby 1.8.7 is version 4.1.1.

The last version to support Rails 3.0 or Mongoid 2 is version 3.0.6.

Development

To run all the tests:

rake

To run the tests for a specific store (examples):

rake test_31_mongo
rake test_32_mongoid
rake test_40_mongoid
rake test_41_mongo_mapper

To see a list of all options for running tests, run

rake -T

Previous contributors

MongoSessionStore started as a fork of the DataMapper session store, modified to work with MongoMapper and Mongoid. Much thanks to all the previous contributors:

  • Nicolas Mérouze
  • Chris Brickley
  • Tony Pitale
  • Nicola Racco
  • Matt Powell
  • Ryan Fitzgerald

License

Copyright (c) 2011-2014 Brian Hempel Copyright (c) 2010 Nicolas Mérouze Copyright (c) 2009 Chris Brickley Copyright (c) 2009 Tony Pitale

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mongo_session_store's People

Contributors

acant avatar benhutton avatar brianhempel avatar canavese avatar codegoalie avatar compressed avatar did avatar galfert avatar hsbt avatar mattbeedle avatar memuller avatar nmerouze avatar shingara avatar tpitale 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongo_session_store's Issues

MongoStore::Session is not deserialized correctly

Hello,

I try to use mongo_session_store with MongoStore. For some reasons, we are stuck with ruby mongo 1.12 driver, so lastest working version of mongo_session_store is 5.1 (6.0 does not want to work with 1.12).

I've noticed that with every request, new document in database is created. Analysing code I saw these lines:

        def self.load(options = {})
          options[:data] = options["data"] if options["data"]
          new(options)
        end

Document fetched from database with e.g. ActionDispatch::Session::MongoStore::Session.collection.find.first is: {"_id"=>"lsn4t6544ngQjAEgofn-dHlMytA", "data"=><BSON::Binary:70311184564240>, "created_at"=>2015-08-18 13:09:19 UTC, "updated_at"=>2015-08-18 13:09:19 UTC}

but using ActionDispatch::Session::MongoStore::Session.where.first, a Session instance is in form:

#<ActionDispatch::Session::MongoStore::Session:0x007fe536bc4238 @_id=nil, @data=<BSON::Binary:70311183800340>, @created_at=nil, @updated_at=nil>

Isn't it a bug, that self.load method sets only options[:data] field, ignoring _id, created_and and updated_at (whose are Strings not Symbols)?

I think it causes that Sessions can't be deleted, e.g.:

2.1.4 :096 > ActionDispatch::Session::MongoStore::Session.where.collect &:_id
 => [nil, nil, nil, nil, nil] 
2.1.4 :107 > ActionDispatch::Session::MongoStore::Session.where.collect &:destroy
 => [{"ok"=>1, "n"=>0}, {"ok"=>1, "n"=>0}, {"ok"=>1, "n"=>0}, {"ok"=>1, "n"=>0}, {"ok"=>1, "n"=>0}]

Mongo session store version 6.0 has the same code for self.load.

Best regards,
Jakub Liput

Do you plan Rails 5 support?

I get this error when running my project with mongo_session_store-rails4 in Rails 5.

RuntimeError (#find_session not implemented.):

vendor/ruby/2.3.0/gems/rack-2.0.1/lib/rack/session/abstract/id.rb:380:in find_session' vendor/ruby/2.3.0/gems/rack-2.0.1/lib/rack/session/abstract/id.rb:270:inload_session'
vendor/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/session/abstract_store.rb:56:in block in load_session' vendor/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/session/abstract_store.rb:64:instale_session_check!'
vendor/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/session/abstract_store.rb:56:in load_session' vendor/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/request/session.rb:216:inload!'
vendor/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/request/session.rb:212:in load_for_write!' vendor/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/request/session.rb:114:in[]='
...
...

It looks like session support was changed in rack 2.

I am using mongoid_store

WwwDrgcms::Application.config.session_store :mongoid_store , {
expire_after: 1.month
}

and if I disable these lines application is working to some degree.

by
TheR

Need a way to clean up the sessions collection (removing "orphaned" session)

I just started using this gem last week. I've noticed that my sessions collection is building up session data for sessions that are no longer active. My app is PKI-enabled so there is no "logout" functionality (where I could reset the session). So, each time the user comes at the site with a new browser, a new session is created. The old session was essentially "orphaned" when the user closed his browser. Is there a way to cleanup this data (similar to ActiveRecords "sweep" method?)?

Can't modify frozen hash with devise #sign_in

I'm working with Devise 1.4.2, Mongoid 2.0.2, mongo_session_store(latest commit) and have a form that manually calls the sign_in helper method for a user. When the forgetable callback for after_set_user is run it attempts to modify the session in some way, and it fails hard with "can't modify frozen hash". The stack trace I get is below. I really don't know exactly what is going on, or how record.data is getting frozen. If there's any more information I can provide, please let me know.

mongoid (2.0.2) lib/mongoid/dirty.rb:226:in `[]='
mongoid (2.0.2) lib/mongoid/dirty.rb:226:in `modify'
mongoid (2.0.2) lib/mongoid/attributes.rb:96:in `write_attribute'
mongoid (2.0.2) lib/mongoid/fields.rb:161:in `block (2 levels) in create_accessors'
/home/steve/.rvm/gems/ruby-1.9.2-p180@organizer/bundler/gems/mongo_session_store-c6486aca2f51/lib/mongo_session_store/mongoid.rb:45:in `set_session'
rack (1.3.0) lib/rack/session/abstract/id.rb:301:in `commit_session'
rack (1.3.0) lib/rack/session/abstract/id.rb:196:in `context'
rack (1.3.0) lib/rack/session/abstract/id.rb:190:in `call'
actionpack (3.1.0.rc4) lib/action_dispatch/middleware/cookies.rb:321:in `call'
actionpack (3.1.0.rc4) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (3.1.0.rc4) lib/active_support/callbacks.rb:392:in `_run_call_callbacks'
activesupport (3.1.0.rc4) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.1.0.rc4) lib/action_dispatch/middleware/callbacks.rb:28:in `call'
actionpack (3.1.0.rc4) lib/action_dispatch/middleware/reloader.rb:68:in `call'
rack (1.3.0) lib/rack/sendfile.rb:102:in `call'
actionpack (3.1.0.rc4) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.1.0.rc4) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
railties (3.1.0.rc4) lib/rails/rack/logger.rb:13:in `call'
rack (1.3.0) lib/rack/methodoverride.rb:24:in `call'
rack (1.3.0) lib/rack/runtime.rb:17:in `call'
activesupport (3.1.0.rc4) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.3.0) lib/rack/lock.rb:34:in `call'
actionpack (3.1.0.rc4) lib/action_dispatch/middleware/static.rb:53:in `call'
railties (3.1.0.rc4) lib/rails/engine.rb:438:in `call'
railties (3.1.0.rc4) lib/rails/railtie/configurable.rb:30:in `method_missing'
railties (3.1.0.rc4) lib/rails/rack/log_tailer.rb:14:in `call'
railties (3.1.0.rc4) lib/rails/rack/content_length.rb:16:in `call'
railties (3.1.0.rc4) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.3.0) lib/rack/handler/webrick.rb:59:in `service'
/home/steve/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
/home/steve/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
/home/steve/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'

Session is loaded when Rails serves assets

See the rails output:

Started GET "/assets/image.png" for 127.0.0.1 at 2013-04-12 21:04:44 -0400
MOPED: ip_removed:27017 COMMAND database=admin command={:ismaster=>1} (49.5179ms)
MOPED: ip_removed:27017 QUERY database=test_app collection=sessions selector={"$query"=>{"_id"=>"Ex3eCW1YUFRMj0w3FSiToazcD4Y"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (24.9338ms)
Served asset /image.png - 304 Not Modified (0ms)

Mongoid 3 slowed down due to bson_ext inclusion

If you're using Mongoid3, having bson_ext installed severely hampers performance. There's a workaround to allow the user to install the correct dependencies for the version of mongoid they are running, noted here:

https://github.com/mongoid/mongoid/issues/2378#issuecomment-10257115

Thanks in advance! If you'd like I can try and get a fix out to you this weekend as a pull request.

I found this issue when testing upgrading our project to mongoid3. To my surprise, this was the culprit. :/

Cheers!

Don't use autload to bring in different session stores

I just ran into an issue starting my JRuby on Rails app (which is deployed as a WAR file to a Tomcat server) that it couldn't load "mongo_mapper". This threw me for a minute b/c I use Mongoid and don't have any direct reference to mongo_mapper.

I found in mongoid_session_store-rails3.rb that autloading was being used (which was added as a pull request on issue #8).

The MongoSessionStore#collection_name= method ultimately ends up referencing the "MongoMapperStore" constant (defined by the autloading setup), which in turn ends up requring 'mongo_mapper', which I don't have installed.

I understand the autoload feature makes things a bit cleaner but it also causes things to break when you don't have all possibly used gems installed.

Updates and ownership

Hi there!

I was looking at this gem and noticed it hasn't been updated in a while. @brianhempel are you still supporting it?

My interest in this gem comes from the need for the feature @appsignal. I updated the gem in my own fork https://github.com/appsignal/mongo_session_store (branch update), so we can use an updated version, but we can also help out with updating this gem or even take over maintenance. Not promising any long time support or anything outside the scope of our needs, but these changes might be useful for some in a new version of the gem.

In my fork I've updated the gem to use more recent versions of mongo, mongoid, rack and RSpec. No Rails 5 support yet, since we're not using it at this time. I removed support for mongo_mapper and jruby, to make the upgrade easier, but this functionality could easily be restored in the future.

I'm planning on expanding the test suite to test more parts individually and to add the feature of a custom session class, which might just avoid the whole different implementations problem (mongo, mongoid, mongo_mapper).

Let me know what you think @brianhempel !

Right way to share session across rails app to other service

I've been able to reliably use this gem with Mongoid, MongoMapper and without an ODM for a single rails project. I am interested in being able to share the session object created in my rails app with another service (nodejs app).

I am unable to convert the BSON::Binary data object to a JSON representation consistently. Is it possible for the data object saved in Mongo to represent the document as a deserialized document, using this gem?

Querying mongo directly I get the following:

db.sessions.findOne();
{
"_id" : "AcXl2BJrZxJm92p3A9Pe8dHgZtc",
"data" : BinData(0,"BAh7CUkiDHVzZXJfaWQGOgZFRmkGSSIMdGVhbV9pZAY7AEZJIgYxBjsARkkiCmZsYXNoBjsARm86JUFjdGlvbkRpc3BhdGNoOjpGbGFzaDo6Rmxhc2hIYXNoCToKQHVzZWRvOghTZXQGOgpAaGFzaHsGOgxzdWNjZXNzVDoMQGNsb3NlZEY6DUBmbGFzaGVzewY7CkkiD0hleSEgSm9zdWUGOwBGOglAbm93bzokQWN0aW9uRGlzcGF0Y2g6OkZsYXNoOjpGbGFzaE5vdwY6C0BmbGFzaEAKSSIQX2NzcmZfdG9rZW4GOwBGSSIxVVpTVVZETktQeGJNY1ZtMG1LTmZYL01FcHdPQW1BR2oxSHFwcnRQUllSWT0GOwBG"),
"created_at" : ISODate("2012-12-04T20:25:42.459Z"),
"updated_at" : ISODate("2012-12-04T20:25:42.490Z")
}

In MongoMapper I fetch the same object:

f = MongoMapperStore::Session.last
=> #<ActionDispatch::Session::MongoMapperStore::Session _id: "AcXl2BJrZxJm92p3A9Pe8dHgZtc", created_at: Tue, 04 Dec 2012 20:25:42 UTC +00:00, data: BSON::Binary:70350084844240, updated_at: Tue, 04 Dec 2012 20:25:42 UTC +00:00>

And follow that up with just referencing the data object.
data = f[:data]
=> BSON::Binary:70350084844240

Things get confusing here:

str = data.to_s
=> "\x04\b{\tI"\fuser_id\x06:\x06EFi\x06I"\fteam_id\x06;\x00FI"\x061\x06;\x00FI"\nflash\x06;\x00Fo:%ActionDispatch::Flash::FlashHash\t:\n@usedo:\bSet\x06:\n@hash{\x06:\fsuccessT:\f@closedF:\r@flashes{\x06;\nI"\x0FHey! Josue\x06;\x00F:\t@nowo:$ActionDispatch::Flash::FlashNow\x06:\v@flash@\nI"\x10_csrf_token\x06;\x00FI"1UZSUVDNKPxbMcVm0mKNfX/MEpwOAmAGj1HqprtPRYRY=\x06;\x00F"

Leading to a DecodeError

ActiveSupport::JSON.decode str
MultiJson::DecodeError: 795: unexpected token

Ideally I need to determine a way to share sessions, but it would also be nice to understand what is going on.

Not Saving Flash messages

Hi,

I recently started using mongo_session_store-rails3 and I observed that flash messages are being lost .

Could you help me out ?

Sairam

Remove dependency on Mongo gem?

I'm trying to use this gem in a Mongoid environment. I have no need for the Mongo gem - it just adds app bloat for me

So, given that this gem is meant to work with all manner of Mongo-based setups, and for Mongoid or MongoMapper, you have to install the appropriate gem yourself, would you consider doing the same for plain Mongo?

That is, remove this line: https://github.com/brianhempel/mongo_session_store/blob/master/mongo_session_store-rails3.gemspec#L16

And then add appropriate instructions in the README to include that gem manually.

Thanks for considering. I'd be more than happy to submit the pull request myself if this is something that you would consider.

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.