Skip to content
Merged
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
49 changes: 12 additions & 37 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { NextRequest, NextResponse } from 'next/server'
import { NextRequest, NextResponse } from 'next/server';

const API_BASE_URL = process.env.NEXT_PUBLIC_BASE_API_URL;

Expand All @@ -7,52 +7,27 @@ const protectedPaths = [
'/admin',
'/main',
'/study'
]
];

export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const { pathname } = request.nextUrl;

// 보호된 경로인지 확인
const isProtectedPath = protectedPaths.some(path => pathname.startsWith(path))
const isProtectedPath = protectedPaths.some(path => pathname.startsWith(path));
if (!isProtectedPath) {
return NextResponse.next()
return NextResponse.next();
}

// Authorization 헤더에서 엑세스 토큰 확인 -> 현재로서는 작동 안함
const authHeader = request.headers.get('authorization')
const accessToken = authHeader?.split(' ')[1] // Bearer 토큰

// 쿠키에서 리프레시 토큰 확인
const refreshToken = request.cookies.get('refresh_token')
const refreshToken = request.cookies.get('refresh_token');

// 엑세스 토큰이 없는 경우
if (!accessToken) {
// 리프레시 토큰이 있는 경우 토큰 재발급 API 호출
if (refreshToken) {
try {
const response = await fetch(`${API_BASE_URL}/api/auth/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refreshToken: refreshToken.value }),
credentials: 'include',
})

if (response.ok) {
// 토큰 재발급 성공 시 원래 요청 계속 진행
return NextResponse.next()
}
} catch (error) {
console.error('Token refresh failed:', error)
}
}
// 리프레시 토큰이 없거나 토큰 재발급 실패 시 로그인 페이지로 리디렉션
return NextResponse.redirect(new URL('/auth/signin', request.url))
// 리프레시 토큰이 없는 경우 로그인 페이지로 리디렉션
if (!refreshToken) {
return NextResponse.redirect(new URL('/auth/signin', request.url));
}

// 모든 조건을 통과하면 다음 미들웨어로 진행
return NextResponse.next()
// 리프레시 토큰이 있으면 요청을 계속 진행
return NextResponse.next();
}

// 미들웨어가 실행될 경로 설정
Expand All @@ -72,4 +47,4 @@ export const config = {
*/
'/((?!api|_next/static|_next/image|favicon.ico|public|auth|robots.txt|sitemap.xml|error|loading|not-found|unauthorized|forbidden|recruit).*)',
],
}
};