1
votes

I am working with socket.io example for chat project. I want to add password protection to the chat application. This is just simple authentication. If user input wrong password, then server will disconnect this user.

Client side code:

var socket = io();
socket.emit('user name', username);
socket.emit('password', password);

Server side code:

socket.on('password', function (msg) {
    if (msg !== '123321') {
        io.emit('system info', 'Wrong password... Disconnecting ' + username+'...');
        io.close(true);
        return false;
    }
});

The close() method doesn't work. the disconnected user still able to receive message from other users. So how to do this properly? Thank you.

1

1 Answers

0
votes

Assuming you are creating an id (server side) with something like:

io.engine.generateId = (req) => {
    return custom_id++; // custom id must be unique
  }

You could close an specific connection using .disconnect() and you could call the id with socket.id

socket.on('password', function (msg) {
    if (msg !== '123321') {
        io.emit('system info', 'Wrong password... Disconnecting ' + username+'...');
        io.sockets.connected[socket.id].disconnect();//<-- in this case it's just a number 
    }
});