Skip to content

Commit

Permalink
Merge pull request #79 from 2024-Team-Techeer-Salon/feat/#78
Browse files Browse the repository at this point in the history
[feat] 로그인 로직 버그 수정 등
  • Loading branch information
YunJuwon0825 authored Jul 7, 2024
2 parents 29206e1 + 4a7bc36 commit b067874
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 69 deletions.
1 change: 0 additions & 1 deletion Github-Study
Submodule Github-Study deleted from d42b13
89 changes: 64 additions & 25 deletions src/api/axios.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint-disable no-param-reassign */
/* eslint-disable consistent-return */
/* eslint-disable no-underscore-dangle */
import axios from 'axios';
import { getCookie, setCookie } from '@/app/cookies.tsx';
Expand All @@ -10,12 +12,12 @@ const reIssuedToken = async () => {
const response = await axios.post(
`${BASE_URL}/reissue`,
{
access_token: getCookie('accessToken'), // 액세스 토큰을 사용하고 있으나, 일반적으로는 사용하지 않습니다.
refresh_token: getCookie('refreshToken'), // 리프레시 토큰
access_token: getCookie('accessToken'),
refresh_token: getCookie('refreshToken'),
},
{
headers: {
'Content-Type': 'application/json', // 요청의 본문 타입을 지정
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
withCredentials: true, // CORS 요청 시 쿠키를 포함
Expand All @@ -29,38 +31,48 @@ const reIssuedToken = async () => {
}
return response.data;
} catch (error) {
throw new Error('토큰 재발급 로직 에러 : ', error || '');
setCookie('accessToken', '');
setCookie('refreshToken', '');
}
};

const api = axios.create({
withCredentials: true,
baseURL: BASE_URL, // 기본 URL 설정
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
});

// 요청 인터셉터를 추가하여 모든 요청에 최신 토큰을 포함시킵니다.
api.interceptors.request.use(
(config) => {
const token = getCookie('accessToken'); // 요청 직전에 액세스 토큰을 쿠키에서 가져옵니다.
config.headers.Authorization = `Bearer ${token}`;
config.headers['Content-Type'] = 'application/json';
return config;
},
(error) => Promise.reject(error),
);

api.interceptors.response.use(
(response) => response, // 성공 응답은 그대로 반환
async (error) => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true; // 재요청 플래그를 설정하여 무한 루프 방지
try {
const data = await reIssuedToken(); // 토큰 재발급 함수 호출
// 재발급 받은 토큰으로 요청 헤더 설정
api.defaults.headers.common.Authorization = `Bearer ${data.data.access_token}`;
originalRequest.headers.Authorization = `Bearer ${data.data.access_token}`;
if (accessToken !== undefined) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true; // 재요청 플래그를 설정하여 무한 루프 방지
try {
const data = await reIssuedToken(); // 토큰 재발급 함수 호출
// 재발급 받은 토큰으로 요청 헤더 설정
api.defaults.headers.common.Authorization = `Bearer ${data.data.access_token}`;
originalRequest.headers.Authorization = `Bearer ${data.data.access_token}`;

return api(originalRequest); // 원래 요청 재시도
} catch (refreshError) {
return Promise.reject(refreshError);
return api(originalRequest); // 원래 요청 재시도
} catch (refreshError) {
return Promise.reject(refreshError);
}
}
}

return Promise.reject(error);
return Promise.reject(error);
}
},
);

Expand All @@ -69,8 +81,35 @@ export { api };
export const formApi = axios.create({
withCredentials: true,
baseURL: BASE_URL,
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${accessToken}`,
},
});

formApi.interceptors.request.use(
(config) => {
const token = getCookie('accessToken');
config.headers.Authorization = `Bearer ${token}`;
return config;
},
(error) => Promise.reject(error),
);

formApi.interceptors.response.use(
(response) => response,
async (error) => {
if (accessToken !== undefined) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
const data = await reIssuedToken();
formApi.defaults.headers.common.Authorization = `Bearer ${data.data.access_token}`;
originalRequest.headers.Authorization = `Bearer ${data.data.access_token}`;

return formApi(originalRequest);
} catch (refreshError) {
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
},
);
2 changes: 1 addition & 1 deletion src/api/nearMeeting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const searchMeetings = async (
);
return response.data;
} catch (error) {
throw new Error('meeting search api request error : ', error || '');
throw new Error('주변 모임 검색 에러 : ', error || '');
}
};

Expand Down
2 changes: 1 addition & 1 deletion src/app/account/[userIdParam]/Classification.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const Classification = ({ id }: accountIdProps) => {
const loadMoreRef = useRef<HTMLDivElement | null>(null);

const { data, fetchNextPage, hasNextPage, refetch } = useInfiniteQuery({
queryKey: ['myMeetingList'],
queryKey: ['My Meeting List', activeTab],
queryFn: ({ pageParam = 0 }: { pageParam: number }) =>
getMyMeetingList(activeTab, id, pageParam, 24),
initialPageParam: 0,
Expand Down
22 changes: 20 additions & 2 deletions src/app/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable operator-linebreak */

'use client';

import { useState } from 'react';
import { useEffect, useState } from 'react';
import { Montserrat } from 'next/font/google';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import category from '@/util/category.json';
import { useQuery } from '@tanstack/react-query';
import { login, logout } from '@/api/user.ts';
import ignorePath from '../styles/ignorePath.ts';
import { removeCookie } from '../cookies.tsx';
import { getCookie, removeCookie } from '../cookies.tsx';

const mont = Montserrat({ subsets: ['latin'], weight: ['500'] });

Expand All @@ -25,6 +28,21 @@ function Header() {
queryFn: login,
});

const checkAuthentication = async () => {
if (
!getCookie('accessToken') &&
!getCookie('refreshToken') &&
path !== '/auth/login' &&
path !== '/auth/signup'
) {
await router.push('/login');
}
};

useEffect(() => {
checkAuthentication();
}, []);

if (ignorePath().includes(path)) {
return null;
}
Expand Down
47 changes: 23 additions & 24 deletions src/app/home/Body.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,29 +50,28 @@ function Distance() {

const renderSize = 8;

const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
useInfiniteQuery({
queryKey: ['Latest Meeting List', latitude, longitude],
queryFn: async ({ pageParam = 0 }) => {
if (latitude !== null && longitude !== null) {
return searchMeetings(
latitude,
longitude,
pageParam,
renderSize,
'asc',
);
}
},
getNextPageParam: (lastPage, allPages) => {
if (lastPage === null) {
return undefined;
}
return allPages.length;
},
enabled: locationFetched, // 위치 정보를 성공적으로 가져왔을 때만 쿼리 실행
initialPageParam: 0,
});
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
queryKey: ['Latest Meeting List', latitude, longitude],
queryFn: async ({ pageParam = 0 }) => {
if (latitude !== null && longitude !== null) {
return searchMeetings(
latitude,
longitude,
pageParam,
renderSize,
'asc',
);
}
},
getNextPageParam: (lastPage, allPages) => {
if (lastPage === null) {
return undefined;
}
return allPages.length;
},
enabled: locationFetched, // 위치 정보를 성공적으로 가져왔을 때만 쿼리 실행
initialPageParam: 0,
});

const loadMoreRef = useRef<HTMLDivElement | null>(null);

Expand Down Expand Up @@ -260,7 +259,7 @@ function Distance() {
),
),
)}
{isFetchingNextPage && <div>Loading...</div>}
{/* {isFetchingNextPage && <div>Loading...</div>} */}
<div ref={loadMoreRef} />
</div>
</div>
Expand Down
18 changes: 9 additions & 9 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './styles/globals.css';
import Script from 'next/script';
import StoreProvider from './StoreProvider.tsx';
// import StoreProvider from './StoreProvider.tsx';
import Header from './components/Header.tsx';
import Footer from './components/Footer.tsx';
import QueryProviders from '../lib/QueryProvider.tsx';
Expand Down Expand Up @@ -31,14 +31,14 @@ export default function RootLayout({
<QueryProviders>
<Suspense fallback={<div>로딩중인데요?ㅋㅋ</div>}>
<Header />
<StoreProvider>
<Script
type="text/javascript"
src={process.env.NEXT_PUBLIC_KAKAO_SDK_URL}
strategy="beforeInteractive"
></Script>
<div className="flex min-h-screen min-w-full">{children}</div>
</StoreProvider>
{/* <StoreProvider> */}
<Script
type="text/javascript"
src={process.env.NEXT_PUBLIC_KAKAO_SDK_URL}
strategy="beforeInteractive"
></Script>
<div className="flex min-h-screen min-w-full">{children}</div>
{/* </StoreProvider> */}
<Footer />
</Suspense>
</QueryProviders>
Expand Down
7 changes: 1 addition & 6 deletions src/app/not-found.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const mont = Montserrat({ subsets: ['latin'], weight: ['500'] });

export default function Notfound() {
return (
<div className="-mb-20 flex min-h-screen flex-col items-center justify-center bg-gradient-to-br from-gray-100 to-blue-200">
<div className="-mb-20 flex min-h-screen w-full flex-col items-center justify-center bg-gradient-to-br from-gray-100 to-blue-200">
<Head>
<link
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap"
Expand All @@ -35,11 +35,6 @@ export default function Notfound() {
</div>
</div>
<div className="mt-10 flex flex-row items-center justify-center">
<Link href="/">
<p className="ml-2 mr-2 flex h-12 w-40 items-center justify-center border-2 border-black transition duration-300 hover:bg-zinc-900 hover:text-white">
이전으로
</p>
</Link>
<Link href="/">
<p className="ml-2 mr-2 flex h-12 w-40 items-center justify-center border-2 border-black transition duration-300 hover:bg-zinc-900 hover:text-white">
메인으로
Expand Down

0 comments on commit b067874

Please sign in to comment.