Skip to content

Commit

Permalink
fix: middleware 내부에서 토큰 삭제하는 로직 제거, logout 에러 핸들링 로직 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
gxxrxn committed Jul 10, 2024
1 parent 24cc4d2 commit 3e34bf9
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 31 deletions.
4 changes: 3 additions & 1 deletion src/apis/core/axios.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import axios, { CreateAxiosDefaults, InternalAxiosRequestConfig } from 'axios';

import { AuthRefreshIgnoredError } from '@/types/customError';
import { SERVICE_ERROR_MESSAGE } from '@/constants';
import { SERVICE_ERROR_MESSAGE, SESSION_COOKIES_KEYS } from '@/constants';
import {
isAuthFailedError,
isAuthRefreshError,
isAxiosErrorWithCustomCode,
} from '@/utils/helpers';
import { deleteAuthSession, setAuthSession } from '@/server/session';
import { deleteCookie } from '@/utils/cookie';

const options: CreateAxiosDefaults = {
baseURL: process.env.NEXT_HOST,
Expand Down Expand Up @@ -86,6 +87,7 @@ const updateToken = () =>
});

const removeToken = async () => {
SESSION_COOKIES_KEYS.map(key => deleteCookie(key));
await deleteAuthSession();
};

Expand Down
8 changes: 4 additions & 4 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ const RootLayout = ({ children }: { children: React.ReactNode }) => {
<body className={`${LineSeedKR.variable} app-layout font-lineseed`}>
<PWAServiceWorkerProvider>
<ToastProvider>
<AuthFailedErrorBoundary>
<ReactQueryProvider>
<ReactQueryProvider>
<AuthFailedErrorBoundary>
<Layout>{children}</Layout>
</ReactQueryProvider>
</AuthFailedErrorBoundary>
</AuthFailedErrorBoundary>
</ReactQueryProvider>
</ToastProvider>
</PWAServiceWorkerProvider>
</body>
Expand Down
13 changes: 8 additions & 5 deletions src/app/profile/me/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,14 @@ const MyProfileForAuth = () => {
const router = useRouter();

const handleLogoutButtonClick = async () => {
await userAPI.logout();
await deleteAuthSession();
SESSION_COOKIES_KEYS.map(key => deleteCookie(key));
queryClient.removeQueries({ queryKey: userKeys.me(), exact: true });
router.refresh();
try {
await userAPI.logout();
await deleteAuthSession();
} finally {
SESSION_COOKIES_KEYS.map(key => deleteCookie(key));
queryClient.removeQueries({ queryKey: userKeys.me(), exact: true });
router.refresh();
}
};

return (
Expand Down
14 changes: 5 additions & 9 deletions src/components/common/AuthFailedErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
'use client';

import { useEffect } from 'react';
import { QueryErrorResetBoundary } from '@tanstack/react-query';
import { ErrorBoundary, FallbackProps } from 'react-error-boundary';

import { SESSION_COOKIES_KEYS } from '@/constants';
import { deleteCookie } from '@/utils/cookie';
import useToast from '@/components/common/Toast/useToast';
import QueryErrorBoundaryFallback from '@/components/common/QueryErrorBoundaryFallback';

Expand All @@ -26,14 +24,12 @@ const AuthFailedErrorBoundary = ({

export default AuthFailedErrorBoundary;

const AuthFailedFallback = ({ resetErrorBoundary }: FallbackProps) => {
const AuthFailedFallback = ({ error, resetErrorBoundary }: FallbackProps) => {
const { show: showToast } = useToast();

const handleError = () => {
SESSION_COOKIES_KEYS.map(key => deleteCookie(key));
useEffect(() => {
showToast({ message: '다시 로그인 해주세요' });
resetErrorBoundary();
};
}, [error, showToast]);

return <QueryErrorBoundaryFallback resetErrorBoundary={handleError} />;
return <QueryErrorBoundaryFallback resetErrorBoundary={resetErrorBoundary} />;
};
23 changes: 11 additions & 12 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const config = {
export async function middleware(request: NextRequest) {
// accessToken을 담고 있는 세션 쿠키
const authSession = request.cookies.get(SESSION_AUTH_KEY);

const uidSession = request.cookies.get(SESSION_PUBLIC_UID_KEY);
/*
* Server API Proxy
*/
Expand All @@ -53,7 +53,11 @@ export async function middleware(request: NextRequest) {
const headers = new Headers(request.headers);

// Authorization header 추가
if (authSession && !EXCLUDE_AUTH_HEADER_API.includes(pathname)) {
if (
authSession &&
uidSession &&
!EXCLUDE_AUTH_HEADER_API.includes(pathname)
) {
headers.set('Authorization', `Bearers ${authSession.value}`);
}

Expand All @@ -73,16 +77,11 @@ export async function middleware(request: NextRequest) {
* 'NEED_PROFILE_PATHS'에 포함되어 있는 경우,
* 추가 프로필 등록 페이지로 리다이렉션
*/
if (authSession && NEED_PROFILE_PATHS.includes(request.nextUrl.pathname)) {
const isVerfied = await verifyJWT(authSession.value);

// accessToken이 유효하지 않은 경우, auth 관련 세션 쿠키 모두 제거 후 재요청
if (!isVerfied) {
const response = NextResponse.rewrite(request.url, { request });
SESSION_COOKIES_KEYS.map(key => response.cookies.delete(key));
return response;
}

if (
authSession &&
uidSession &&
NEED_PROFILE_PATHS.includes(request.nextUrl.pathname)
) {
// 프로필이 등록되었는지 여부를 저장하고 있는 세션 쿠키
const profileSession = request.cookies.get(COOKIE_KEYS.ADDED_PROFILE_FLAG);

Expand Down

0 comments on commit 3e34bf9

Please sign in to comment.