Created
January 25, 2015 22:17
-
-
Save grofit/8c202a5e1589a36378a3 to your computer and use it in GitHub Desktop.
SocketIO + Passport + Cookie-Sessions
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
/* | |
This is just a hacky approach to get things moving, as passport-socketio library | |
does not support cookie-sessions. | |
*/ | |
var Promise = require("bluebird"); | |
var passport = require("passport"); | |
var session = require("cookie-session"); | |
var sessionConfig = { | |
secret: "secret-goes-here", | |
resave: false, | |
saveUninitialized: true, | |
name: "cookie-name-goes-here", | |
signed: true | |
}; | |
var configuredSessionMiddleware = session(sessionConfig); | |
var parseCookieSession = function(socket) { | |
var dummyRequest = { | |
headers: { | |
cookie: socket.request.headers.cookie || '' | |
} | |
}; | |
var dummyResponse = {}; | |
return new Promise(function(resolve, reject){ | |
var passportProperty = passport._key; | |
var userProperty = passport._userProperty; | |
configuredSessionMiddleware(dummyRequest, dummyResponse, function(error){ | |
if(error) { return reject(error); } | |
if(!dummyRequest.session[passportProperty]) { return reject("Authentication data not provided"); } | |
if(!dummyRequest.session[passportProperty][userProperty]) { return reject("User data not provided"); } | |
var userId = dummyRequest.session[passportProperty][userProperty]; | |
return resolve(userId); | |
}); | |
}); | |
}; | |
var getUserData = function(userId) { | |
return new Promise(function(resolve, reject){ | |
passport.deserializeUser(userId, function(err, user) { | |
if (err) { return reject(err);} | |
if (!user) { return reject("User not found"); } | |
resolve(user); | |
}); | |
}); | |
}; | |
var assignUserToSocket = function(socket, user) | |
{ socket.request.user = user; }; | |
module.exports = function(socket, next) { | |
Promise.resolve(socket) | |
.then(parseCookieSession) | |
.then(getUserData) | |
.then(function(user) { | |
assignUserToSocket(socket, user); | |
}) | |
.then(function() { next(); }) | |
.catch(function(error){ | |
next(new Error('unable to authorise')); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment