-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
79 lines (70 loc) · 2.19 KB
/
Copy pathproxy.ts
File metadata and controls
79 lines (70 loc) · 2.19 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
import { auth } from '@/lib/auth'
import { authRateLimit, contactRateLimit } from '@/lib/ratelimit'
import { NextResponse } from 'next/server'
export default auth(async (req) => {
const { pathname } = req.nextUrl
const session = req.auth
const ip = (req.headers.get('x-forwarded-for') ?? '').split(',')[0].trim() || '127.0.0.1'
// Rate limiting:auth 相關 API
if (
pathname.startsWith('/api/login') ||
pathname.startsWith('/api/signup') ||
pathname === '/api/auth/callback/credentials'
) {
const { success } = await authRateLimit.limit(ip)
if (!success) {
return NextResponse.json(
{ errors: [{ message: 'Too many requests. Please try again later.' }] },
{ status: 429 }
)
}
}
// Rate limiting:contact
if (pathname.startsWith('/api/contact')) {
const { success } = await contactRateLimit.limit(ip)
if (!success) {
return NextResponse.json(
{ errors: [{ message: 'Too many requests. Please try again later.' }] },
{ status: 429 }
)
}
}
// 保護 /account/* 頁面
if (pathname.startsWith('/account') || pathname.startsWith('/logout')) {
if (!session?.user?.roles?.account) {
const loginUrl = new URL('/login', req.url)
loginUrl.searchParams.set('returnUrl', pathname)
return NextResponse.redirect(loginUrl)
}
}
// 保護 /admin/* 頁面
if (pathname.startsWith('/admin')) {
if (!session?.user?.roles?.admin) {
const loginUrl = new URL('/login', req.url)
loginUrl.searchParams.set('returnUrl', pathname)
return NextResponse.redirect(loginUrl)
}
}
// 保護 /api/account/* 端點
if (pathname.startsWith('/api/account')) {
if (!session?.user?.roles?.account) {
return NextResponse.json(
{ errors: [{ message: 'Unauthorized' }] },
{ status: 401 }
)
}
}
// 保護 /api/admin/* 端點
if (pathname.startsWith('/api/admin')) {
if (!session?.user?.roles?.admin) {
return NextResponse.json(
{ errors: [{ message: 'Unauthorized' }] },
{ status: 401 }
)
}
}
return NextResponse.next()
})
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)']
}