Skip to content
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

Merged
merged 4 commits into from
Mar 18, 2025
Merged

Conversation

JaeIn1
Copy link
Collaborator

@JaeIn1 JaeIn1 commented Mar 17, 2025

📌 개요

  • 인증 미들웨어 구현을 통한 접근 제어 기능 추가

📋 변경사항

  • Next.js 미들웨어를 이용한 인증 상태 기반 라우팅 구현

기능

  • 비로그인 사용자가 페이지 접근 시 로그인 페이지로 자동 리다이렉트
  • 로그인 상태에서 로그인/회원가입 페이지 접근 시 메인 페이지로 리다이렉트

화면

기능 스크린샷

고민한 점

리다이렉트 대상 페이지 선택

현재 구현: 로그인 상태에서 로그인 페이지 접근 시 홈('/')으로 리다이렉트
고려사항: 비로그인 사용자가 로그인이 필요한 페이지 접근 시 해당 URL을 저장했다가 로그인 후 원래 페이지로 돌려보내는 기능의 필요성
결정 이유: 현재 서비스는 대부분 로그인 후에만 접근 가능한 페이지로 구성되어 있어 단순 홈 리다이렉트로도 충분하다고 생각
참고: [리다이렉트를 어디로 할까?] - 참고자료(https://bsnn.tistory.com/179)

✅ 체크사항

  • 기능이 정상적으로 동작하는지 확인
  • 코드 스타일 및 규칙 준수 확인
  • UI가 변경된 경우 스크린샷 첨부 여부 확인

Summary by CodeRabbit

  • New Features
    • 사용자의 인증 상태와 요청 경로에 따라 자동으로 리디렉션되는 기능이 도입되었습니다.
      • 보호된 콘텐츠 접근 시 로그인 페이지로, 이미 인증된 사용자가 공용 페이지에 접속할 경우 홈 페이지로 리디렉션됩니다.
    • 정적 자원(CSS, JavaScript, 이미지 등) 요청은 기존 방식대로 원활하게 처리됩니다.

@JaeIn1 JaeIn1 added the 🚀 feature 새로운 기능 개발 label Mar 17, 2025
@JaeIn1 JaeIn1 self-assigned this Mar 17, 2025
@JaeIn1 JaeIn1 linked an issue Mar 17, 2025 that may be closed by this pull request
1 task
Copy link

coderabbitai bot commented Mar 17, 2025

📝 Walkthrough

Walkthrough

이 PR은 인증 및 접근 제어를 처리하는 새로운 미들웨어 함수를 추가합니다. 해당 함수는 요청의 URL 경로를 확인하고, 미리 정의된 공개 경로 목록과 비교하여 인증 필요 여부를 판단합니다. 또한 요청 쿠키에서 액세스 및 리프레시 토큰의 존재를 확인합니다. 파일 타입(CSS, JS, PNG 등)의 경우 인증 검증 없이 요청을 진행하며, 인증 상태 및 경로에 따라 사용자를 홈 페이지 또는 로그인 페이지로 리다이렉션합니다. 추가로, 미들웨어가 일치해야 하는 요청 경로를 지정하는 구성 객체가 내보내집니다.

Changes

파일 변경 요약
src/middleware.ts 새로운 미들웨어 함수 추가: URL 경로 확인, 토큰 체크, 공개/보호 경로 판별 및 리다이렉션 구현, 구성 객체 내보냄

Suggested reviewers

  • jangwonyoon
  • evenway2025
  • youngju6143

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 127e110 and 07c245f.

📒 Files selected for processing (1)
  • src/middleware.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/middleware.ts

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 66d3062 and 9298af3.

📒 Files selected for processing (1)
  • src/middleware.ts (1 hunks)
🔇 Additional comments (2)
src/middleware.ts (2)

1-40: 인증 미들웨어가 잘 구현되었습니다!

미들웨어의 전체적인 흐름이 명확하며 주석을 통해 목적과 기능을 잘 설명하고 있습니다. 인증 상태에 따른 리다이렉션 로직이 PR 목적에 맞게 구현되었습니다.


29-32: 리다이렉션 루프 방지 검사 추가

현재 구현에서는 리다이렉션 루프가 발생할 가능성이 있습니다. 예를 들어, 특정 상황에서 무한히 리다이렉션이 발생할 수 있으므로 이를 방지하는 로직을 추가하는 것이 좋겠습니다.

Comment on lines +10 to +14
const publicPaths = [
'/login',
'/api/auth', // 인증 관련 API 경로
'/api/auth/callback', // 소셜 로그인 콜백 경로
];
Copy link

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.

Suggested change
const publicPaths = [
'/login',
'/api/auth', // 인증 관련 API 경로
'/api/auth/callback', // 소셜 로그인 콜백 경로
];
const publicPaths = [
'/login',
'/signup',
'/api/auth', // 인증 관련 API 경로
'/api/auth/callback', // 소셜 로그인 콜백 경로
];

Copy link
Collaborator

@youngju6143 youngju6143 left a comment

Choose a reason for hiding this comment

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

너무 수고 많으셨어요!!🤩

Copy link
Collaborator

@jangwonyoon jangwonyoon left a 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

@JaeIn1
Copy link
Collaborator Author

JaeIn1 commented Mar 17, 2025

@jangwonyoon 아아 이해했습니다. 수정해서 올리겠습니다 👍👍

Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9298af3 and 127e110.

📒 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', // 소셜 로그인 콜백 경로
];

Comment on lines +4 to +40
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();
}
Copy link

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.

Suggested change
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();
}
}

Comment on lines +30 to +32
if (isPublicPath && accessToken && refreshToken) {
return NextResponse.redirect(new URL('/', request.url));
}
Copy link

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.

Suggested change
if (isPublicPath && accessToken && refreshToken) {
return NextResponse.redirect(new URL('/', request.url));
}
if (isPublicPath && accessToken && refreshToken) {
// 토큰 유효성 검증 로직 추가 (예: JWT 검증)
// 이는 서버 측 검증이 필요할 수 있으므로 별도의 유틸리티 함수로 구현하는 것이 좋습니다
return NextResponse.redirect(new URL('/', request.url));
}

@JaeIn1 JaeIn1 merged commit ba7a46d into develop Mar 18, 2025
2 checks passed
@JaeIn1 JaeIn1 deleted the feat/#82-login-middleware branch March 18, 2025 13:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🚀 feature 새로운 기능 개발
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[feat] 로그인 미들웨어 설정
3 participants