Skip to content

Commit

Permalink
autentica websocket usando token
Browse files Browse the repository at this point in the history
  • Loading branch information
allgood committed Mar 12, 2024
1 parent 27738c8 commit e09caa4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
15 changes: 15 additions & 0 deletions backend/src/libs/socket.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Server as SocketIO } from "socket.io";
import { Server } from "http";
import { verify } from "jsonwebtoken";
import AppError from "../errors/AppError";
import { logger } from "../utils/logger";
import authConfig from "../config/auth";

let io: SocketIO;

Expand All @@ -13,6 +15,17 @@ 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 +45,8 @@ 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 e09caa4

Please sign in to comment.