Skip to content

Commit

Permalink
Autenticando o Websocket com token
Browse files Browse the repository at this point in the history
  • Loading branch information
rtenorioh committed Oct 25, 2024
1 parent 980be20 commit cbada47
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
15 changes: 14 additions & 1 deletion backend/src/libs/socket.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Server as SocketIO } from "socket.io";
import { Server } from "http";
import { verify } from "jsonwebtoken";
import { Server as SocketIO } from "socket.io";
import authConfig from "../config/auth";
import AppError from "../errors/AppError";
import { logger } from "../utils/logger";

Expand All @@ -13,6 +15,16 @@ export const initIO = (httpServer: Server): SocketIO => {
});

io.on("connection", socket => {
const { token } = socket.handshake.query;
let tokenData = null;
try {
tokenData = verify(token, authConfig.secret);
logger.debug(JSON.stringify(tokenData), "io-onConnection: tokenData");
} catch (error) {
logger.error(JSON.stringify(error), "Error decoding token");
socket.disconnect();
return io;
}
logger.info("Client Connected");
socket.on("joinChatBox", (ticketId: string) => {
logger.info("A client joined a ticket channel");
Expand All @@ -32,6 +44,7 @@ export const initIO = (httpServer: Server): SocketIO => {
socket.on("disconnect", () => {
logger.info("Client disconnected");
});
return socket;
});
return io;
};
Expand Down
8 changes: 7 additions & 1 deletion frontend/src/services/socket-io.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ import openSocket from "socket.io-client";
import { getBackendUrl } from "../config";

function connectToSocket() {
return openSocket(getBackendUrl());
const token = localStorage.getItem("token");
return openSocket(getBackendUrl(), {
transports: ["websocket", "polling", "flashsocket"],
query: {
token: JSON.parse(token),
},
});
}

export default connectToSocket;

0 comments on commit cbada47

Please sign in to comment.