I am using a middleware that validates JWT token from
socket.handshake.auth.token
After the token is validated I add the user in the socket variable like this
socket.user = user
I have a function that fetches all connected users using the io variable.
const getAllUsers = () => {
const connectedSockets = Array.from(io.sockets.sockets.values());
const connectedUsers = connectedSockets.map((socket) => socket.user);
console.log(connectedUsers);
return connectedUsers;
};
But the problem is that I cannot access this io variable in my middleware. The middleware only has access to a socket and next variable. Is there a way I can access the io variable in my middleware. Or get all connected sockets in any other way?
PURPOSE:
I want to see if the same user is trying to connect with a different socket. And if he is, block the connection. Therefore I need array of all connected users.
Is there any other way to implement this logic without a middleware?
MIDDLEWARE
const protectSocket = async (socket, next) => {
const token =
socket.handshake.auth.token;
if (token) {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
//get user from token
socket.user = await User.findById(decoded.id).select("-password");
return next();
} catch (err) {
console.log(err);
return next(new Error(err));
}
} else {
return next(new Error("Token is missing"));
}