lty/qy-lty-admin/middleware.ts
2026-03-17 13:17:02 +08:00

44 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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()
}