Custom auth system with socket.io and mongodb - Your thoughts?

Hello JS community,

I have many requests with socket.io that go FE to BE to FE. Classic way for auth is to use JWT, but I have a different idea in mind.

So whenever a user connects to the web page (game), they are given a unique socket id, which is the same on FE and BE. So upon logging in, I can save that users socket.id inside his mongodb collection.

With JWT, I would do something like this:

// FE
socket.emit("saveDeck", {token, deck});

// BE
socket.on("saveDeck", ({token, deck}) => {  
  const {username} = JWT.verify(token);
  const user = await mongo.collection("players").updateOne({username}, {deck});
});

Something like this. I simplified it a lot but I hope you get the idea.

Since I'm saving the socket.id in the players collection, I could reduce the steps and write the code like this:

// FE
socket.emit("saveDeck", {deck});

// BE
socket.on("saveDeck", ({deck}) => {
  const socketId = socket.id;
  const user = await mongo.collection("players").updateOne({socketId}, {deck});
});

Since every time a player logs in, his socketId would be updated in the database, and I tried this method and it "works" as expected.

My question is regarding security. Is there any loopholes here, anyone else doing this and what are your thoughts on this approach? One downside I have currently is, player is always required to login upon visiting the game, since his socketId always needs to be updated when the page is opened / refreshed. The upside is of course less code and cleaner code.

Looking forward for your opinions!

Thanks!

Posted Dec 2, 2021, 6:09 PM UTC

10
Loading comments…