forked from fastcampus-final-project/fast-final-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
52 lines (42 loc) · 1.7 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { NextResponse, NextRequest } from 'next/server';
import { protectedRoutes, authRedirectRoutes, apiAuthPrefix } from './routes';
import { currentUserSession } from './shared/actions/auth';
import { match } from 'path-to-regexp';
/**
* 인증 및 권한 부여 ,서버 측 리디렉션, 경로 재작성
*/
const middleware = async (request: NextRequest) => {
const { nextUrl } = request;
const session = await currentUserSession();
const isLoggedIn = !!session;
if (isApiAuthRequest(nextUrl.pathname)) {
return NextResponse.next();
}
// 로그인이 필요한 경로에 대한 처리
if (isProtectedRoute(nextUrl.pathname)) {
if (!isLoggedIn) {
return NextResponse.redirect(new URL('/auth/login', nextUrl));
}
// /bucket-landing으로 접속할 경우 tab=저축생활+1편으로 주소 바꿈
if (nextUrl.pathname === '/bucket-landing' && !nextUrl.searchParams.get('tab')) {
return NextResponse.redirect(new URL('/bucket-landing?tab=저축생활+1편', nextUrl));
}
return NextResponse.next();
}
// 로그인 한 사용자가 접근하면 홈으로 리디렉션
if (isAuthRedirectRoute(nextUrl.pathname)) {
if (isLoggedIn) {
return NextResponse.redirect(new URL('/', nextUrl));
}
return NextResponse.next();
}
};
export default middleware;
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']
};
const isApiAuthRequest = (pathname: string) => pathname.startsWith(apiAuthPrefix);
const isProtectedRoute = (pathname: string) =>
protectedRoutes.some((url) => Boolean(match(url)(pathname)));
const isAuthRedirectRoute = (pathname: string) =>
authRedirectRoutes.some((url) => Boolean(match(url)(pathname)));