-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Rick Cotter
committed
Jan 21, 2013
0 parents
commit dcb26f2
Showing
6 changed files
with
804 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
lib-cov | ||
*.seed | ||
*.log | ||
*.csv | ||
*.dat | ||
*.out | ||
*.pid | ||
*.gz | ||
|
||
pids | ||
logs | ||
results | ||
|
||
npm-debug.log | ||
|
||
node_modules | ||
.idea/* |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
# connect-mongodb-simple | ||
Copyright(c) 2013 BeauCoo | ||
Author: Rick Cotter | ||
|
||
Reasoning: | ||
|
||
* Few dependencies equals easy to keep up to date. | ||
* Lets what could be dependencies do what they do best i.e. | ||
[node-mongodb-native](http://github.com/christkv/node-mongodb-native) - connectivity and write level concerns. | ||
* Upgraded to work with [Connect 2.x](http://www.senchalabs.org/connect/) yet decoupled from it | ||
(a la [connect-redis](https://github.com/visionmedia/connect-redis)) | ||
* Ability to annotate sessions for orthogonal concerns | ||
|
||
Attribution: | ||
|
||
* Initial implementation inspired by [connect-mongodb](https://npmjs.org/package/connect-mongodb), especially by its lack of maintenance. | ||
* Updates by nathanbower (from connect-mongodb uncommitted pull request #60) | ||
* Heavy referencing of [connect-redis](https://github.com/visionmedia/connect-redis) | ||
|
||
|
||
## Installation | ||
|
||
Via <code>npm install connect-mongodb-simple</code> | ||
|
||
|
||
## Use | ||
|
||
<pre><code> | ||
var MongoStore = require('connect-mongodb-simple')(express); | ||
// OR var MongoStore = require('connect-mongodb-simple')(connect); | ||
|
||
var sessionStore = new MongoStore( | ||
openDb, | ||
{collectionName:"sess", reapIntervalMs:(60 * 1000), ttl:(60 * 60 * 1000}, | ||
function modify(session) { return {...} }, | ||
function callback() { console.log("done"); } | ||
); | ||
|
||
// Where 'app' is an ExpressJS instance (or whatever) | ||
app.configure(function () { | ||
|
||
... | ||
|
||
app.use(express.session({ | ||
cookie:{maxAge:[MAX AGE MS]}, | ||
store:sessionStore, | ||
secret:[SECRET]} | ||
)); | ||
|
||
... | ||
}); | ||
</code></pre> | ||
|
||
|
||
Where: | ||
|
||
* **openDB** is an open [node-mongodb-native](http://github.com/christkv/node-mongodb-native) database connection. | ||
Write mode (safe, w:, etc) is controlled here. Recommended use is the new [MongoClient](http://mongodb.github.com/node-mongodb-native/api-generated/mongoclient.html) | ||
* **options** (optional): | ||
* **ttl** (optional) is the time-to-live for sessions. If omitted, the cookie's maxAge will be used. | ||
* **collectionName** to override default 'sessions' MongoDB collection name. | ||
* **reapIntervalMs** ms to remove expired sessions. Omit or specify as less than 500 to turn-off. | ||
* **logReaping** (optional) true/false determines whether each reap is logged to console. | ||
* **modifyFunc** (optional) is a function: | ||
* Receives a session hash | ||
* Can modify it and must return null | ||
* Or returns a hash that will be merged with the root session document as json. Useful for including extra-info | ||
that will queried for orthogonal means. | ||
* **callback** (optional) to know when the async instance construction has completed. | ||
|
||
|
||
### modifyFunc Example 1: | ||
function(session) { | ||
delete session.SOME_KEY; | ||
return null; | ||
} | ||
|
||
// Resulting in a session document: | ||
|
||
{ | ||
_id:[ID], | ||
session:"{...}", // without SOME_KEY | ||
expires:[DATE] | ||
} | ||
|
||
### modifyFunc Example 2: | ||
function(session) { | ||
return {k:session.SOME_KEY}; | ||
} | ||
|
||
// Resulting in a session document: | ||
|
||
{ | ||
_id:[ID], | ||
session:"{...}", | ||
expires:[DATE], | ||
k:[VALUE OF SOME_KEY] | ||
} | ||
|
||
|
||
|
||
## Alternative Session Reaping Configuration | ||
|
||
Instead of having **connect-mongodb-simple** reap expired sessions use new features in | ||
[MongoDB](http://docs.mongodb.org/manual/tutorial/expire-data/) where the index created could be: | ||
<pre> | ||
<code>db.sessions.ensureIndex({expires:1}, {expireAfterSeconds:3600})</code> | ||
</pre> | ||
|
||
|
||
## Tests | ||
|
||
* Run <code>npm test</code> | ||
* or run `mocha test --require should --reporter spec --recursive --grep "unit tests"` | ||
* or run `mocha test --require should --reporter spec --recursive` to run unit and functional tests (requires running | ||
a mongod instance at localhost:27017 with a 'test' database) | ||
* or run continuously via `mocha watch --require should --reporter spec --recursive"` | ||
|
||
|
||
##License | ||
(The MIT License) | ||
|
||
Copyright (c) 2013 BeauCoo Technologies Inc. <info@beaucoo.com> | ||
|
||
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. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,179 @@ | ||
// Connect - MongoDB - Simple | ||
// Copyright(c) 2013 BeauCoo | ||
// Author: Rick Cotter | ||
// MIT Licensed | ||
// | ||
// Reasoning: | ||
// - Few dependencies equals easy to keep up to date. | ||
// - Let what could be dependencies do what they do best i.e. https://github.com/mongodb/node-mongodb-native | ||
// - Decoupled from Connect (for no particular reason a la connect-redis) | ||
// | ||
// Attribution: | ||
// - Initial implementation inspired by connect-mongodb | ||
// - Updates by nathanbower (from un-committed pull request #60) | ||
// - Heavy referencing to connect-redis | ||
|
||
|
||
var util = require('util'); | ||
var _ = require('lodash'); | ||
|
||
|
||
// Return the `MongoStore` extending `connect`'s session Store. | ||
module.exports = function (connect, testDbCollection) { | ||
"use strict"; | ||
|
||
var Store = connect.session.Store; | ||
var dbCollection = testDbCollection ? testDbCollection : null; | ||
var modifyFunc = null; | ||
var ttl = null; | ||
|
||
|
||
// Connect does not seem to guarantee providing callbacks | ||
function getSafeCallback(callback) { | ||
return (callback ? callback : function () { | ||
}); | ||
} | ||
|
||
|
||
// Initialize | ||
// - 'db' is a required and open MongoDb connect | ||
// - 'options' (optional): | ||
// - 'ttl' (optional) is the time-to-live for sessions. If omitted, the cookie's maxAge will be used. | ||
// - 'reapIntervalMs' (optional) specifies how often to check and remove expired sessions. Must be 1000ms or greater. | ||
// - 'collectionName' (optional) specifies the sessions collection to use. Defaults to 'sessions'. | ||
// - 'logReaping' (optional) true/false will log out when reaping occurs. | ||
// - ...and is passed on to the Connect session Store. | ||
// - 'aModifyFunc' (optional) can: | ||
// - a) modify the given session and return null. | ||
// - b) merge into the root session document by returning a hash. | ||
// - c) or a combination of the two. | ||
// - It has signature function (session) { return {...} or null; } | ||
// - Is useful for adding meta-data that can be used by external queries. | ||
// - 'callback' (optional) to know when the async instance construction has completed. | ||
function MongoStore(db, options, aModifyFunc, callback) { | ||
options = options || {}; | ||
Store.call(this, options); | ||
|
||
if (options.ttl) { | ||
ttl = options.ttl; | ||
} | ||
|
||
modifyFunc = aModifyFunc; | ||
|
||
|
||
function reap() { | ||
dbCollection.remove({expires:{'$lte':Date.now()}}, function () { | ||
if (options.logReaping === true) { | ||
console.log("Reaping sessions at %s", new Date().toISOString()); | ||
} | ||
}); | ||
} | ||
|
||
|
||
// Start Reaping i.e polling for expired sessions for removal | ||
// - Presumed that reaping is desired for lifetime of the process | ||
// - Database connectivity can be intermittent in nature but is desired to be constant | ||
// - The database driver does not reliable emit 'close' events. They are only emitted when no callback | ||
// is provided to db.close() which is out of this module's scope. | ||
// - Reaping is thus terminated on process exit | ||
function startReaping() { | ||
if (options.reapIntervalMs && 500 <= options.reapIntervalMs) { | ||
console.log("Reaping sessions enabled at %s every %d milliseconds", new Date().toISOString(), options.reapIntervalMs); | ||
|
||
var timerHandle = setInterval(reap, options.reapIntervalMs); | ||
|
||
process.on('exit', function () { | ||
console.log("Reaping sessions closed on process exit at %s", new Date().toISOString()); | ||
clearInterval(timerHandle); | ||
}); | ||
} else { | ||
console.log("Reaping sessions disabled"); | ||
} | ||
} | ||
|
||
|
||
callback = getSafeCallback(callback); | ||
function getCollectionCallback(err, collection) { | ||
if (err) { | ||
return callback(err); | ||
} | ||
|
||
dbCollection = collection; | ||
startReaping(); // Ensure collection exists before reaping begins | ||
callback(); | ||
} | ||
|
||
|
||
// Get collection | ||
if (dbCollection) { | ||
getCollectionCallback(null, dbCollection); // For testing | ||
} else { | ||
db.collection(options.collectionName || 'sessions', getCollectionCallback); | ||
} | ||
} | ||
|
||
|
||
util.inherits(MongoStore, Store); | ||
|
||
|
||
// Attempt to fetch session by the given `sid`. | ||
MongoStore.prototype.get = function (sid, callback) { | ||
callback = getSafeCallback(callback); | ||
dbCollection.findOne({_id:sid}, function (err, data) { | ||
if (err || !data) { | ||
return callback(err); | ||
} | ||
|
||
var session = JSON.parse(data.session); | ||
callback(null, session); | ||
}); | ||
}; | ||
|
||
|
||
// Commit the given `session` object associated with the given `sid` | ||
MongoStore.prototype.set = function (sid, session, callback) { | ||
var update = {}; | ||
|
||
if (modifyFunc) { | ||
var result = modifyFunc(session); | ||
if (result) { | ||
_.merge(update, result); | ||
} | ||
} | ||
|
||
update.session = JSON.stringify(session); | ||
|
||
var maxAgeSeconds = session.cookie.maxAge; | ||
var calculatedTtl = ttl || (('number' === typeof maxAgeSeconds) ? (maxAgeSeconds * 1000) : 86400000); // Default to one day | ||
update.expires = Date.now() + calculatedTtl; | ||
|
||
callback = getSafeCallback(callback); | ||
dbCollection.update({_id:sid}, {$set:update}, {upsert:true}, function (err, data) { | ||
return callback.apply(this, arguments); | ||
}); | ||
}; | ||
|
||
|
||
// Destroy the session associated with the given `sid` | ||
MongoStore.prototype.destroy = function (sid, callback) { | ||
dbCollection.remove({_id:sid}, getSafeCallback(callback)); | ||
}; | ||
|
||
|
||
// Fetch number of sessions | ||
MongoStore.prototype.length = function (callback) { | ||
dbCollection.count({}, getSafeCallback(callback)); | ||
}; | ||
|
||
|
||
// Clear all sessions | ||
MongoStore.prototype.clear = function (callback) { | ||
dbCollection.drop(getSafeCallback(callback)); | ||
}; | ||
|
||
|
||
return MongoStore; | ||
}; | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
{ | ||
"name":"connect-mongodb-simple", | ||
"description":"Simplified mongodb session store for connect. 1. Leaves the db connection logic to the native mongo driver including write level concerns. 2. Requires a very low number of dependencies meaning it is easily kept up to date (node-mongodb-native 2.x & Connect 2.x). 3. Easy modification of session enabling annotation for use by orthogonal concerns", | ||
"version": "0.0.1", | ||
"keywords": [ | ||
"connect", | ||
"mongodb", | ||
"session" | ||
], | ||
"engines": [ | ||
"node" | ||
], | ||
"directories": { | ||
"test": "./test" | ||
}, | ||
"scripts": { | ||
"test": "mocha test --require should --reporter spec --recursive --grep 'unit tests'" | ||
}, | ||
"contributors": [ | ||
{ | ||
"name": "BeauCoo", | ||
"email": "info@beaucoo.com", | ||
"url": "http://beaucoo.com/" | ||
}, | ||
{ | ||
"name": "Rick Cotter", | ||
"email": "rick@beaucoo.com" | ||
} | ||
], | ||
"bugs": { | ||
"url": "https://github.com/beaucoo/connect-mongodb-simple/issues" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/beaucoo/connect-mongodb-simple.git" | ||
}, | ||
"dependencies":{ | ||
"lodash":"1.0.0-rc.3" | ||
}, | ||
"devDependencies":{ | ||
"mongodb":"1.2.x", | ||
"connect":"2.7.x", | ||
"should":"1.2.x" | ||
}, | ||
"readmeFilename": "README.md", | ||
"main":"./connect-mongodb-simple" | ||
} |
Oops, something went wrong.