I am running my server in node.js language and i am using express module, how can i prevent the client from opening more than one instance of my web site
Since most server-side techniques don't scale because they require you to hold state server-side, I'd go with a client-side approach. You could communicate between windows using cookies, and make sure only one client "owns" the cookie at any given time. Maybe use something like the Raft Consensus Algorithm to pick which window is the active one, then have the other display "Multiple sessions not allowed."
Here is one way to handle making sure only one authenticated socket per user is allowed at a time.
var socketSessions = {};
io.use(function(socket, next) {
var request = {
url: socket.request.url,
headers: {
cookie: socket.request.headers.cookie
}
}
cookieParser(request, {}, function(err) {
if(err) {
return next(err);
}
expressSession(sessionSettings)(request, {}, function(err) {
if(err) {
return next(err);
}
socket.session = request.session;
if(socketSessions[request.session.userId]) {
var oldSocket = socketSessions[request.session.userId];
oldSocket.disconnect();
}
socketSessions[request.session.userId] = socket;
next();
});
});
});
Assumptions for the code above: 1. You're using Express. 2. You're using cookie-parser and express-session. 3. your authentication mechanism creates a session.userId
This creates a socket.io middleware which maps a session to a socket. If a new socket connection comes in for a user, we disconnect the other socket, and then create a new socket/session map.