verifying if user is member of conversation before joining

This commit is contained in:
slawk0
2024-12-14 22:37:29 +01:00
parent 3efd536db6
commit 9a0f8c6de6
5 changed files with 104 additions and 24 deletions

View File

@@ -990,6 +990,28 @@ async function removeUserFromGroupById(conversation_id, user_id) {
}
}
async function isConversationMember(user_id, conversation_id) {
const query = `
SELECT EXISTS (
SELECT 1
FROM Memberships
WHERE user_id = $1
AND conversation_id = $2
) AS is_member;
`;
try {
const result = await client.query(query, [user_id, conversation_id]);
return result.rows[0].is_member;
} catch (e) {
console.error(
`Failed to verify membership for user_id: ${user_id} in conversation_id: ${conversation_id}`,
e,
);
return false;
}
}
module.exports = {
client,
insertUser,
@@ -1010,4 +1032,5 @@ module.exports = {
deleteMessage,
getMembers,
removeUserFromGroupById,
isConversationMember,
};

View File

@@ -4,6 +4,7 @@ const {
deleteContact,
deleteMessage,
removeUserFromGroupById,
isConversationMember,
} = require("../db/db");
const { isValidUsername } = require("../utils/filter");
const { verifyJwtToken } = require("../auth/jwt");
@@ -76,9 +77,24 @@ function initializeSocket(io) {
console.error("(socket) Failed to get user conversations");
}
socket.on("join room", (msg) => {
console.log("Join room for: ", username, "room: ", msg);
socket.join(msg);
socket.on("join room", async (conversation_id, callback) => {
const isMember = await isConversationMember(
socket.user_id,
conversation_id,
);
if (isMember) {
console.log("Join room for: ", username, "room: ", conversation_id);
socket.join(conversation_id);
return callback({
status: "ok",
message: "Successfully joined to conversation",
});
} else {
return callback({
status: "error",
message: "You are not member of this conversation",
});
}
});
socket.on("chat message", async (msg, callback) => {