-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
58 lines (50 loc) · 1.56 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
import { jwtDecode } from 'jwt-decode';
import createMiddleware from 'next-intl/middleware';
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import {
COOKIE_KEYS,
privateRoutes,
protectedRoutes,
} from './app/lib/constants';
import { AccessToken } from './app/lib/utils/validation/assert/jwt';
const i18nMiddleware = createMiddleware({
locales: ['en', 'ko'],
defaultLocale: 'ko',
localeDetection: true,
});
const middleware = async (req: NextRequest) => {
const response = i18nMiddleware(req);
const path = req.nextUrl.pathname;
const isProtectedRoute = protectedRoutes.some((route) =>
path.includes(route),
);
const isPrivateRoute = privateRoutes.some((route) => path.includes(route));
if (isProtectedRoute) {
const jwt = cookies().get(COOKIE_KEYS.accessToken)?.value;
if (!jwt) {
return NextResponse.redirect(new URL(`/ko/login`, req.nextUrl));
}
const { userRole } = jwtDecode<AccessToken>(jwt);
const userRoles = userRole.split(',');
const isAdmin = userRoles.includes('ROLE_ADMIN');
if (!isAdmin) {
return NextResponse.redirect(new URL('/', req.nextUrl));
}
} else if (isPrivateRoute) {
const jwt = cookies().get(COOKIE_KEYS.accessToken)?.value;
if (!jwt) {
return NextResponse.redirect(
new URL(
`/ko/login?redirect=${encodeURIComponent(req.nextUrl.pathname)}`,
req.nextUrl,
),
);
}
}
return response;
};
export const config = {
matcher: ['/', '/(ko|en)/:path*'],
};
export default middleware;