Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Socket.IO connects with the jwt token #321

Merged
merged 5 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion components/rooms/RoomChatroom/RoomChatroom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default function RoomChatroom({ roomId }: RoomChatroom) {
if (!socket || !socket.connected) return;
joinChatroom(roomId);
return () => leaveChatroom(roomId);
}, [joinChatroom, leaveChatroom, roomId, socket, socket.connected]);
}, [joinChatroom, leaveChatroom, roomId, socket, socket?.connected]);

// update message list while received new message from websocket
useEffect(() => {
Expand Down
41 changes: 25 additions & 16 deletions containers/provider/SocketProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
import React, { useEffect, FC, useCallback } from "react";
import SocketContext, { socket, SOCKET_EVENT } from "@/contexts/SocketContext";
import React, { useEffect, FC, useState } from "react";
import SocketContext, {
SOCKET_EVENT,
createSocket,
} from "@/contexts/SocketContext";
import useAuth from "@/hooks/context/useAuth";
import useHistory from "@/hooks/context/useHistory";
import { WebSocketHistoryType } from "@/contexts/HistoryContext";
import { Socket } from "socket.io-client";

type Props = {
children: React.ReactNode;
};

export const SocketProvider: FC<Props> = ({ children }) => {
const { addWsHistory } = useHistory();
const { currentUser } = useAuth();
const { currentUser, token } = useAuth();
const [socket, setSocket] = useState<Socket | null>(null);

const connect = useCallback(() => {
if (socket?.connected) return;
socket.connect();
}, []);

const disconnect = useCallback(() => {
if (!socket?.connected) return;
socket.disconnect();
}, []);
useEffect(() => {
setSocket(createSocket(token));
}, [token]);

useEffect(() => {
socket
.on(SOCKET_EVENT.CONNECT, () => {
?.on(SOCKET_EVENT.CONNECT, () => {
addWsHistory({
type: WebSocketHistoryType.CONNECTION,
event: "CONNECT",
Expand Down Expand Up @@ -55,22 +54,32 @@ export const SocketProvider: FC<Props> = ({ children }) => {

return () => {
socket
.off(SOCKET_EVENT.CONNECT)
?.off(SOCKET_EVENT.CONNECT)
.offAny()
.offAnyOutgoing()
.off(SOCKET_EVENT.DISCONNECT);
};
}, [addWsHistory]);
}, [socket, addWsHistory]);

useEffect(() => {
const connect = () => {
if (socket?.connected) return;
socket?.connect();
};

const disconnect = () => {
if (!socket?.connected) return;
socket.disconnect();
};

if (!currentUser) return;
window.addEventListener("beforeunload", disconnect);
connect();
return () => {
window.removeEventListener("beforeunload", disconnect);
disconnect();
};
}, [connect, disconnect, currentUser]);
}, [socket, currentUser]);

return (
<SocketContext.Provider value={{ socket }}>
Expand Down
16 changes: 10 additions & 6 deletions contexts/SocketContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ import { Env, getEnv } from "@/lib/env";
import { createContext } from "react";
import { Socket, io } from "socket.io-client";

type StoreContextType = {
socket: Socket;
};

const { internalEndpoint, env } = getEnv();

export const SOCKET_URL = "/api/internal/socketio";
Expand Down Expand Up @@ -45,8 +41,16 @@ export enum SOCKET_EVENT {
ROOM_CLOSED = "ROOM_CLOSED",
}

export const socket = io(internalEndpoint, config);
export const createSocket = (token: string | null | undefined) => {
return io(internalEndpoint, { auth: { token }, ...config });
};

type StoreContextType = {
socket: Socket | null;
};

const SocketContext = createContext<StoreContextType>({ socket });
const SocketContext = createContext<StoreContextType>({
socket: null,
});

export default SocketContext;
13 changes: 13 additions & 0 deletions pages/api/mock/socketio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ const onlineUsers = new Map<string, string>();
let isEmitting = false;
let sendOnlineUsers: NodeJS.Timeout;

function registeringMiddleware(io: ServerIO) {
io.use((socket, next) => {
const token = socket.handshake.auth.token;
if (token == undefined) {
next(new Error("not authorized"));
} else {
next();
}
});
}

const socketio = async (req: NextApiRequest, res: NextApiResponseServerIO) => {
if (!res.socket.server.io) {
// eslint-disable-next-line no-console
Expand All @@ -32,6 +43,8 @@ const socketio = async (req: NextApiRequest, res: NextApiResponseServerIO) => {
addTrailingSlash: false,
});

registeringMiddleware(io);

io.on(SOCKET_EVENT.CONNECT, (socket) => {
// eslint-disable-next-line no-console
console.log("SOCKET CONNECTED IN SERVER! ", socket.id);
Expand Down