44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
import { NextResponse } from 'next/server'
|
||
import type { NextRequest } from 'next/server'
|
||
|
||
// 需要身份验证的路径
|
||
const protectedPaths = [
|
||
'/',
|
||
'/dashboard',
|
||
'/users',
|
||
'/roles',
|
||
'/ai-models',
|
||
'/outfits',
|
||
'/props',
|
||
'/songs',
|
||
'/settings',
|
||
]
|
||
|
||
export function middleware(request: NextRequest) {
|
||
// 获取当前路径
|
||
const { pathname } = request.nextUrl
|
||
|
||
// 检查是否为需要身份验证的路径
|
||
const isProtectedPath = protectedPaths.some(path =>
|
||
pathname === path || pathname.startsWith(`${path}/`)
|
||
)
|
||
|
||
// 登录页和其他公共页面可以跳过验证
|
||
if (!isProtectedPath) {
|
||
return NextResponse.next()
|
||
}
|
||
|
||
// 从 Cookie 中获取 token
|
||
const token = request.cookies.get('auth_token')?.value
|
||
|
||
// 如果没有 token,重定向到登录页
|
||
if (!token) {
|
||
const url = new URL('/login', request.url)
|
||
// 保存原始 URL 以便登录后重定向回来
|
||
url.searchParams.set('callbackUrl', pathname)
|
||
return NextResponse.redirect(url)
|
||
}
|
||
|
||
// 如果有 token,继续请求
|
||
return NextResponse.next()
|
||
}
|