Skip to content

Instantly share code, notes, and snippets.

@nnarhinen nnarhinen/app.js
Last active Dec 21, 2015

Embed
What would you like to do?
Automatically join sockets to user-specific rooms using express.js sessions and socket.io
/**
* Module dependencies.
*/
var express = require('express'),
http = require('http'),
RedisStore = require('connect-redis')(express),
redis = require('redis'),
cookie = require('cookie'),
connect = require('connect'),
app = express(),
redisClient = redis.createClient(),
sessionStore = new RedisStore({client: redisClient}),
io;
app.configure(function(){
app.set('port', process.env.PORT || 3010);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({store: sessionStore, secret: 'my_secret', key: 'myapp.sid'}));
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io = require('socket.io').listen(server);
io.set('authorization', function (handshakeData, accept) {
if (handshakeData.headers.cookie) {
var handshakeCookie = cookie.parse(handshakeData.headers.cookie);
var sessionId = connect.utils.parseSignedCookie(handshakeCookie['myapp.sid'], 'my_secret');
if (!sessionId) {
return accept(new Error('Invalid cookie.'), false);
}
sessionStore.get(sessionId, function(err, data) { // Get user id set by req.session.userId = '<userid>'
if (err) return accept(new Error('Unable to find session'), false);
handshakeData.userId = data.userId;
accept(null, true);
});
} else {
return accept(new Error('No cookie available.'), false);
}
});
io.sockets.on('connection', function(socket) {
socket.join(socket.handshake.userId);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.