Skip to content

Commit

Permalink
[Fix] 자동 로그아웃 로직 수정
Browse files Browse the repository at this point in the history
- 기존 : 토큰을 세션 스토리지에 저장하여 활용
- 변경 : 토큰을 로컬 스토리지에 저장하여 활용
- 변경사유 : 유저가 로그인 시 브라우저의 다수의 탭에서 로그인 상태 적용되도록 하기 위하여 수정 (관련하여 새로고침 및 브라우저 종료 시에도 자동 로그아웃 처리 정상적으로 작동하도록 로직 추가)

Issues #122
  • Loading branch information
novice1993 committed Sep 30, 2023
1 parent 3e71f9f commit a0e534b
Show file tree
Hide file tree
Showing 22 changed files with 77 additions and 61 deletions.
8 changes: 4 additions & 4 deletions client/src/components/Headers/LoginHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ const LoginHeader: React.FC<LoginHeaderProps> = () => {
// 로그아웃 클릭 처리 함수
const handleLogout = () => {
dispatch(setLogoutState()); // 전역변수에서 로그아웃 상태로 설정
sessionStorage.removeItem("accessToken"); // 엑세스 토큰 제거
sessionStorage.removeItem("refreshToken"); // 리프레시 토큰 제거
sessionStorage.removeItem("logoutAlarmTime01");
sessionStorage.removeItem("logoutAlarmTime02");
localStorage.removeItem("accessToken"); // 엑세스 토큰 제거
localStorage.removeItem("refreshToken"); // 리프레시 토큰 제거
localStorage.removeItem("logoutAlarmTime01");
localStorage.removeItem("logoutAlarmTime02");

// 페이지를 새로고침합니다.
window.location.reload();
Expand Down
6 changes: 2 additions & 4 deletions client/src/components/Logins/EmailLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ const EmailLoginModal: React.FC<EmailLoginModalProps> = ({ onClose, onSignup })
}
};

// 🔴 자동 로그아웃 관련 코드 -> 정리 필요
const handleLoginClick = async () => {
try {
const response = await axios.post("http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/members/login", { email, password }, { validateStatus: (status) => status >= 200 && status < 600 });
Expand All @@ -52,8 +51,8 @@ const EmailLoginModal: React.FC<EmailLoginModalProps> = ({ onClose, onSignup })
const accessToken = response.headers["authorization"];
const refreshToken = response.headers["refresh"];

if (accessToken) sessionStorage.setItem("accessToken", accessToken);
if (refreshToken) sessionStorage.setItem("refreshToken", refreshToken);
if (accessToken) localStorage.setItem("accessToken", accessToken);
if (refreshToken) localStorage.setItem("refreshToken", refreshToken);
dispatch(setLoginState());

setAutoLogoutAlarm(dispatch, "first", secondAlarmTime, lastAlarmTime);
Expand All @@ -70,7 +69,6 @@ const EmailLoginModal: React.FC<EmailLoginModalProps> = ({ onClose, onSignup })
}
}
};
// 🔴 자동 로그아웃 관련 코드 -> 정리 필요

return (
<ModalBackground>
Expand Down
7 changes: 4 additions & 3 deletions client/src/components/StockOrderSection/StockOrder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,16 +86,17 @@ const StockOrder = ({ corpName }: { corpName: string }) => {

// 1) 주말, 공휴일 여부 체크
const today = new Date();
const nonBusinessDay = isHoliday(today, { include: { saturday: true, sunday: true } }); // 토요일, 일요일, 공휴일 (임시 공휴일 포함)
const isBusinessDay = !isHoliday(today, { include: { saturday: true, sunday: true } }); // 토요일, 일요일, 공휴일 (임시 공휴일 포함)

// 2) 개장시간 여부 체크
const currentHour = today.getHours();
const currentMinute = today.getMinutes();
const isBefore9AM = currentHour < 9;
const isAfter330PM = currentHour > 15 || (currentHour === 15 && currentMinute >= 30);
const closingTime = isBefore9AM || isAfter330PM;
const marketCloseTime = isBefore9AM || isAfter330PM;

const orderFailureCase01 = nonBusinessDay || closingTime;
const orderFailureCase01 = false;
// const orderFailureCase01 = !isBusinessDay || marketCloseTime;
const orderFailureCase02 = orderPrice === 0 || orderVolume === 0;

return (
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/communityComponents/Comments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const Comments = ({ boardId }: { boardId: number }) => {
setCommentsValue(e.target.value);
};

const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");

const handleClickSubmit = async () => {
if (commentsValue) {
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/communityComponents/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const TimeLineComponent = () => {
};

// 서브밋 버튼 클릭
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");
const handleClickSubmit = async () => {
// 로그인 토큰 확인
if (!accessToken) {
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/stars/useDeletestars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useMutation } from 'react-query';

// DELETE 요청을 수행하는 함수
const deleteStarData = async (companyId: number) => {
const accessToken = sessionStorage.getItem('accessToken');
const accessToken = localStorage.getItem('accessToken');
const response = await fetch(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/stars/?companyId=${companyId}`, {
method: 'DELETE',
headers: {
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/stars/useGetstars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type StarData = StarDataItem[];
// : Promise<StarData>

const fetchStarData = async () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");

// 로그인 상태에만 관심목록 데이터 호출하도록 설정
if (accessToken !== null) {
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/stars/usePoststars.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useMutation } from 'react-query';

const postStarData = async (companyId: number) => {
const accessToken = sessionStorage.getItem('accessToken');
const accessToken = localStorage.getItem('accessToken');
const res = await fetch(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/stars/?companyId=${companyId}`, {
method: 'POST',
headers: {
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useCash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { RootState } from "../store/config";
const BASE_URL = "http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080";

const getAuthHeader = () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");
return {
Authorization: `${accessToken}`,
};
Expand Down
4 changes: 2 additions & 2 deletions client/src/hooks/useDeleteMembers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export function useDeleteMember() {
const dispatch = useDispatch();

return useMutation(async () => {
const accessToken = sessionStorage.getItem('accessToken');
const accessToken = localStorage.getItem('accessToken');
const response = await axios.delete(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/members`, {
headers: {
Authorization: `${accessToken}`
Expand All @@ -30,7 +30,7 @@ export function useDeleteMember() {
}, {
onSuccess: () => {
// 토큰 삭제
sessionStorage.removeItem('accessToken');
localStorage.removeItem('accessToken');

// 로그아웃 상태로 변경
dispatch(setLogoutState());
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useDeleteStockOrder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default useDeleteStockOrder;
const deleteStockOrder = async (orderId: number, cancleVolume: number) => {
const url = `http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/stock/stockorders?stockOrderId=${orderId}&stockCount=${cancleVolume}`;

const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");
const options = {
headers: {
Authorization: `${accessToken}`,
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useGetCash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const useGetCash = () => {
export default useGetCash;

const getCashData = async () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");
const options = {
headers: {
Authorization: `${accessToken}`,
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useGetCashId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const useGetCashId = () => {
export default useGetCashId;

const getCashData = async () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");
const options = {
headers: {
Authorization: `${accessToken}`,
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useGetHoldingStock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const useGetHoldingStock = () => {
export default useGetHoldingStock;

const getHoldingStock = async () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");
const options = {
headers: {
Authorization: `${accessToken}`,
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useGetMemberId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const useGetMemberId = () => {
export default useGetMemberId;

const getMemberId = async () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");

const options = {
headers: {
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useGetMemberInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import axios from "axios";

export function useGetMemberInfo() {
return useQuery(["member"], async () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");

const response = await axios.get(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/members`, {
headers: {
Expand Down
4 changes: 2 additions & 2 deletions client/src/hooks/useGetStockInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ const useGetStockInfo = (companyId: number) => {
const currentMinute = today.getMinutes();
const isBefore9AM = currentHour < 9;
const isAfter330PM = currentHour > 15 || (currentHour === 15 && currentMinute >= 30);
const marketOpenTime = !isBefore9AM || !isAfter330PM;
const marketCloseTime = isBefore9AM || isAfter330PM;

const dataRenewalTime = isBusinessDay || marketOpenTime;
const dataRenewalTime = isBusinessDay || !marketCloseTime;

// 개장 시간 이내일 경우, 현재 시각이 30분, 정각이 아닌 경우 남은 시간 계산하여 checkTime 함수 다시 실행
useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useGetStockOrderRecord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const useGetStockOrderRecord = () => {
export default useGetStockOrderRecord;

const getOrderRecord = async () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");
const options = {
headers: {
Authorization: `${accessToken}`,
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useGetStockholds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const useGetStockHolds = () => {
export default useGetStockHolds;

const getStockHolds = async () => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");
const res = await axios.get("http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/stock/stockholds", {
headers: {
Authorization: accessToken,
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useTradeStock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const useTradeStock = () => {
export default useTradeStock;

const postOrderRequest = async (orderType: boolean, companyId: number, price: number, volume: number) => {
const accessToken = sessionStorage.getItem("accessToken");
const accessToken = localStorage.getItem("accessToken");

const options = {
headers: {
Expand Down
51 changes: 34 additions & 17 deletions client/src/page/MainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,25 +133,32 @@ const MainPage = () => {
};

useEffect(() => {
const acessToken = sessionStorage.getItem("accessToken");
const acessToken = localStorage.getItem("accessToken");
if (acessToken !== null) {
dispatch(setLoginState());

const currentTime = Date.now();

const autoLogoutSecondAlarm = sessionStorage.getItem("autoLogoutSecondAlarm");
const autoLogoutLastAlarm = sessionStorage.getItem("autoLogoutLastAlarm");
const autoLogoutSecondAlarm = localStorage.getItem("autoLogoutSecondAlarm");
const autoLogoutLastAlarm = localStorage.getItem("autoLogoutLastAlarm");

if (autoLogoutSecondAlarm !== null) {
const timeGone = currentTime - parseInt(autoLogoutSecondAlarm);
const remainTime = secondAlarmTime - timeGone;
setAutoLogoutAlarm(dispatch, "second", remainTime, lastAlarmTime);
if (currentTime >= parseInt(autoLogoutSecondAlarm) + secondAlarmTime + lastAlarmTime) {
localStorage.removeItem("autoLogoutSecondAlarm");
} else {
const timeGone = currentTime - parseInt(autoLogoutSecondAlarm);
const remainTime = secondAlarmTime - timeGone;
dispatch(setLoginState());
setAutoLogoutAlarm(dispatch, "second", remainTime, lastAlarmTime);
}
}

if (autoLogoutLastAlarm !== null) {
const timeGone = currentTime - parseInt(autoLogoutLastAlarm);
const remainTime = lastAlarmTime - timeGone;
setAutoLogoutAlarm(dispatch, "last", remainTime);
if (currentTime >= parseInt(autoLogoutLastAlarm) + lastAlarmTime) {
localStorage.removeItem("autoLogoutLastAlarm");
} else {
const timeGone = currentTime - parseInt(autoLogoutLastAlarm);
const remainTime = lastAlarmTime - timeGone;
dispatch(setLoginState());
setAutoLogoutAlarm(dispatch, "last", remainTime);
}
}
}
}, []);
Expand All @@ -164,31 +171,41 @@ const MainPage = () => {
const refreshToken = urlParams.get("refresh_token");

const currentTime = Date.now();
const autoLogoutSecondAlarm = sessionStorage.getItem("autoLogoutSecondAlarm");
const autoLogoutLastAlarm = sessionStorage.getItem("autoLogoutLastAlarm");
const autoLogoutSecondAlarm = localStorage.getItem("autoLogoutSecondAlarm");
const autoLogoutLastAlarm = localStorage.getItem("autoLogoutLastAlarm");

if (accessToken && refreshToken) {
sessionStorage.setItem("accessToken", `Bearer ${accessToken}`);
sessionStorage.setItem("refreshToken", refreshToken);
dispatch(setLoginState());
localStorage.setItem("accessToken", `Bearer ${accessToken}`);
localStorage.setItem("refreshToken", refreshToken);

urlParams.delete("access_token");
urlParams.delete("refresh_token");
window.history.replaceState({}, "", "?" + urlParams.toString());

if (autoLogoutSecondAlarm === null) {
dispatch(setLoginState()); // 로그인 처리
setAutoLogoutAlarm(dispatch, "first", secondAlarmTime, lastAlarmTime);
}

if (autoLogoutSecondAlarm !== null) {
if (currentTime >= parseInt(autoLogoutSecondAlarm) + secondAlarmTime + lastAlarmTime) {
localStorage.removeItem("autoLogoutSecondAlarm");
}

const timeGone = currentTime - parseInt(autoLogoutSecondAlarm);
const remainTime = secondAlarmTime - timeGone;
dispatch(setLoginState()); // 로그인 처리
setAutoLogoutAlarm(dispatch, "second", remainTime, lastAlarmTime);
}

if (autoLogoutLastAlarm !== null) {
if (currentTime >= parseInt(autoLogoutLastAlarm) + lastAlarmTime) {
localStorage.removeItem("autoLogoutLastAlarm");
}

const timeGone = currentTime - parseInt(autoLogoutLastAlarm);
const remainTime = lastAlarmTime - timeGone;
dispatch(setLoginState()); // 로그인 처리
setAutoLogoutAlarm(dispatch, "last", remainTime);
}
}
Expand Down
28 changes: 14 additions & 14 deletions client/src/utils/setAutoLogoutAlarm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ const setAutoLogoutAlarm = (dispatch: any, alarmNum: string, secondAlarmTime: nu

// 2차 알림 셋팅 시간 기록
const autoLogoutSecondAlarm = Date.now();
sessionStorage.setItem("autoLogoutSecondAlarm", `${autoLogoutSecondAlarm}`);
localStorage.setItem("autoLogoutSecondAlarm", `${autoLogoutSecondAlarm}`);

setTimeout(() => {
// 2차 알림 셋팅 시간 제거
sessionStorage.removeItem("autoLogoutSecondAlarm");
localStorage.removeItem("autoLogoutSecondAlarm");

toast.warning("1분 뒤 로그아웃 처리됩니다", {
style: toastStyle,
Expand All @@ -42,15 +42,15 @@ const setAutoLogoutAlarm = (dispatch: any, alarmNum: string, secondAlarmTime: nu

// 3차 알림 셋팅 시간 기록
const autoLogoutLastAlarm = Date.now();
sessionStorage.setItem("autoLogoutLastAlarm", `${autoLogoutLastAlarm}`);
localStorage.setItem("autoLogoutLastAlarm", `${autoLogoutLastAlarm}`);

setTimeout(() => {
// 3차 알림 셋팅 시간 제거
sessionStorage.removeItem("autoLogoutLastAlarm");
localStorage.removeItem("autoLogoutLastAlarm");

dispatch(setLogoutState());
sessionStorage.removeItem("accessToken");
sessionStorage.removeItem("refreshToken");
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");

toast.warning("로그아웃 처리되었습니다", {
style: toastStyle,
Expand All @@ -64,7 +64,7 @@ const setAutoLogoutAlarm = (dispatch: any, alarmNum: string, secondAlarmTime: nu
if (alarmNum === alarmNumType.Second) {
setTimeout(() => {
// 2차 알림 셋팅 시간 제거
sessionStorage.removeItem("autoLogoutSecondAlarm");
localStorage.removeItem("autoLogoutSecondAlarm");

toast.warning("1분 뒤 로그아웃 처리됩니다", {
style: toastStyle,
Expand All @@ -73,15 +73,15 @@ const setAutoLogoutAlarm = (dispatch: any, alarmNum: string, secondAlarmTime: nu

// 3차 알림 셋팅 시간 기록
const autoLogoutLastAlarm = Date.now();
sessionStorage.setItem("autoLogoutLastAlarm", `${autoLogoutLastAlarm}`);
localStorage.setItem("autoLogoutLastAlarm", `${autoLogoutLastAlarm}`);

setTimeout(() => {
// 3차 알림 셋팅 시간 제거
sessionStorage.removeItem("autoLogoutLastAlarm");
localStorage.removeItem("autoLogoutLastAlarm");

dispatch(setLogoutState());
sessionStorage.removeItem("accessToken");
sessionStorage.removeItem("refreshToken");
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");

toast.warning("로그아웃 처리되었습니다", {
style: toastStyle,
Expand All @@ -97,11 +97,11 @@ const setAutoLogoutAlarm = (dispatch: any, alarmNum: string, secondAlarmTime: nu
if (alarmNum === alarmNumType.Last) {
setTimeout(() => {
// 3차 알림 셋팅 시간 제거
sessionStorage.removeItem("autoLogoutLastAlarm");
localStorage.removeItem("autoLogoutLastAlarm");

dispatch(setLogoutState());
sessionStorage.removeItem("accessToken");
sessionStorage.removeItem("refreshToken");
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");

toast.warning("로그아웃 처리되었습니다", {
style: toastStyle,
Expand Down

0 comments on commit a0e534b

Please sign in to comment.