Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js chat - user authentication

I've recently set up a nodejs chat server, the chat client is served by a php server. When users log in, their sessions will be stored in mysql of the php server, and a login cookie will append to browser.

I want to restrict users that only logged in users are able to chat. What is the best practice to archieve that ?

My quick thought:

When the chat client loaded, if user logged in, I'll send the login cookie information to nodejs verver via socket. Then create a nodejs session. When user chat, the message together with cookie information will be sent to nodejs server via socket. If the cookie information does not match the nodejs session, the message will not be broadcasted and client socket will be disconected.

like image 898
angry kiwi Avatar asked Apr 21 '11 08:04

angry kiwi


1 Answers

A websocket is a permanent open connection. You only need to autheticate once when you connect to the websocket.

Simply send your login cookie to node.js once and store it on the server with a reference to the socket connection. Then only handle messages from authenticated users and only broadcast to authenticated users.

The problem is that client side users can easily fake this cookie as node does not talk to php to ensure that it's a valid login cookie.

An example using now.

warning pseudo code

// server.js
everyone.now.joinChat = function(cookie) {
    chat.add(this, cookie);
}

everyone.now.serverMessage = function(message) {
    if (chat.hasUser(this)) {
        chat.broadcast(message);
    }
}

chat = (function() {
    var users = [];

    return {
         "add": function(client) {
             users.push(client);
         },
         "hasUser": function(client) {
             return users.some(function(user) {
                 return user === client;
             });
         },
         "broadcast": function(message) {
              users.each(function(user) {
                  user.clientMessage(message);
              });
         }
    }
}());

// client.js
$(function() {
    now.joinChat($.cookie("login"));

    $("#send").click(function() {
         now.serverMessage($(this).data("message"));
    });

    now.clientMessage = function(message) {
         $("#messages").append($("<span></span>").text(message));
    }

});
like image 166
Raynos Avatar answered Oct 21 '22 17:10

Raynos