Node.js login to Express for Socket.io

Place to place any code snippets, completed games, or even uncompleted games for IR users to use.
Post Reply
User avatar
Jackolantern
Posts: 10893
Joined: Wed Jul 01, 2009 11:00 pm

Node.js login to Express for Socket.io

Post by Jackolantern »

I figured I would put this up here, as it seems to work pretty well. The login system is very naive, as it has no hashing of passwords and no SSL/TSL (that is today's work), but the login really isn't the important part. The important part is the "authentication" event, the treatment of the handshake data, the usage of the MemoryStore inside socket.io to get the session data, and bringing it all together to create a single Express/Socket.io login system. It also demonstrates how to keep track of users so you can send private messages and handle disconnections. Also it uses MongoDB using the regular MongoDB node driver.

Here is the Github page. The main files of interest are app.js and, in the routes folder, login.js. Most of the server-side logic is kept there. There is also a handful of view EJS files, and a client-side JS file, sock.js.
The indelible lord of tl;dr
User avatar
kaos78414
Posts: 507
Joined: Thu Jul 22, 2010 5:36 am

Re: Node.js login to Express for Socket.io

Post by kaos78414 »

This looks great man. For a good blowfish encryption, you could couple it with this package: https://npmjs.org/package/bcrypt-nodejs

Also note that if for some reason you need to use PHP or Rails alongside node, that encryption method is compatible with Rails' Devise gem, and PHP's crypt method, so for instance if you needed to encrypt in PHP you could use the below method, and then validate it in node or vice versa. Probably worthless info, but figured I'd share anyway.

Code: Select all

    /**
     * Blowfish encrypt a password
     * @param type $password
     * @param type $cost
     * @return type
     */
    private function blowfishCrypt($password, $cost)
    {
        $chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $salt=sprintf('$2a$%02d$',$cost);
        mt_srand();
        for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
        return crypt($password,$salt);
    }

    //check this using crypt($password, $hash);
    //returns true if the password matches
w00t
User avatar
Jackolantern
Posts: 10893
Joined: Wed Jul 01, 2009 11:00 pm

Re: Node.js login to Express for Socket.io

Post by Jackolantern »

I have hashing working on my actual game, but this was more of a test of the 'authorize' event. Every example I found online didn't work. Some of them looked like they worked, but it would keep the cookie functioning even when they shouldn't allowing easy and erroneous re-login to the sockets. That is when I finally had to use the memoryStore. But you can use the accept() callback pretty much any way you want.
The indelible lord of tl;dr
Post Reply

Return to “Code Sharing”