-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathmiddleware.ts
More file actions
140 lines (119 loc) · 4.17 KB
/
middleware.ts
File metadata and controls
140 lines (119 loc) · 4.17 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
129
130
131
132
133
134
135
136
137
138
139
140
import { auth } from "@/lib/auth"
import { NextResponse } from "next/server"
import { i18n, type Locale } from "@/i18n/config"
import { PERMISSIONS } from "@/lib/permissions"
import { checkPermission } from "@/lib/auth"
import { Permission } from "@/lib/permissions"
import { handleApiKeyAuth } from "@/lib/apiKey"
const API_PERMISSIONS: Record<string, Permission> = {
'/api/emails': PERMISSIONS.MANAGE_EMAIL,
'/api/webhook': PERMISSIONS.MANAGE_WEBHOOK,
'/api/roles/promote': PERMISSIONS.PROMOTE_USER,
'/api/config': PERMISSIONS.MANAGE_CONFIG,
'/api/api-keys': PERMISSIONS.MANAGE_API_KEY,
}
export async function middleware(request: Request) {
const url = new URL(request.url)
const pathname = url.pathname
if (pathname.startsWith('/api')) {
if (pathname.startsWith('/api/auth')) {
return NextResponse.next()
}
request.headers.delete("X-User-Id")
const apiKey = request.headers.get("X-API-Key")
if (apiKey) {
return handleApiKeyAuth(apiKey, pathname)
}
const session = await auth()
if (!session?.user) {
return NextResponse.json(
{ error: "未授权" },
{ status: 401 }
)
}
if (pathname === '/api/config' && request.method === 'GET') {
return NextResponse.next()
}
for (const [route, permission] of Object.entries(API_PERMISSIONS)) {
if (pathname.startsWith(route)) {
const hasAccess = await checkPermission(permission)
if (!hasAccess) {
return NextResponse.json(
{ error: "权限不足" },
{ status: 403 }
)
}
break
}
}
return NextResponse.next()
}
// Pages: 语言前缀
const segments = pathname.split('/')
const maybeLocale = segments[1]
const hasLocalePrefix = i18n.locales.includes(maybeLocale as any)
if (!hasLocalePrefix) {
const cookieLocale = request.headers.get('Cookie')?.match(/NEXT_LOCALE=([^;]+)/)?.[1]
const acceptLanguage = request.headers.get('Accept-Language')
const preferredLocale = resolvePreferredLocale(cookieLocale, acceptLanguage)
const targetLocale = preferredLocale ?? i18n.defaultLocale
const redirectURL = new URL(`/${targetLocale}${pathname}${url.search}`, request.url)
return NextResponse.redirect(redirectURL)
}
return NextResponse.next()
}
function resolvePreferredLocale(cookieLocale: string | undefined, acceptLanguageHeader: string | null): Locale | null {
if (cookieLocale && i18n.locales.includes(cookieLocale as Locale)) {
return cookieLocale as Locale
}
if (!acceptLanguageHeader) return null
const candidates = parseAcceptLanguage(acceptLanguageHeader)
for (const lang of candidates) {
const match = matchLocale(lang)
if (match) {
return match
}
}
return null
}
function parseAcceptLanguage(header: string): string[] {
return header
.split(',')
.map((part) => {
const [lang, ...params] = part.trim().split(';')
const qualityParam = params.find((param) => param.trim().startsWith('q='))
const quality = qualityParam ? parseFloat(qualityParam.split('=')[1]) : 1
return { lang: lang.toLowerCase(), quality: isNaN(quality) ? 1 : quality }
})
.sort((a, b) => b.quality - a.quality)
.map((entry) => entry.lang)
}
function matchLocale(lang: string): Locale | null {
const exactMatch = i18n.locales.find((locale) => locale.toLowerCase() === lang)
if (exactMatch) return exactMatch
const base = lang.split('-')[0]
// Handle Chinese variants with explicit regions or scripts
if (base === 'zh') {
if (lang.includes('tw') || lang.includes('hk') || lang.includes('mo') || lang.includes('hant')) {
return 'zh-TW'
}
if (lang.includes('cn') || lang.includes('sg') || lang.includes('hans')) {
return 'zh-CN'
}
// default Chinese fallback
return 'zh-CN'
}
const baseMatch = i18n.locales.find((locale) => locale.toLowerCase().split('-')[0] === base)
if (baseMatch) return baseMatch
return null
}
export const config = {
matcher: [
'/((?!_next|.*\\..*).*)', // all pages excluding static assets
'/api/emails/:path*',
'/api/webhook/:path*',
'/api/roles/:path*',
'/api/config/:path*',
'/api/api-keys/:path*',
]
}