-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
128 lines (110 loc) · 3.7 KB
/
middleware.ts
File metadata and controls
128 lines (110 loc) · 3.7 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
const locales = [
'zh', // Chinese
'en', // English
'fil', // Filipino
'fr', // French
'de', // German
'el', // Greek
'he', // Hebrew
'hi', // Hindi
'it', // Italian
'ja', // Japanese
'ko', // Korean
'pl', // Polish
'pt', // Portuguese
'ru', // Russian
'es', // Spanish
'th', // Thai
];
const defaultLocale = 'en';
const botUserAgents = [
'SentryUptimeBot',
'UptimeRobot',
'Pingdom',
'Site24x7',
'BetterUptime',
'StatusCake',
'AhrefsBot',
'SemrushBot',
'MJ12bot',
'DotBot',
'PetalBot',
'Bytespider',
];
const isBotRequest = (userAgent: string | null): boolean => {
if (!userAgent) return false;
return botUserAgents.some((botSubstring) => userAgent.includes(botSubstring));
};
const handleBotFiltering = (req: NextRequest): NextResponse | null => {
const userAgent = req.headers.get('user-agent');
if (isBotRequest(userAgent)) {
console.log(`[Middleware] Blocking bot: ${userAgent || 'unknown'}. Returning 200 OK.`);
return new NextResponse(null, { status: 200 });
}
return null;
};
const handleLocaleRedirect = (req: NextRequest): NextResponse | null => {
const pathname = req.nextUrl.pathname;
const isAdminRoute = pathname.startsWith('/admin');
const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
if (pathnameIsMissingLocale && !isAdminRoute) {
const locale = req.cookies.get('NEXT_LOCALE')?.value || defaultLocale;
const url = req.nextUrl.clone();
url.pathname = `/${locale}${pathname}`;
return NextResponse.redirect(url);
}
return null;
};
const handleAdminRoute = (req: NextRequest, isAdmin: boolean): NextResponse | null => {
const pathname = req.nextUrl.pathname;
const isAdminRoute = pathname.startsWith('/admin');
if (isAdminRoute && !isAdmin) {
console.log(`[Middleware] Redirecting non-admin from /admin to /`);
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = `/${defaultLocale}`;
return NextResponse.redirect(redirectUrl);
}
return null;
};
const middleware = async (req: NextRequest) => {
const botResponse = handleBotFiltering(req);
if (botResponse) return botResponse;
const localeRedirectResponse = handleLocaleRedirect(req);
if (localeRedirectResponse) return localeRedirectResponse;
const token = await getToken({ req });
const isAdmin = token?.isAdmin === true;
const adminRouteResponse = handleAdminRoute(req, isAdmin);
if (adminRouteResponse) return adminRouteResponse;
try {
const ip = req.headers.get('fly-client-ip') || req.headers.get('x-forwarded-for') || 'unknown';
const userAgent = req.headers.get('user-agent') || 'unknown';
const pathname = req.nextUrl.pathname;
// Reduce logging verbosity in production
if (process.env.NODE_ENV !== 'production') {
console.log(
`[Middleware] Request: ${req.method} ${pathname} - IP: ${ip} - User-Agent: ${userAgent}`
);
console.log(`[Middleware] isAdmin check result: ${isAdmin}`);
console.log(`[Middleware] Allowing access to ${pathname}`);
} else {
// Only log errors and admin access attempts in production
if (pathname.startsWith('/admin')) {
console.log(
`[Middleware] Admin access attempt: ${req.method} ${pathname} - IP: ${ip} - Admin: ${isAdmin}`
);
}
}
return NextResponse.next();
} catch {
return new NextResponse('Internal Server Error', { status: 500 });
}
};
export default middleware;
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico|sw.js|manifest.json).*)'],
};