Mohammed
Mohammed

Reputation: 343

Sending Private Message ( Socket.IO )

In many Posts or Articles.I often saw something like that.

Client-Side :

 socket.emit("shhh!Secrets", {
  To : "AlexId",
  Message : "Hello World!"
 })
Server-Side: 

 socket.on("shhh!Secrets", (Send) => {
  io.in(Send.TO).emit("SO...Secrets", Send.Message)
 })

Whatever it is socketId , Specific user socketObj or room base .

What If I change Client Source code and change with others room or socketId then my crazy message will saved to others chat timeline...

Upvotes: 2

Views: 341

Answers (2)

Nur
Nur

Reputation: 2473

First Method

Socket.IO is stateful. So this Smart Socket will not forget who you are in every event call.

lets say user want to join room001
So when Joining a socket to a specific Room,Save RoomId To socket.roomId = "room001"

Then use io.in(socket.roomId).emit("SO...Secrets", "message")

Second Method

Never give a change a client directly send message to specific room.

Server-Side: 
  
 socket.on("shhh!Secrets", (Send) => {
  // Send message only if the user already joined to this Room
  if (Send instanceof Object && socket.rooms[Send.TO] === Send.TO) 
    io.in(Send.TO).emit("SO...Secrets", Send.Message);
 })

Upvotes: 3

Dmitriy K
Dmitriy K

Reputation: 36

Mohammed, of course you can change your client code, but you need to know real userId (AlexId in your example), and it is usually uuid, that is not easy to get... So there is very low chance to do that.

By the way, usually in articles use very simple examples and do not mention security aspects, so be careful with it!

Upvotes: 0

Related Questions