-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
63 lines (56 loc) ยท 1.75 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 { NextResponse } from 'next/server';
import { withAuth, NextRequestWithAuth } from 'next-auth/middleware';
export default withAuth(
async function middleware(request: NextRequestWithAuth) {
console.log('middleware ์คํ', {
path: request.nextUrl.pathname,
token: request.nextauth.token,
});
// ํ ํฐ์ด ์๊ฑฐ๋ ๋ง๋ฃ๋ ๊ฒฝ์ฐ
if (!request.nextauth.token) {
return NextResponse.json(
{ error: '์ธ์ฆ๋์ง ์์ ์์ฒญ์
๋๋ค.' },
{ status: 401 }
);
}
// ํ ํฐ์ ๋ง๋ฃ ์๊ฐ ํ์ธ
const tokenExpires = request.nextauth.token.accessTokenExpires as number;
if (tokenExpires && Date.now() > tokenExpires) {
return NextResponse.json(
{ error: 'ํ ํฐ์ด ๋ง๋ฃ๋์์ต๋๋ค.' },
{ status: 401 }
);
}
// userId์ nickname์ ํ ํฐ์์ ์ถ์ถ
const userId = request.nextauth.token.userId as string;
const nickname = request.nextauth.token.nickname as string;
if (!userId || !nickname) {
return NextResponse.json(
{ error: '์ ์ ์ ๋ณด๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค.' },
{ status: 401 }
);
}
// userId์ ์ธ์ฝ๋ฉ๋ nickname์ ํค๋์ ์ถ๊ฐ
const response = NextResponse.next();
response.headers.set('User-Id', userId);
response.headers.set('Nickname', encodeURIComponent(nickname));
return response;
},
{
callbacks: {
authorized: ({ token }) => !!token,
},
pages: {
signIn: '/login',
},
}
);
// ๋ฏธ๋ค์จ์ด๋ฅผ ์ ์ฉํ ๊ฒฝ๋ก ์ค์
export const config = {
matcher: [
// API ๊ฒฝ๋ก์ ๋ํด์๋ง ์ ์ฉ
'/api/:path*',
// auth ๊ด๋ จ ๊ฒฝ๋ก๋ ์ ์ธ
'/((?!api/auth|_next/static|_next/image|favicon.ico|login|$).*)',
],
};