Search code examples
node.jswebsocketsocket.iopassport.jspassport-local

Serve/Stop serve Socket.IO


Im wondering how can I serve socket.io only for logged users?

for now Im just adding/removing

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io();
</script>

but when I remove it after successful session, page is not loading. Any idea for using/serving socket.io only for users with passport session authentication?


Solution

  • The true answer here is to use the so called handshake of the SocketIO framework. It allows you to do some checks and decide if you should allow the user to connect to your server or not. The other answers around simply don't automatically allow the user to connect. But if he only opens a console and instantiates socket against your server - he's online.

    Check this out: http://socket.io/docs/server-api/#namespace#use(fn:function):namespace

    On each connection attempt, you can run a specific function to see if things are okay or not. You can then decline the connection (calling next with a parameter), or accept it - just call next.

    And that's it :)

    But here comes the tricky part - how to actually authenticate the user? Each socket is instantiated with a simple HTTP request from the client. It's later on upgraded to a socket connection.

    If you are using some kind of database or a session, you can use one of the many modules out there. I've been using passport, so everything happens automatically. Here's more info about how to do it: https://github.com/jfromaniello/passport.socketio

    var io           = require("socket.io")(server),
    sessionStore     = require('awesomeSessionStore'), // find a working session store (have a look at the readme)
    passportSocketIo = require("passport.socketio");
    
    io.use(passportSocketIo.authorize({
        cookieParser: cookieParser,       // the same middleware you registrer in express
        key:          'express.sid',       // the name of the cookie where express/connect stores its session_id
        secret:       'session_secret',    // the session_secret to parse the cookie
        store:        sessionStore,        // we NEED to use a sessionstore. no memorystore please
        success:      onAuthorizeSuccess,  // *optional* callback on success - read more below
        fail:         onAuthorizeFail,     // *optional* callback on fail/error - read more below
    }));
    
    function onAuthorizeSuccess(data, accept){
        console.log('successful connection to socket.io');
    
        // The accept-callback still allows us to decide whether to
        // accept the connection or not.
        accept(null, true);
    
        // OR
    
        // If you use socket.io@1.X the callback looks different
        accept();
    }
    
    function onAuthorizeFail(data, message, error, accept){
        if(error)
            throw new Error(message);
        console.log('failed connection to socket.io:', message);
    
        // We use this callback to log all of our failed connections.
        accept(null, false);
    
        // OR
    
        // If you use socket.io@1.X the callback looks different
        // If you don't want to accept the connection
        if(error)
            accept(new Error(message));
        // this error will be sent to the user as a special error-package
        // see: http://socket.io/docs/client-api/#socket > error-object
    }