Skip to content

Commit

Permalink
Merge pull request #144 from Gamegoo-repo/feat/#129
Browse files Browse the repository at this point in the history
[Feat] jwt 재발급토큰 소켓서버 반영
  • Loading branch information
yyypearl authored Oct 19, 2024
2 parents e9c104d + 79f3661 commit ca452bc
Show file tree
Hide file tree
Showing 12 changed files with 83 additions and 31 deletions.
2 changes: 1 addition & 1 deletion src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import styled, { ThemeProvider } from "styled-components";
import { theme } from "@/styles/theme";
import Header from "@/components/common/Header";
import StyledComponentsRegistry from "@/libs/registry";
import { use, useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { Provider } from "react-redux";
import { AppStore, store } from "@/redux/store";
import { usePathname } from "next/navigation";
Expand Down
26 changes: 15 additions & 11 deletions src/components/chat/MessageHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,23 @@ const MessageHeader = (props: MessageHeaderProps) => {
>
{chatEnterData.gameName}
</UserName>
{onlineFriends.includes(chatEnterData.memberId) ? (
{chatEnterData?.friend &&
<>
<OnlineStatus>온라인</OnlineStatus>
<OnlineImage
src="/assets/icons/online.svg"
width={5}
height={5}
alt="온라인"
/>
{onlineFriends.includes(chatEnterData.memberId) ? (
<>
<OnlineStatus>온라인</OnlineStatus>
<OnlineImage
src="/assets/icons/online.svg"
width={5}
height={5}
alt="온라인"
/>
</>
) : (
<OnlineStatus>오프라인</OnlineStatus>
)}
</>
) : (
<OnlineStatus>오프라인</OnlineStatus>
)}
}
</Div>
</Middle>
<ThreeDotsImage
Expand Down
2 changes: 1 addition & 1 deletion src/components/common/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ const Title = styled.p``;

const DropBox = styled.div`
position: absolute;
background: ${theme.colors.white};
/* background: ${theme.colors.white}; */
z-index: 1;
`;

Expand Down
2 changes: 1 addition & 1 deletion src/components/crBoard/CRModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const Wrapper = styled.div<{ $type: string }>`
width: 100%;
position: relative;
min-height: ${({ $type }) => ($type === "posting" ? "837px" : "880px")};
height: auto;
max-height: ${({ $type }) => ($type === "posting" ? "837px" : "880px")};
height: 100%;
margin: 50px;
padding: 0 20px;
Expand Down
9 changes: 5 additions & 4 deletions src/components/createBoard/GameStyle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,15 @@ const GameStyle = (props: GameStyleProps) => {
useEffect(() => {
setSelectedStyleIds(selectedStyles);
}, [selectedStyles, setSelectedStyleIds]);
const selectedGameStyles = GAME_STYLE.filter(style => selectedStyleIds.includes(style.gameStyleId))
.map(style => style.gameStyleName);

return (
<>
<StylesWrapper>
{selectedStyles.map((styleId) => {
const style = GAME_STYLE.find((item) => item.gameStyleId === styleId);
return <Content key={styleId}>{style?.gameStyleName}</Content>;
})}
{selectedGameStyles.map((styleName, index) => (
<Content key={index}>{styleName}</Content>
))}
</StylesWrapper>
<Div>
<AddGameStyle onClick={handleStylePopup}>
Expand Down
8 changes: 5 additions & 3 deletions src/components/readBoard/ReadBoard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ const ReadBoard = (props: ReadBoardProps) => {
await deletePost(postId);
await dispatch(setPostStatus("delete"));
await dispatch(setCloseReadingModal());
await dispatch(setPostStatus(""));
} catch (error) {
console.error(error);
}
Expand Down Expand Up @@ -470,9 +471,10 @@ const ReadBoard = (props: ReadBoardProps) => {
} else {
try {
dispatch(setCloseReadingModal());
if (!isPost) return;
dispatch(setChatRoomUuid(isPost.boardId));
dispatch(openChatRoom());
if (isPost) {
dispatch(setChatRoomUuid(isPost.boardId));
dispatch(openChatRoom());
}
} catch (error) {
console.error(error);
}
Expand Down
48 changes: 42 additions & 6 deletions src/components/socket/SocketConnection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { useDispatch } from "react-redux";
import { socket } from "@/socket";
import useChatMessage from "@/hooks/useChatMessage";
import useChatFriend from "@/hooks/useChatFriend";

import { reissueToken } from "@/api/auth";
import { getAccessToken } from "@/utils/storage";
import { isTokenExpired } from "@/utils/auth";

const SocketConnection: React.FC = () => {
const dispatch = useDispatch();
Expand All @@ -12,25 +14,59 @@ const SocketConnection: React.FC = () => {
useChatFriend();

useEffect(() => {
function onConnect() {
const onConnect = () => {
const socketId = socket?.id || "";
sessionStorage.setItem("gamegooSocketId", socketId);
}
};

function onDisconnect() {
const onDisconnect = () => {
console.error("소켓 끊김");
}
};

const handleJwtExpiredError = async (data: any) => {
const { eventName, eventData } = data;
try {
const currentToken = getAccessToken();
// 토큰이 없을 경우 토큰 재발급
if (!currentToken || isTokenExpired(currentToken)) {
const response = await reissueToken();
const newToken = response.result.refreshToken;
console.log('newToken', newToken);
socket?.emit(eventName, { ...eventData, token: newToken });
}
} catch (error) {
console.error("토큰 재발급 실패:", error);
}
};

const handleConnectionJwtError = async () => {
try {
const currentToken = getAccessToken();

// 토큰이 없을 경우 토큰 재발급
if (!currentToken || isTokenExpired(currentToken)) {
const response = await reissueToken();
const newToken = response.result.refreshToken;
socket?.emit("connection-update-token", { token: newToken });
}
} catch (error) {
console.error("토큰 재발급 실패:", error);
}
};

if (socket?.connected) {
onConnect();
}

socket?.on("connect", onConnect);
socket?.on("disconnect", onDisconnect);

socket?.on("connection-jwt-error", handleConnectionJwtError);
socket?.on("jwt-expired-error", handleJwtExpiredError);
return () => {
socket?.off("connect", onConnect);
socket?.off("disconnect", onDisconnect);
socket?.off("connection-jwt-error", handleConnectionJwtError);
socket?.off("jwt-expired-error", handleJwtExpiredError);
};
}, [dispatch]);

Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useChatFriend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const useChatFriend = () => {
useEffect(() => {
// 소켓 연결되어 있지 않으면 소켓 연결
if (!socket) {
return connectSocket();
connectSocket();
}

const handleMemberInfo = (res: any) => {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useChatList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const useChatList = (setChatrooms: (chatrooms: ChatroomList[]) => void) => {
useEffect(() => {
// 소켓 연결되어 있지 않으면 소켓 연결
if (!socket) {
return connectSocket();
connectSocket();
}

const handleJoinedNewChatroom = async () => {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useChatMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const useChatMessage = () => {
useEffect(() => {
// 소켓 연결되어 있지 않으면 소켓 연결
if (!socket) {
return connectSocket();
connectSocket();
}

const handleChatMessage = (res: any) => {
Expand Down
9 changes: 9 additions & 0 deletions src/utils/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const isTokenExpired = (token: string): boolean => {
if (!token) return true;

const payload = JSON.parse(atob(token.split('.')[1]));
const expiryTime = payload.exp * 1000;
const currentTime = Date.now();

return currentTime > expiryTime;
};
2 changes: 1 addition & 1 deletion src/utils/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ export const clearTokens = () => {
localStorage.removeItem('refreshToken');
localStorage.removeItem('name');
localStorage.removeItem('profileImg');
localStorage.removeItem('userId');
sessionStorage.removeItem('accessToken');
sessionStorage.removeItem('refreshToken');
sessionStorage.removeItem('name');
sessionStorage.removeItem('profileImg');
sessionStorage.removeItem('userId');
sessionStorage.removeItem('userId');
};

/* 매칭 완료 여부 */
Expand Down

0 comments on commit ca452bc

Please sign in to comment.