-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.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).*)',
],
};