Skip to content

Instantly share code, notes, and snippets.

@weikinhuang
Created August 7, 2014 19:35
Show Gist options
  • Save weikinhuang/5509563c6cdbe4ba1c5e to your computer and use it in GitHub Desktop.
Save weikinhuang/5509563c6cdbe4ba1c5e to your computer and use it in GitHub Desktop.
Express 4 and socket.io share sessions
var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var session = require("express-session");
var cookie = require("cookie");
var q = require("q");
var routes = require("./routes/index");
var users = require("./routes/users");
var app = express();
var sessionStore = new session.MemoryStore();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(cookieParser());
app.use(session({
name : "connect.sid",
secret : "abc123",
cookie : {
httpOnly : true
},
saveUninitialized : true,
resave : true,
store : sessionStore
}));
app.use(express.static(path.join(__dirname, "public")));
app.use("/", routes);
app.use("/users", users);
app.use("/abc", function(req, res, next) {
req.session.views = (req.session.views || 0) + 1;
res.end(JSON.stringify({
data : "abc"
}));
});
// / catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// / error handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
app.use(function(err, req, res, next) {
res.render("error", {
message : err.message,
error : err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.render("error", {
message : err.message,
error : {}
});
});
var server = require("http").Server(app);
var io = require("socket.io")(server);
module.exports = server;
server.listen(process.env.PORT || 3000, function() {
console.log("Server listening on port " + (process.env.PORT || 3000));
});
// THIS IS THE PARSER!
function getSession(socket) {
var defer = q.defer();
var signedCookies,
parsedCookies = cookie.parse(socket.handshake.headers.cookie);
signedCookies = cookieParser.signedCookies(parsedCookies, "abc123");
signedCookies = cookieParser.JSONCookies(signedCookies);
sessionStore.get(signedCookies["connect.sid"], function(err, sess) {
if (err || !sess) {
defer.reject(err);
return;
}
defer.resolve(sess);
});
return defer.promise;
}
// testing...
io.of("/test").on("connection", function(socket) {
socket.on("message", function(data) {
getSession(socket).then(console.log);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment