Skip to content
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
24 changes: 19 additions & 5 deletions src/app/provider/authStore.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface AuthStore {
accessToken: string | null;
refreshToken: string | null;
setAccessToken: (token: string | null) => void;
setRefreshToken: (token: string | null) => void;

isModalOpen: boolean;
openModal: () => void;
closeModal: () => void;
}

const useAuthStore = create<AuthStore>(set => ({
isModalOpen: false,
openModal: () => set({ isModalOpen: true }),
closeModal: () => set({ isModalOpen: false }),
}));
export const useAuthStore = create<AuthStore>()(
persist(
(set) => ({
accessToken: null,
refreshToken: null,
setAccessToken: (token) => set({ accessToken: token }),
setRefreshToken: (token) => set({ refreshToken: token }),
isModalOpen: false,
openModal: () => set({ isModalOpen: true }),
closeModal: () => set({ isModalOpen: false }),
}), { name: 'auth-storage' }
)
);

export default useAuthStore;
9 changes: 6 additions & 3 deletions src/pages/home/ui/MainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const MainPage = () => {
const [closingStartIndex, setClosingStartIndex] = useState<number>(0);
const maxCardsToShow = 2;
const navigate = useNavigate();
const { isModalOpen, openModal, closeModal } = useAuthStore();
const { isModalOpen, openModal, closeModal} = useAuthStore();

type SetStartIndex = Dispatch<SetStateAction<number>>;

Expand All @@ -51,12 +51,12 @@ const MainPage = () => {
<SearchTextField
iconPath={<img src={searchIcon} alt="Search" />}
onClick={() => navigate('/search')}
onChange={() => {}}
onChange={() => { }}
placeholder="입력해주세요"
/>
}
leftButtonClassName="sm:text-lg md:text-xl lg:text-2xl font-extrabold font-nexon"
leftButtonClick={() => {}}
leftButtonClick={() => { }}
leftButtonLabel="같이가요"
rightContent={<SecondaryButton size="large" color="black" label="로그인" onClick={openModal} />}
/>
Expand Down Expand Up @@ -91,6 +91,7 @@ const MainPage = () => {
)
.map((event, index) => (
<EventCard
id={index}
key={index}
img={event.img}
eventTitle={event.eventTitle}
Expand Down Expand Up @@ -127,6 +128,7 @@ const MainPage = () => {
)
.map((event, index) => (
<EventCard
id={index}
key={index}
img={event.img}
eventTitle={event.eventTitle}
Expand Down Expand Up @@ -165,6 +167,7 @@ const MainPage = () => {
)
.map((event, index) => (
<EventCard
id={index}
key={index}
img={event.img}
eventTitle={event.eventTitle}
Expand Down
19 changes: 18 additions & 1 deletion src/pages/menu/ui/MyTicketPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { readTicket } from '../../../features/ticket/api/order';
import completedImg from '../../../../public/assets/menu/Completed.svg';
import pendingImg from '../../../../public/assets/menu/Pending.svg';
import ticketImg from '../../../../public/assets/menu/Ticket.svg';
import useAuthStore from '../../../app/provider/authStore';
import Cookies from 'js-cookie';

type Ticket = {
id: number;
Expand All @@ -33,7 +35,22 @@ const MyTicketPage = () => {
const [isModalOpen, setIsModalOpen] = useState(false);
const [myTickets, setMyTickets] = useState<Ticket[]>([]);
const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);

const { setAccessToken, setRefreshToken } = useAuthStore();
useEffect(() => {
const accessToken = Cookies.get('access-token');
const refreshToken = Cookies.get('refresh-token');

console.log("access-token:", accessToken);
console.log("refresh-token:", refreshToken);

if (accessToken) {
setAccessToken(accessToken);
}
if (refreshToken) {
setRefreshToken(refreshToken);
}
}, []);
Comment on lines +38 to +52
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

토큰 관리 로직에 보안 및 최적화 문제가 있습니다.

다음과 같은 문제점이 있습니다:

  1. 민감한 토큰이 콘솔에 출력되고 있어 보안 위험이 있습니다
  2. 의존성 배열이 비어 있어 컴포넌트 마운트 시에만 실행됩니다
  3. 토큰 설정 시 오류 처리가 없습니다

다음과 같이 개선할 것을 제안합니다:

  const { setAccessToken, setRefreshToken } = useAuthStore();
  useEffect(() => {
    const accessToken = Cookies.get('access-token');
    const refreshToken = Cookies.get('refresh-token');
  
-    console.log("access-token:", accessToken);
-    console.log("refresh-token:", refreshToken);
-  
    if (accessToken) {
      setAccessToken(accessToken);
    }
    if (refreshToken) {
      setRefreshToken(refreshToken);
    }
-  }, []);
+  }, [setAccessToken, setRefreshToken]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { setAccessToken, setRefreshToken } = useAuthStore();
useEffect(() => {
const accessToken = Cookies.get('access-token');
const refreshToken = Cookies.get('refresh-token');
console.log("access-token:", accessToken);
console.log("refresh-token:", refreshToken);
if (accessToken) {
setAccessToken(accessToken);
}
if (refreshToken) {
setRefreshToken(refreshToken);
}
}, []);
const { setAccessToken, setRefreshToken } = useAuthStore();
useEffect(() => {
const accessToken = Cookies.get('access-token');
const refreshToken = Cookies.get('refresh-token');
if (accessToken) {
setAccessToken(accessToken);
}
if (refreshToken) {
setRefreshToken(refreshToken);
}
}, [setAccessToken, setRefreshToken]);


useEffect(() => {
const fetchMyTickets = async () => {
try {
Expand Down
13 changes: 7 additions & 6 deletions src/shared/types/api/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ import useAuthStore from '../../../app/provider/authStore';
export const axiosClient = axios.create({
baseURL: 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/api/v1',
timeout: 3000,
withCredentials: true,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${import.meta.env.VITE_HEADER_TOKEN}`,
//Authorization: `Bearer `,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

인증 관련 코드가 일관되지 않게 주석 처리되었습니다.

Authorization 헤더와 토큰 설정 로직이 주석 처리되었지만, 완전히 제거되지 않았습니다. 이는 코드 품질과 유지보수성을 저하시킵니다. 또한 line 49에서는 여전히 access_token을 참조하고 있으나 다른 부분에서는 access-token을 사용하고 있습니다.

다음과 같이 개선할 것을 제안합니다:

  headers: {
    'Content-Type': 'application/json',
-    //Authorization: `Bearer `,
  },
});

axiosClient.interceptors.request.use(
  config => {
-    //const token = Cookies.get('access_token');
-    //zustand 사용함으로써 코드변경 할 듯 현재는 임시 입니다.
-    // const token = useAuthStore.getState().accessToken;
-    // if (token) {
-    //   config.headers.Authorization = `Bearer ${token}`;
-    // }
+    const token = useAuthStore.getState().accessToken;
+    if (token) {
+      config.headers.Authorization = `Bearer ${token}`;
+    }

    return config;

그리고 아래의 에러 처리 부분도 수정이 필요합니다:

  // 401(토큰 만료)일 경우 로그아웃 처리 or 토큰 갱신 가능
  if (errorInfo.status === 401) {
-    Cookies.remove('access_token');
+    Cookies.remove('access-token');
+    Cookies.remove('refresh-token');

    useAuthStore.getState().openModal();
  }

Also applies to: 18-23

},
});

axiosClient.interceptors.request.use(
config => {
const token = Cookies.get('access_token');
//const token = Cookies.get('access_token');
//zustand 사용함으로써 코드변경 할 듯 현재는 임시 입니다.

if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// const token = useAuthStore.getState().accessToken;
// if (token) {
// config.headers.Authorization = `Bearer ${token}`;
// }

return config;
},
Expand Down
10 changes: 8 additions & 2 deletions src/widgets/main/ui/LoginModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ interface LoginModalProps {
}

const LoginModal = ({ onClose }: LoginModalProps) => {
const kakaoLogin = () => {
window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/kakao';
};
const gooleLogin = () => {
window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/google';
}
Comment on lines +12 to +17
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

OAuth 로그인 함수 구현 개선이 필요합니다.

OAuth 로그인 함수에 다음과 같은 개선이 필요합니다:

  1. gooleLogin 함수명에 오타가 있습니다 (googleLogin으로 수정 필요)
  2. 하드코딩된 URL은 환경 변수로 이동하는 것이 바람직합니다
  3. 로딩 상태 표시나 오류 처리 메커니즘이 없습니다

다음과 같이 개선할 것을 제안합니다:

-  const kakaoLogin = () => {
-    window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/kakao';
-  };
-  const gooleLogin = () => {
-    window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/google';
-  }
+  const [isLoading, setIsLoading] = useState(false);
+  
+  const kakaoLogin = () => {
+    try {
+      setIsLoading(true);
+      window.location.href = import.meta.env.VITE_API_BASE_URL + '/oauth2/authorization/kakao';
+    } catch (error) {
+      console.error('카카오 로그인 중 오류 발생:', error);
+      setIsLoading(false);
+    }
+  };
+  
+  const googleLogin = () => {
+    try {
+      setIsLoading(true);
+      window.location.href = import.meta.env.VITE_API_BASE_URL + '/oauth2/authorization/google';
+    } catch (error) {
+      console.error('구글 로그인 중 오류 발생:', error);
+      setIsLoading(false);
+    }
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const kakaoLogin = () => {
window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/kakao';
};
const gooleLogin = () => {
window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/google';
}
const [isLoading, setIsLoading] = useState(false);
const kakaoLogin = () => {
try {
setIsLoading(true);
window.location.href = import.meta.env.VITE_API_BASE_URL + '/oauth2/authorization/kakao';
} catch (error) {
console.error('카카오 로그인 중 오류 발생:', error);
setIsLoading(false);
}
};
const googleLogin = () => {
try {
setIsLoading(true);
window.location.href = import.meta.env.VITE_API_BASE_URL + '/oauth2/authorization/google';
} catch (error) {
console.error('구글 로그인 중 오류 발생:', error);
setIsLoading(false);
}
}

return (
<motion.div
initial={{ y: '-100vh', opacity: 0 }}
Expand All @@ -30,15 +36,15 @@ const LoginModal = ({ onClose }: LoginModalProps) => {
<HorizontalCardButton
iconPath={<img src={kakao} alt="카카오 아이콘" className="" />}
label="카카오 로그인"
onClick={() => {}}
onClick={kakaoLogin}
className="mx-auto my-auto"
/>
</div>
<div className="flex items-center w-full h-12 bg-white gap-4 rounded-full">
<HorizontalCardButton
iconPath={<img src={google} alt="구글 아이콘" className="" />}
label="Google 로그인"
onClick={() => {}}
onClick={gooleLogin}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

구글 로그인 버튼에 오타가 있는 함수를 사용하고 있습니다.

구글 로그인 기능을 호출하는 함수명에 오타가 있습니다.

-              onClick={gooleLogin}
+              onClick={googleLogin}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onClick={gooleLogin}
onClick={googleLogin}

className="mx-auto my-auto"
/>
</div>
Expand Down