1

I'm working with mean.js and I need to have some real time features in my app, to accomplish that I'm going to use socket.io library. Here is my idea on how to integrate and still have a good structure in the app.

Mean is using a server.js file, that is the one that do a lot of configurations, so I want to do the following:

// Expose app
exports = module.exports = app;

// Add my reference to the socketServer
var io = require('/socketServer')(app);

The file '/socketServer.js' is going to be my starting point and my configuration point of my socket, could looks something like this:

var http = require('http');
var socketio = require('socket.io');

module.exports = function(express){
    var server = http.Server(express);
    var io = socketio(server);
    io.path('/');
    io.on('connect', function(socket){
        socket.emit('connected', {msg: 'You are connected now.'});
        socket.on('upvote', function(data){

            socket.emit('upvoteR', 'newConnected');
            socket.broadcast.emit('upvoteR', 'newCOnnected');
        });
    });
    server.listen(8080);
    return io;
};

I feel like could be useful for me separate the server default config, of my socket config, and use it file (socketServer.js) as my starting point to develop all my sockets logics injecting the dependencies I want. I don't know if is out there a better approach to this problem, or some structure best practices that I should follow or inconveniences of doing this.

So besides this structure, this are other doubts:

  • How to use sockets and express server in the same port? Seems like, with express 4 I'm not able to link the express server with socket, because express 4 server does not inherit any more of httpServer of node.js, so now I have to do a server.listen(socketPort) and if I use the same app.port of mean.js this just is an EADDRINUSE error. Is still possible to have it working in the same port ?
  • How to use express session to authenticate each socket connection? if not possible, what's the better approach ? An example or a document reference would be nice for me.

thanks in advance.

rahpuser
  • 1,224
  • 10
  • 31
  • socket.io 1.0 works nicely with Express 4: http://socket.io/docs/#using-with-express-3/4 – Oleg Jun 10 '14 at 17:33
  • ops.. yeah sorry I didn't realize I forgot to comment the app.listen(config.port) of mean server ( server.js ) that's why I was getting EDDRAUNISE error, sorry about that. thanks, still I would like to know if I could use express sessions and let the security to express. Thanks a lot.. – rahpuser Jun 10 '14 at 17:42
  • It's ok :D Honestly I don't have any experience with socket.io+Express shared sessions, but I think [this code snippet](https://gist.github.com/bminer/1213036) would be helpful to you. But it might be a bit outdated (not compatible with socket.io 1.0 and Express 4). – Oleg Jun 10 '14 at 17:48
  • agree, seems to be out of date ( 3 years right ? ), but yes, this could be useful for me,I'm going to take a look on this code, maybe I could find the way studying a last version of what I want, thanks a lot. – rahpuser Jun 10 '14 at 18:13
  • Have you looked at `express.io`? – Josh C. Jun 24 '14 at 14:36
  • Also, if you are using passport.js, checkout `passport.socketio`. – Josh C. Jun 24 '14 at 14:57
  • Intesresting, yes I looked at express.io, gonna look about passport.socketio, thanks – rahpuser Jun 24 '14 at 16:06

1 Answers1

0

I would like to share my solution just in case someone in the future has the same requirement that I had.

How to authenticate each socket connection base on express session information.

First I configure express to use passport.js library the following way:

// CookieParser should be above session
    var cp =cookieParser;
    app.use(cp());

    // Express MongoDB session storage
    var mStore = new mongoStore({
            db: db.connection.db,
            collection: config.sessionCollection
        });

    app.use(session({
        secret: config.sessionSecret,
        store: mStore
    }));

    // use passport session
    app.use(passport.initialize());
    app.use(passport.session());

So far is the normal implementation of passport over express. be sides this configuration I added passport-socket.io.js to my project. This is my working configuration:

var server = http.Server(app);
    var io = IO(server);

    io.use(
        function(socket,next){
            passportSocketIo.authorize({
                cookieParser: cp,
                key:         'connect.sid',             // the name of the express cookie 
                secret:      config.sessionSecret,      // the session_secret to parse the cookie
                store:       mStore,                    // mongo session storage
                success:     onAuthorizeSuccess,        // *optional* callback on success
                fail:        onAuthorizeFail,           // *optional* callback on fail/error
            })(socket, next);
        }
    );
    app.io=io;
    server.listen(config.port);

Where "onAuthorizeSuccess" and "onAuthorizeFail" are functions to allow the conections and develop the sockets logics.. well,with this my socket.io connection is authenticated with my passport session information and if the user is not logged the socket would not connect..

And if we need some authorization logic based on user roles, the passport.socketio creates a socket.request.user where you can find yours users roles to use in your roles sockets logics..

rahpuser
  • 1,224
  • 10
  • 31