-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[feat] 로그인 미들웨어 설정 #83
Conversation
📝 WalkthroughWalkthrough이 PR은 인증 및 접근 제어를 처리하는 새로운 미들웨어 함수를 추가합니다. 해당 함수는 요청의 URL 경로를 확인하고, 미리 정의된 공개 경로 목록과 비교하여 인증 필요 여부를 판단합니다. 또한 요청 쿠키에서 액세스 및 리프레시 토큰의 존재를 확인합니다. 파일 타입(CSS, JS, PNG 등)의 경우 인증 검증 없이 요청을 진행하며, 인증 상태 및 경로에 따라 사용자를 홈 페이지 또는 로그인 페이지로 리다이렉션합니다. 추가로, 미들웨어가 일치해야 하는 요청 경로를 지정하는 구성 객체가 내보내집니다. Changes
Suggested reviewers
Tip ⚡🧪 Multi-step agentic review comment chat (experimental)
📜 Recent review detailsConfiguration used: .coderabbit.yml 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/middleware.ts (3)
7-7
: 파일 타입 감지 로직 개선 제안현재 파일 타입 검사 정규식이 다소 간단합니다. 좀 더 명확한 파일 타입 검사를 위해 확장자 기반의 구체적인 정규식으로 개선하는 것이 좋겠습니다.
- const isFile = request.nextUrl.pathname.match(/\.(.*)$/); + const isFile = request.nextUrl.pathname.match(/\.(css|js|png|jpg|jpeg|svg|ico|woff|woff2|ttf|otf)$/i);
19-21
: 토큰 검사 강화 고려현재는 토큰의 존재 여부만 확인하고 있습니다. 보안을 강화하기 위해 토큰 형식이나 유효성을 검사하는 로직을 추가하는 것을 고려해보세요.
35-37
: 원래 URL 저장 기능 고려PR 설명에서 언급된 대로, 인증되지 않은 사용자가 원래 접근하려던 페이지로 로그인 후 리다이렉션할 수 있는 기능을 구현하는 것을 고려해보세요. 이는 사용자 경험을 개선할 수 있습니다.
if (!isPublicPath && (!accessToken || !refreshToken)) { - return NextResponse.redirect(new URL('/login', request.url)); + const url = new URL('/login', request.url); + url.searchParams.set('callbackUrl', encodeURIComponent(request.nextUrl.pathname)); + return NextResponse.redirect(url); }
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/middleware.ts
(1 hunks)
🔇 Additional comments (2)
src/middleware.ts (2)
1-40
: 인증 미들웨어가 잘 구현되었습니다!미들웨어의 전체적인 흐름이 명확하며 주석을 통해 목적과 기능을 잘 설명하고 있습니다. 인증 상태에 따른 리다이렉션 로직이 PR 목적에 맞게 구현되었습니다.
29-32
: 리다이렉션 루프 방지 검사 추가현재 구현에서는 리다이렉션 루프가 발생할 가능성이 있습니다. 예를 들어, 특정 상황에서 무한히 리다이렉션이 발생할 수 있으므로 이를 방지하는 로직을 추가하는 것이 좋겠습니다.
const publicPaths = [ | ||
'/login', | ||
'/api/auth', // 인증 관련 API 경로 | ||
'/api/auth/callback', // 소셜 로그인 콜백 경로 | ||
]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
회원가입 경로 추가 필요
PR 목표에 따르면 로그인 및 회원가입 페이지에 대한 접근 제어가 필요합니다. 현재 publicPaths에 /login
만 포함되어 있고 회원가입(/signup
) 경로가 누락되어 있습니다.
const publicPaths = [
'/login',
+ '/signup',
'/api/auth', // 인증 관련 API 경로
'/api/auth/callback', // 소셜 로그인 콜백 경로
];
📝 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.
const publicPaths = [ | |
'/login', | |
'/api/auth', // 인증 관련 API 경로 | |
'/api/auth/callback', // 소셜 로그인 콜백 경로 | |
]; | |
const publicPaths = [ | |
'/login', | |
'/signup', | |
'/api/auth', // 인증 관련 API 경로 | |
'/api/auth/callback', // 소셜 로그인 콜백 경로 | |
]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
너무 수고 많으셨어요!!🤩
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@JaeIn1 고생하셨습니다 고민의 흔적이 보이네요.
하나 코멘트 드리고 싶다면, 미들웨어 같은 경우, 프로젝트의 모든 라우트에 대해 호출이 되기 때문에, 정확하게 타겟팅 하거나 , 특정 라우트 같은경우는 제외하는 것이 좋습니다.
이때 모든 라우트라고 하면, 정적 파일, api 라우트 등의 파일도 접근하기 때문에, 이러한 파일들은 제외해주는것이 좋습니다. 이 부분도 한번 살펴보면 좋을거 같습니다.
export const config = {
matcher: // 미들웨어가 동작할 route
}
- 예시
export const config = {
matcher: [
/*
* 다음으로 시작하는 경로를 제외한 모든 요청 경로를 매칭합니다:
* - api (API 라우트)
* - _next/static (정적 파일)
* - _next/image (이미지 최적화 파일)
* - favicon.ico (파비콘 파일)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}
레퍼런스 : https://nextjs-ko.org/docs/app/building-your-application/routing/middleware#matching-paths
@jangwonyoon 아아 이해했습니다. 수정해서 올리겠습니다 👍👍 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🔭 Outside diff range comments (1)
src/middleware.ts (1)
1-54
: 🛠️ Refactor suggestion코드 구성 및 가독성 개선
전반적으로 코드 구성과 가독성은 양호하지만, 중요한 로직들을 별도의 함수로 분리하여 더 모듈화하면 가독성과 유지보수성이 향상될 것입니다. 또한 코드에 대한 주석이 있어 이해하기 쉽습니다.
// middleware.ts import { NextResponse, NextRequest } from 'next/server'; + // 인증이 필요하지 않은 경로들 정의 + const publicPaths = [ + '/login', + '/signup', // 회원가입 경로 추가 + '/api/auth', // 인증 관련 API 경로 + '/api/auth/callback', // 소셜 로그인 콜백 경로 + ]; + + // 파일 확장자를 가진 경로인지 확인하는 함수 + function hasFileExtension(path: string): boolean { + return !!path.match(/\.(.*)$/); + } + + // 공개 경로인지 확인하는 함수 + function isPublicPath(path: string): boolean { + return publicPaths.some((publicPath) => path === publicPath || path.startsWith(`${publicPath}/`)); + } export function middleware(request: NextRequest) { try { // 현재 URL 경로 가져오기 const path = request.nextUrl.pathname; - const isFile = request.nextUrl.pathname.match(/\.(.*)$/); + const isFile = hasFileExtension(path); - // 인증이 필요하지 않은 경로들 - const publicPaths = [ - '/login', - '/api/auth', // 인증 관련 API 경로 - '/api/auth/callback', // 소셜 로그인 콜백 경로 - ]; - // 현재 경로가 public 경로인지 확인 - const isPublicPath = publicPaths.some((publicPath) => path === publicPath || path.startsWith(`${publicPath}/`)); + // 현재 경로가 public 경로인지 확인 + const isPathPublic = isPublicPath(path); // 토큰 확인 const accessToken = request.cookies.get('accessToken'); const refreshToken = request.cookies.get('refreshToken'); // 문자가 있는지 검사합니다 (예: .css, .js, .png 등). // 로그인 페이지 CSS 깨짐 현상 해결 if (isFile) { return NextResponse.next(); } // 토큰이 존재할 때 로그인 페이지에 접근한다면 /경로로 리다이렉트 - if (isPublicPath && accessToken && refreshToken) { + if (isPathPublic && accessToken && refreshToken) { return NextResponse.redirect(new URL('/', request.url)); } // 인증이 필요한 경로에 토큰 없이 접근하려고 하면 로그인 페이지로 리다이렉트 - if (!isPublicPath && (!accessToken || !refreshToken)) { + if (!isPathPublic && (!accessToken || !refreshToken)) { + const loginUrl = new URL('/login', request.url); + loginUrl.searchParams.set('redirectUrl', request.nextUrl.pathname); - return NextResponse.redirect(new URL('/login', request.url)); + return NextResponse.redirect(loginUrl); } return NextResponse.next(); + } catch (error) { + console.error('미들웨어 처리 중 오류 발생:', error); + return NextResponse.next(); + } } export const config = { matcher: [ /* * 다음으로 시작하는 경로를 제외한 모든 요청 경로를 매칭합니다: * - api (API 라우트) * - _next/static (정적 파일) * - _next/image (이미지 최적화 파일) * - favicon.ico (파비콘 파일) */ - '/((?!api|_next/static|_next/image|favicon.ico).*)', + // api 경로 중 auth 관련 경로는 미들웨어 적용이 필요하므로 제외 패턴 수정 필요 + '/((?!_next/static|_next/image|favicon.ico).*)', ], };
🧹 Nitpick comments (3)
src/middleware.ts (3)
7-7
: isFile 변수의 명확한 네이밍 및 설명 필요
isFile
변수는 확장자가 있는지 확인하는 정규식을 사용하지만, 실제로는 파일 여부를 확인하는 것이 아니라 요청된 경로에 확장자가 있는지만 확인합니다. 이에 대한 설명이나 변수명을 더 명확하게 수정하는 것이 좋겠습니다.- const isFile = request.nextUrl.pathname.match(/\.(.*)$/); + const hasFileExtension = request.nextUrl.pathname.match(/\.(.*)$/);
17-17
: publicPath 확인 로직 개선 필요현재 코드는 경로가 publicPath와 정확히 일치하거나 publicPath로 시작하는지 확인합니다. 그러나
/login/reset
과 같은 경로도 public으로 간주될 수 있으며, 이것이 의도적인지 확인해 볼 필요가 있습니다. 정확한 경로 매칭을 위해 로직을 개선하는 것이 좋겠습니다.- const isPublicPath = publicPaths.some((publicPath) => path === publicPath || path.startsWith(`${publicPath}/`)); + const isPublicPath = publicPaths.some((publicPath) => { + // 정확한 경로 일치 (예: '/login' === '/login') + if (path === publicPath) return true; + + // API 경로의 경우에만 하위 경로 포함 (예: '/api/auth/something') + if (publicPath.startsWith('/api/') && path.startsWith(`${publicPath}/`)) return true; + + return false; + });
34-37
: 리다이렉션 시 원래 URL 저장 기능 고려PR 목표에서 언급된 대로, 로그인 후 사용자를 원래 접근하려던 페이지로 리다이렉션하는 기능을 고려해볼 수 있습니다. 이를 위해 로그인 페이지로 리다이렉션할 때 원래 URL을 쿼리 파라미터로 전달하는 방식을 추가하면 좋겠습니다.
if (!isPublicPath && (!accessToken || !refreshToken)) { - return NextResponse.redirect(new URL('/login', request.url)); + const loginUrl = new URL('/login', request.url); + loginUrl.searchParams.set('redirectUrl', request.nextUrl.pathname); + return NextResponse.redirect(loginUrl); }
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/middleware.ts
(1 hunks)
🔇 Additional comments (1)
src/middleware.ts (1)
10-14
: 회원가입 경로 추가 필요PR 목표에 따르면 로그인 및 회원가입 페이지에 대한 접근 제어가 필요합니다. 현재 publicPaths에
/login
만 포함되어 있고 회원가입(/signup
) 경로가 누락되어 있습니다.const publicPaths = [ '/login', + '/signup', '/api/auth', // 인증 관련 API 경로 '/api/auth/callback', // 소셜 로그인 콜백 경로 ];
export function middleware(request: NextRequest) { | ||
// 현재 URL 경로 가져오기 | ||
const path = request.nextUrl.pathname; | ||
const isFile = request.nextUrl.pathname.match(/\.(.*)$/); | ||
|
||
// 인증이 필요하지 않은 경로들 | ||
const publicPaths = [ | ||
'/login', | ||
'/api/auth', // 인증 관련 API 경로 | ||
'/api/auth/callback', // 소셜 로그인 콜백 경로 | ||
]; | ||
|
||
// 현재 경로가 public 경로인지 확인 | ||
const isPublicPath = publicPaths.some((publicPath) => path === publicPath || path.startsWith(`${publicPath}/`)); | ||
|
||
// 토큰 확인 | ||
const accessToken = request.cookies.get('accessToken'); | ||
const refreshToken = request.cookies.get('refreshToken'); | ||
|
||
// 문자가 있는지 검사합니다 (예: .css, .js, .png 등). | ||
// 로그인 페이지 CSS 깨짐 현상 해결 | ||
if (isFile) { | ||
return NextResponse.next(); | ||
} | ||
|
||
// 토큰이 존재할 때 로그인 페이지에 접근한다면 /경로로 리다이렉트 | ||
if (isPublicPath && accessToken && refreshToken) { | ||
return NextResponse.redirect(new URL('/', request.url)); | ||
} | ||
|
||
// 인증이 필요한 경로에 토큰 없이 접근하려고 하면 로그인 페이지로 리다이렉트 | ||
if (!isPublicPath && (!accessToken || !refreshToken)) { | ||
return NextResponse.redirect(new URL('/login', request.url)); | ||
} | ||
|
||
return NextResponse.next(); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
에러 처리 로직 추가 필요
미들웨어 함수 내에서 발생할 수 있는 예외 상황(예: 쿠키 파싱 오류, URL 파싱 오류 등)에 대한 에러 처리 로직이 없습니다. try-catch 블록을 추가하여 예외 상황을 적절히 처리하는 것이 좋겠습니다.
export function middleware(request: NextRequest) {
+ try {
// 현재 URL 경로 가져오기
const path = request.nextUrl.pathname;
const isFile = request.nextUrl.pathname.match(/\.(.*)$/);
// ... 기존 코드 ...
return NextResponse.next();
+ } catch (error) {
+ console.error('미들웨어 처리 중 오류 발생:', error);
+ // 오류 발생 시 사용자 경험을 위해 기본 페이지로 리다이렉션하거나 요청 진행
+ return NextResponse.next();
+ }
}
📝 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.
export function middleware(request: NextRequest) { | |
// 현재 URL 경로 가져오기 | |
const path = request.nextUrl.pathname; | |
const isFile = request.nextUrl.pathname.match(/\.(.*)$/); | |
// 인증이 필요하지 않은 경로들 | |
const publicPaths = [ | |
'/login', | |
'/api/auth', // 인증 관련 API 경로 | |
'/api/auth/callback', // 소셜 로그인 콜백 경로 | |
]; | |
// 현재 경로가 public 경로인지 확인 | |
const isPublicPath = publicPaths.some((publicPath) => path === publicPath || path.startsWith(`${publicPath}/`)); | |
// 토큰 확인 | |
const accessToken = request.cookies.get('accessToken'); | |
const refreshToken = request.cookies.get('refreshToken'); | |
// 문자가 있는지 검사합니다 (예: .css, .js, .png 등). | |
// 로그인 페이지 CSS 깨짐 현상 해결 | |
if (isFile) { | |
return NextResponse.next(); | |
} | |
// 토큰이 존재할 때 로그인 페이지에 접근한다면 /경로로 리다이렉트 | |
if (isPublicPath && accessToken && refreshToken) { | |
return NextResponse.redirect(new URL('/', request.url)); | |
} | |
// 인증이 필요한 경로에 토큰 없이 접근하려고 하면 로그인 페이지로 리다이렉트 | |
if (!isPublicPath && (!accessToken || !refreshToken)) { | |
return NextResponse.redirect(new URL('/login', request.url)); | |
} | |
return NextResponse.next(); | |
} | |
export function middleware(request: NextRequest) { | |
try { | |
// 현재 URL 경로 가져오기 | |
const path = request.nextUrl.pathname; | |
const isFile = request.nextUrl.pathname.match(/\.(.*)$/); | |
// 인증이 필요하지 않은 경로들 | |
const publicPaths = [ | |
'/login', | |
'/api/auth', // 인증 관련 API 경로 | |
'/api/auth/callback', // 소셜 로그인 콜백 경로 | |
]; | |
// 현재 경로가 public 경로인지 확인 | |
const isPublicPath = publicPaths.some((publicPath) => path === publicPath || path.startsWith(`${publicPath}/`)); | |
// 토큰 확인 | |
const accessToken = request.cookies.get('accessToken'); | |
const refreshToken = request.cookies.get('refreshToken'); | |
// 문자가 있는지 검사합니다 (예: .css, .js, .png 등). | |
// 로그인 페이지 CSS 깨짐 현상 해결 | |
if (isFile) { | |
return NextResponse.next(); | |
} | |
// 토큰이 존재할 때 로그인 페이지에 접근한다면 /경로로 리다이렉트 | |
if (isPublicPath && accessToken && refreshToken) { | |
return NextResponse.redirect(new URL('/', request.url)); | |
} | |
// 인증이 필요한 경로에 토큰 없이 접근하려고 하면 로그인 페이지로 리다이렉트 | |
if (!isPublicPath && (!accessToken || !refreshToken)) { | |
return NextResponse.redirect(new URL('/login', request.url)); | |
} | |
return NextResponse.next(); | |
} catch (error) { | |
console.error('미들웨어 처리 중 오류 발생:', error); | |
// 오류 발생 시 사용자 경험을 위해 기본 페이지로 리다이렉션하거나 요청 진행 | |
return NextResponse.next(); | |
} | |
} |
if (isPublicPath && accessToken && refreshToken) { | ||
return NextResponse.redirect(new URL('/', request.url)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
토큰 유효성 검증 보완 필요
현재 코드는 토큰이 존재하는지만 확인하고 있으며, 토큰의 유효성(형식, 만료 여부 등)은 검증하지 않습니다. 보안을 강화하기 위해 토큰 유효성 검증 로직을 추가하는 것이 좋겠습니다.
if (isPublicPath && accessToken && refreshToken) {
+ // 토큰 유효성 검증 로직 추가 (예: JWT 검증)
+ // 이는 서버 측 검증이 필요할 수 있으므로 별도의 유틸리티 함수로 구현하는 것이 좋습니다
return NextResponse.redirect(new URL('/', request.url));
}
📝 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.
if (isPublicPath && accessToken && refreshToken) { | |
return NextResponse.redirect(new URL('/', request.url)); | |
} | |
if (isPublicPath && accessToken && refreshToken) { | |
// 토큰 유효성 검증 로직 추가 (예: JWT 검증) | |
// 이는 서버 측 검증이 필요할 수 있으므로 별도의 유틸리티 함수로 구현하는 것이 좋습니다 | |
return NextResponse.redirect(new URL('/', request.url)); | |
} |
📌 개요
📋 변경사항
기능
화면
고민한 점
리다이렉트 대상 페이지 선택
현재 구현: 로그인 상태에서 로그인 페이지 접근 시 홈('/')으로 리다이렉트
고려사항: 비로그인 사용자가 로그인이 필요한 페이지 접근 시 해당 URL을 저장했다가 로그인 후 원래 페이지로 돌려보내는 기능의 필요성
결정 이유: 현재 서비스는 대부분 로그인 후에만 접근 가능한 페이지로 구성되어 있어 단순 홈 리다이렉트로도 충분하다고 생각
참고: [리다이렉트를 어디로 할까?] - 참고자료(https://bsnn.tistory.com/179)
✅ 체크사항
Summary by CodeRabbit