express-socket.io-session
Advanced tools
Comparing version 1.2.6 to 1.3.0
@@ -17,3 +17,5 @@ var debug = require("debug")("express-socket.io-session:example"), | ||
// Share session with io sockets | ||
io.use(sharedsession(session)); | ||
io.use(sharedsession(session, { | ||
autoSave: true | ||
})); | ||
@@ -36,6 +38,7 @@ | ||
app.use("/login", function(req, res, next) { | ||
debug("Requested /login") | ||
req.session.user = { | ||
username: "OSK" | ||
}; | ||
req.session.save(); | ||
//req.session.save(); | ||
res.redirect("/"); | ||
@@ -45,4 +48,5 @@ }); | ||
app.use("/logout", function(req, res, next) { | ||
debug("Requested /logout") | ||
delete req.session.user; | ||
req.session.save(); | ||
//req.session.save(); | ||
res.redirect("/"); | ||
@@ -55,7 +59,11 @@ }); | ||
// Set session data via socket | ||
debug("Emitting session data"); | ||
socket.on("login", function() { | ||
debug("Received login message"); | ||
socket.handshake.session.user = { | ||
username: "OSK" | ||
}; | ||
socket.handshake.session.save(); | ||
debug("socket.handshake session data is %j.", socket.handshake.session); | ||
// socket.handshake.session.save(); | ||
//emit logged_in for debugging purposes of this example | ||
@@ -66,5 +74,9 @@ socket.emit("logged_in", socket.handshake.session); | ||
socket.on("logout", function() { | ||
delete socket.handshake.session.user; | ||
socket.handshake.session.save(); | ||
debug("Received logout message"); | ||
socket.handshake.session.user = {}; | ||
delete socket.handshake.session.logged; | ||
// socket.handshake.session.save(); | ||
//emit logged_out for debugging purposes of this example | ||
debug("socket.handshake session data is %j.", socket.handshake.session); | ||
socket.emit("logged_out", socket.handshake.session); | ||
@@ -71,0 +83,0 @@ }); |
97
index.js
var cookieparser = require('cookie-parser'); | ||
var debug = require("debug")("express-socket.io-session"); | ||
var crc = require("crc").crc32; | ||
// The express session object will be set | ||
@@ -10,13 +10,24 @@ // in socket.handskake.session. | ||
* | ||
* @param {Function} an express-session middleware function to reuse with io.use | ||
* @param {Function} an express-session middleware function to reuse with express-session | ||
* @param {Function} expressSessionMiddleware - An express-session middleware function to reuse with io.use | ||
* @param {Function} cookieParserMiddleware - An express-session middleware function to reuse with express-session | ||
* @param {Object} options - An object with some options for overriding default behaviour. | ||
* - {Boolean} autSave - If true, the session variables will be saved asyncrhonously to express-session driver | ||
* by wrapping the method socket.on | ||
*/ | ||
module.exports = function(expressSessionMiddleware, cookieParserMiddleware) { | ||
module.exports = function(expressSessionMiddleware, cookieParserMiddleware, options) { | ||
var socketIoSharedSessionMiddleware; | ||
// Accept options as second argument if only 2 parameters passed | ||
if (arguments.length == 2 && typeof cookieParserMiddleware === 'object') { | ||
options = cookieParserMiddleware; | ||
cookieParserMiddleware = undefined; | ||
} | ||
if (typeof cookieParserMiddleware === 'undefined') { | ||
debug("No cookie-parser instance passed as argument"); | ||
debug("Creating a cookie-parser instance with default values"); | ||
debug("No cookie-parser instance passed as argument. Creating a cookie-parser " + | ||
"instance with default values"); | ||
cookieParserMiddleware = cookieparser(); | ||
} | ||
options = options || {}; | ||
var saveUninitializedSession = options.saveUninitialized; | ||
debug("Creating socket.io middleware"); | ||
@@ -26,3 +37,26 @@ | ||
var req = socket.handshake; | ||
var res = {}; | ||
var res = { | ||
end: function() {} | ||
}; | ||
// originalHash, savedHash, originalId, cookieId | ||
// are variables present for replicating express-session autoSaving behavioiur | ||
var originalHash, savedHash; | ||
var originalId; | ||
var cookieId; | ||
var _onevent = socket.onevent; | ||
// Override socket.on if autoSave = true; | ||
if (options.autoSave === true) { | ||
debug("Using autoSave feature. express-session middleware will be called on every event received") | ||
socket.onevent = function() { | ||
debug("Executing socket.onevent monkeypatched by express-socket.io-session"); | ||
var _args = arguments; | ||
originalHash = savedHash = hash(req.session); | ||
cookieId = req.sessionID; | ||
originalId = req.sessionID; | ||
_onevent.apply(socket, _args); | ||
if (shouldSave(req)) { | ||
req.session.save() | ||
} | ||
}; | ||
} | ||
//Parse session cookie | ||
@@ -38,4 +72,53 @@ cookieParserMiddleware(req, res, function(err) { | ||
}); | ||
/* | ||
* These functions hash, isModified, isSaved, shouldSave | ||
* and shouldDestroy are canibalized from express-session | ||
* in order to this module being able to comply with the autoSave options. | ||
*/ | ||
/** | ||
* Hash the given `sess` object omitting changes to `.cookie`. | ||
* | ||
* @param {Object} sess | ||
* @return {String} | ||
* @private | ||
*/ | ||
function hash(sess) { | ||
return crc(JSON.stringify(sess, function(key, val) { | ||
if (key !== 'cookie') { | ||
return val; | ||
} | ||
})); | ||
} | ||
// check if session has been modified | ||
function isModified(sess) { | ||
return originalId !== sess.id || originalHash !== hash(sess); | ||
} | ||
// check if session has been saved | ||
function isSaved(sess) { | ||
return originalId === sess.id && savedHash === hash(sess); | ||
} | ||
// determine if session should be destroyed | ||
function shouldDestroy(req) { | ||
return req.sessionID && unsetDestroy && req.session == null; | ||
} | ||
// determine if session should be saved to store | ||
function shouldSave(req) { | ||
// cannot set cookie without a session ID | ||
if (typeof req.sessionID !== 'string') { | ||
debug('session ignored because of bogus req.sessionID %o', req.sessionID); | ||
return false; | ||
} | ||
return !saveUninitializedSession && cookieId !== req.sessionID ? isModified(req.session) : !isSaved(req.session) | ||
} | ||
}; | ||
return socketIoSharedSessionMiddleware; | ||
}; |
{ | ||
"name": "express-socket.io-session", | ||
"version": "1.2.6", | ||
"version": "1.3.0", | ||
"description": "Share a cookie-based express-session middleware with socket.io", | ||
@@ -25,4 +25,5 @@ "main": "index.js", | ||
"cookie-parser": "~1.3.3", | ||
"crc": "^3.3.0", | ||
"debug": "~2.1.0" | ||
} | ||
} |
express-socket.io-session | ||
========================= | ||
Share a cookie-based express-session middleware with socket.io | ||
Share a cookie-based express-session middleware with socket.io. Works with **express > 4.0.0** and **socket.io > 1.0.0** and won't be backward compatible. | ||
**express-socket.io-session** works with **express > 4.0.0** and **socket.io > 1.0.0** and won't be backward compatible. | ||
**Help me notice errors or ask me for improvements [creating an issue](https://github.com/oskosk/express-socket.io-session/issues/new)**. | ||
## Installation | ||
``` | ||
$ npm install express-socket.io-session | ||
``` | ||
## Overview | ||
On every socket connection, you'll have the session object at | ||
**socket.handshake.session** | ||
After every socket connection, you'll have **socket.handshake.session**. | ||
That is the same session object `req.session` you get in your route middleware when your app | ||
uses `express-session`. | ||
uses [express-session](https://www.npmjs.com/package/express-session). | ||
@@ -20,15 +24,13 @@ | ||
Don't rely on **session data autosaving** if you use an [async store](https://github.com/expressjs/session#compatible-session-stores) for **express-session**. | ||
When inside express, you normally get to modify your session variables trusting | ||
that **express-session** saves them for you. | ||
Use [Session.reload()](https://github.com/expressjs/session#sessionreload) and [Session.save()](https://github.com/expressjs/session#sessionsave) | ||
on the `socket.handshake.session` object inside your socket.io event handlers. | ||
Invoke this module with an option of `autoSave:true` in order for achieveing the | ||
same behaviour. | ||
**Please, see [More about updating and getting session data](more-about-updating-and-getting-session-data) for better understanding | ||
of how to read and update session data inside your socket.io event handlers**. | ||
io.use(sharedsession(session, { | ||
autoSave:true | ||
})); | ||
## Installation | ||
``` | ||
$ npm install express-socket.io-session | ||
``` | ||
@@ -42,12 +44,18 @@ ## Usage | ||
}); | ||
var sharedsession = require("express-socket.io-session")(session); | ||
var sharedsession = require("express-socket.io-session"); | ||
app.use(session); // Use express-session middleware for express | ||
// Use express-session middleware for express | ||
app.use(session); | ||
io.use(sharedsession(session)); // use shared session middleware for socket.io | ||
// Use shared session middleware for socket.io | ||
// setting autoSave:true | ||
io.use(sharedsession(session, { | ||
autoSave:True | ||
})); | ||
**Sharing session data with a namespaced socket** | ||
io.of('/namespace').use(sharedsession(session)); | ||
io.of('/namespace').use(sharedsession(session, { | ||
autoSave: true | ||
})); | ||
@@ -95,3 +103,2 @@ | ||
socket.handshake.session.userdata = userdata; | ||
socket.handshake.session.save(); | ||
}); | ||
@@ -101,4 +108,2 @@ socket.on("logout", function(userdata) { | ||
delete socket.handshake.session.userdata; | ||
// Save the data to the session store | ||
socket.handshake.session.save(); | ||
} | ||
@@ -110,30 +115,14 @@ }); | ||
## More about updating and getting session data | ||
You may be used to `express-session` behaviour by which, you just | ||
modify the `session` properties and its value gets updated (even with | ||
using asynchronous stores like mongodb or redis). **express-session** achieves that | ||
by monkeypatching (and overloading) `req.end`. | ||
The case here is that **socket.io middleware is run only once**. On connection handshake. | ||
The event handlers you define can't trigger the middleware. | ||
So if you get used to accessing and saving session data **inside | ||
your event handlers**, with the `.reload()` | ||
and `.save()` from the session object you'll do just fine. | ||
By using **express-socket.io-session** you'll find these methods in `socket.handshake.session.get()` and `socket.handshake.session.save()` | ||
when handling an event. | ||
## API | ||
This module exports a middleware function for **socket.io**. | ||
This **sharedsession** function can be used with the `io.use()` method. | ||
var sharedsession = require("express-socket.io-session"); | ||
io.use(sharedsession(express_session)); | ||
**sharedsession( express_session_middleware, [cookieparser_instance] )** | ||
###sharedsession( express_session, [cookieparser], [options]) | ||
* `express_session_middleware` is **required** and must be an express middleware function created with the [express-session](https://www.npmjs.org/package/express-session) module that allows cookie-based sessions. | ||
* `cookieparser_instance` is optional. If you don't provide en instance created by [cookie-parser](https://www.npmjs.org/package/cookie-parser), this module creates one for you with defaults. | ||
* **express_session** - This parameter is **required** and must be an express middleware function created with the [express-session](https://www.npmjs.org/package/express-session) module that allows cookie-based sessions over Express. | ||
* **cookieparser** - Optional. If you don't provide en instance created by [cookie-parser](https://www.npmjs.org/package/cookie-parser), this module creates one for you with defaults. | ||
* **options** | ||
* **options.autoSave** - Boolean - If true, session will be autosaved if it has been modified | ||
inside your event handler. Default: `false`. | ||
@@ -140,0 +129,0 @@ ## Inspiration |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
17549
175
3
162
+ Addedcrc@^3.3.0
+ Addedbase64-js@1.5.1(transitive)
+ Addedbuffer@5.7.1(transitive)
+ Addedcrc@3.8.0(transitive)
+ Addedieee754@1.2.1(transitive)