Skip to content

Commit

Permalink
corrige vazamento entre usuários
Browse files Browse the repository at this point in the history
  • Loading branch information
allgood committed Mar 12, 2024
1 parent e09caa4 commit 67494df
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 22 deletions.
14 changes: 10 additions & 4 deletions backend/src/controllers/TicketController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,13 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
const ticket = await CreateTicketService({ contactId, status, userId });

const io = getIO();
io.to(ticket.status).emit("ticket", {
action: "update",
ticket
});
// send status to the specific queue channel
io.to(ticket.status)
.to(`queue-${ticket.queueId}-${ticket.status}`)
.emit("ticket", {
action: "update",
ticket
});

return res.status(200).json(ticket);
};
Expand Down Expand Up @@ -119,9 +122,12 @@ export const remove = async (
const ticket = await DeleteTicketService(ticketId);

const io = getIO();
// send delete message to queues of ticket's current status
io.to(ticket.status)
.to(ticketId)
.to("notification")
.to(`queue-${ticket.queueId}-${ticket.status}`)
.to(`queue-${ticket.queueId}-notification`)
.emit("ticket", {
action: "delete",
ticketId: +ticketId
Expand Down
11 changes: 7 additions & 4 deletions backend/src/helpers/SetTicketMessagesAsRead.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,13 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
}

const io = getIO();
io.to(ticket.status).to("notification").emit("ticket", {
action: "updateUnread",
ticketId: ticket.id
});
io.to(ticket.status)
.to("notification")
.to(`queue-${ticket.queueId}-notification`)
.emit("ticket", {
action: "updateUnread",
ticketId: ticket.id
});
};

export default SetTicketMessagesAsRead;
71 changes: 62 additions & 9 deletions backend/src/libs/socket.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { Server as SocketIO } from "socket.io";
import { Server } from "http";
import { verify } from "jsonwebtoken";
import { JwtPayload, verify } from "jsonwebtoken";
import AppError from "../errors/AppError";
import { logger } from "../utils/logger";
import authConfig from "../config/auth";
import User from "../models/User";
import Queue from "../models/Queue";
import Ticket from "../models/Ticket";

let io: SocketIO;

Expand All @@ -14,38 +17,88 @@ export const initIO = (httpServer: Server): SocketIO => {
}
});

io.on("connection", socket => {
io.on("connection", async socket => {
const { token } = socket.handshake.query;
let tokenData = null;
try {
tokenData = verify(token, authConfig.secret);
tokenData = verify(token, authConfig.secret) as JwtPayload;
logger.debug(JSON.stringify(tokenData), "io-onConnection: tokenData");
} catch (error) {
logger.error(JSON.stringify(error), "Error decoding token");
socket.disconnect();
return io;
}

const userId = tokenData.id;

let user: User;
if (userId && userId !== "undefined" && userId !== "null") {
user = (await User.findByPk(userId, { include: [Queue] })) as User;
}

logger.info("Client Connected");
socket.on("joinChatBox", (ticketId: string) => {
logger.info("A client joined a ticket channel");
socket.join(ticketId);
if (ticketId === "undefined") {
return;
}
Ticket.findByPk(ticketId).then(
ticket => {
// only admin and the current user of the ticket
// can join the message channel of it.
if (
ticket &&
(ticket.userId === user.id || user.profile === "admin")
) {
logger.debug(`User ${user.id} joined ticket ${ticketId} channel`);
socket.join(ticketId);
} else {
logger.info(
`Invalid attempt to join chanel of ticket ${ticketId} by user ${user.id}`
);
}
},
error => {
logger.error(error, `Error fetching ticket ${ticketId}`);
}
);
});

socket.on("joinNotification", () => {
logger.info("A client joined notification channel");
socket.join("notification");
if (user.profile === "admin") {
// admin can join all notifications
logger.debug(`Admin ${user.id} joined the notification channel.`);
socket.join("notification");
} else {
// normal users join notifications of the queues they participate
user.queues.forEach(queue => {
logger.debug(`User ${user.id} joined queue ${queue.id} channel.`);
socket.join(`queue-${queue.id}-notification`);
});
}
});

socket.on("joinTickets", (status: string) => {
logger.info(`A client joined to ${status} tickets channel.`);
socket.join(status);
if (user.profile === "admin") {
// only admin can join the notifications of a particular status
logger.debug(`Admin ${user.id} joined ${status} tickets channel.`);
socket.join(`${status}`);
} else {
// normal users can only receive messages of the queues they participate
user.queues.forEach(queue => {
logger.debug(
`User ${user.id} joined queue ${queue.id} ${status} tickets channel.`
);
socket.join(`queue-${queue.id}-${status}`);
});
}
});

socket.on("disconnect", () => {
logger.info("Client disconnected");
});

socket.emit("ready");

return socket;
});
return io;
Expand Down
3 changes: 3 additions & 0 deletions backend/src/services/MessageServices/CreateMessageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ const CreateMessageService = async ({
io.to(message.ticketId.toString())
.to(message.ticket.status)
.to("notification")
// send message to specific queues
.to(`queue-${message.ticket.queueId}-${message.ticket.status}`)
.to(`queue-${message.ticket.queueId}-notification`)
.emit("appMessage", {
action: "create",
message,
Expand Down
5 changes: 4 additions & 1 deletion backend/src/services/TicketServices/UpdateTicketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const UpdateTicketService = async ({
const io = getIO();

if (ticket.status !== oldStatus || ticket.user?.id !== oldUserId) {
io.to(oldStatus).emit("ticket", {
io.to(oldStatus).to(`queue-${ticket.queueId}-${oldStatus}`).emit("ticket", {
action: "delete",
ticketId: ticket.id
});
Expand All @@ -73,6 +73,9 @@ const UpdateTicketService = async ({
io.to(ticket.status)
.to("notification")
.to(ticketId.toString())
// send queue specific messages
.to(`queue-${ticket.queueId}-${ticket.status}`)
.to(`queue-${ticket.queueId}-notification`)
.emit("ticket", {
action: "update",
ticket
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/MessagesList/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ const MessagesList = ({ ticketId, isGroup }) => {
useEffect(() => {
const socket = openSocket();

socket.on("connect", () => socket.emit("joinChatBox", ticketId));
socket.on("ready", () => socket.emit("joinChatBox", ticketId));

socket.on("appMessage", (data) => {
if (data.action === "create") {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/NotificationsPopOver/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ const NotificationsPopOver = () => {
useEffect(() => {
const socket = openSocket();

socket.on("connect", () => socket.emit("joinNotification"));
socket.on("ready", () => socket.emit("joinNotification"));

socket.on("ticket", data => {
if (data.action === "updateUnread" || data.action === "delete") {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Ticket/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ const Ticket = () => {
useEffect(() => {
const socket = openSocket();

socket.on("connect", () => socket.emit("joinChatBox", ticketId));
socket.on("ready", () => socket.emit("joinChatBox", ticketId));

socket.on("ticket", (data) => {
if (data.action === "update") {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/TicketsList/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ const reducer = (state, action) => {
const notBelongsToUserQueues = ticket =>
ticket.queueId && selectedQueueIds.indexOf(ticket.queueId) === -1;

socket.on("connect", () => {
socket.on("ready", () => {
if (status) {
socket.emit("joinTickets", status);
} else {
Expand Down

0 comments on commit 67494df

Please sign in to comment.