GGlowcode
GGlowcode

Reputation: 53

How to prevent empty messages from being sent

I'm making a simple React chat with Fairbase. I am not strong in this and therefore I have such a situation that if I do not display anything in niput and press enter, then I will send an empty message.

My code messages

I removed the code with the insertion of the picture so that it was smaller, so this is "url" and the "img" was for a images

 const selectUser = async (user) => {
setChat(user);

const user2 = user.uid;
const id = user1 > user2 ? `${user1 + user2}` : `${user2 + user1}`;

const msgsRef = collection(db, "messages", id, "chat");
const q = query(msgsRef, orderBy("createdAt", "asc"));

onSnapshot(q, (querySnapshot) => {
  let msgs = [];
  querySnapshot.forEach((doc) => {
    msgs.push(doc.data());
  });

const docSnap = await getDoc(doc(db, "lastMsg", id));
if (docSnap.data() && docSnap.data().from !== user1) {
  await updateDoc(doc(db, "lastMsg", id), { unread: false });
 }
};

await addDoc(collection(db, "messages", id, "chat"), {
  text,
  from: user1,
  to: user2,
  createdAt: Timestamp.fromDate(new Date()),
  media: url || "",
});

await setDoc(doc(db, "lastMsg", id), {
  text,
  from: user1,
  to: user2,
  createdAt: Timestamp.fromDate(new Date()),
  media: url  || "",
  unread: true,
  });

setText("");
setImg("");
 };

And my component Messeges

    const Message = ({ msg, user1 }) => {
    const scrollRef = useRef();

    useEffect(() => {
        scrollRef.current?.scrollIntoView({ behavior: "smooth" });
     }, [msg]);

     return (
        <div
           className={`message_wrapper ${msg.from === user1 ? "own" : ""}`}
           ref={scrollRef}
        >
            <p className={msg.from === user1 ? "me" : "friend"}>
            {msg.media ? <img src={msg.media} alt={msg.text} /> : null}
            {msg.text}
            <br />
            <small>
                <Moment fromNow>{msg.createdAt.toDate()}</Moment>
                </small>
             </p>
         </div> 
      );
   };

Upvotes: 2

Views: 666

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

You can implement several mechanisms in your front-end, like:

  • "Disabling the send button if the length of your message is 0" (from Anuj Kumar's comment above)
  • Display an error message if the length of your message is 0, like a dialog box.

but what is more important is to implement a check in the back-end, because a malicious user could easily bypass your code and directly write to your database, for example by using the Firestore REST API.

For that you would use some security rules along the following lines:

// ....
match /messages/{message} {
  allow create: if request.resource.data.text is string
  && request.resource.data.text.size() > 0;
  allow read: if ...;
  allow update: if ...;
  allow delete: if ...;
}

You'll find here in the doc more details on the methods you can apply to a String in security rules.

Upvotes: 3

Related Questions