forked from depromeet/Swimie-Web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
63 lines (51 loc) · 1.92 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
53
54
55
56
57
58
59
60
61
62
63
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { NewTokenData } from './apis/refresh-token';
export async function middleware(request: NextRequest) {
let accessToken = request.cookies.get('accessToken')?.value;
const refreshToken = request.cookies.get('refreshToken')?.value;
const loginPageRegex = /^\/login$/;
const isLoginPage = loginPageRegex.test(request.nextUrl.pathname);
// NOTE: refreshToken이 없으면 로그인 페이지로 리다이렉트
if (!refreshToken) {
return NextResponse.redirect(new URL('/login', request.url));
}
// NOTE: accessToken이 없으면 재발급 시도
if (!accessToken) {
const refreshResponse = await fetch(
`${process.env.NEXT_PUBLIC_SERVER_URL}/login/refresh`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: refreshToken,
},
},
);
if (refreshResponse.ok) {
const data = (await refreshResponse.json()) as NewTokenData;
accessToken = `Bearer ${data.data.accessToken}`;
const response = NextResponse.next();
response.cookies.set('accessToken', accessToken, {
maxAge: 3600, // 1시간
httpOnly: true,
secure: true,
});
response.headers.set('Authorization', accessToken);
// NOTE: 로그인 페이지일 경우, '/' 경로로 리다이렉트
if (isLoginPage) {
return NextResponse.redirect(new URL('/', request.url));
}
return response;
} else {
// NOTE: 리프레시 토큰이 유효하지 않은 경우 로그인 페이지로 리다이렉트
return NextResponse.redirect(new URL('/login', request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|fonts|images|login|kakao/oauth|google/oauth|setting/privacy-policy|setting/terms).*)',
],
};