2025-12-29 14:37:03 +08:00
|
|
|
import { type NextRequest, NextResponse, type ProxyConfig } from "next/server"
|
|
|
|
|
import { refreshAuth } from "@/actions/auth"
|
|
|
|
|
|
|
|
|
|
export const config: ProxyConfig = {
|
|
|
|
|
matcher: [
|
|
|
|
|
"/((?!api|_next/static|_next/image|.well-known|sw.js|favicon.ico|sitemap.xml|robots.txt).*(?<!.svg|.webp|.jpg)$)",
|
|
|
|
|
],
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function proxy(request: NextRequest) {
|
|
|
|
|
console.log(
|
|
|
|
|
"👀 middleware triggered",
|
|
|
|
|
request.method,
|
|
|
|
|
request.nextUrl.pathname,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// 记录请求页面
|
|
|
|
|
request.headers.set("x-pathname", request.nextUrl.pathname)
|
|
|
|
|
|
|
|
|
|
// 刷新访问令牌
|
|
|
|
|
try {
|
2026-01-09 17:34:57 +08:00
|
|
|
const accessToken = request.cookies.get("admin/auth_token")
|
|
|
|
|
const refreshToken = request.cookies.get("admin/auth_refresh")
|
2025-12-29 14:37:03 +08:00
|
|
|
if (!accessToken && !!refreshToken) {
|
|
|
|
|
console.log("💡 refresh token")
|
|
|
|
|
const token = await refreshAuth()
|
2026-01-09 17:34:57 +08:00
|
|
|
request.cookies.set("admin/auth_token", token.access_token)
|
|
|
|
|
request.cookies.set("admin/auth_refresh", token.refresh_token)
|
2025-12-29 14:37:03 +08:00
|
|
|
}
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.log("刷新访问令牌失败", request.url, (e as Error).message)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 验证访问令牌
|
2026-01-09 17:34:57 +08:00
|
|
|
const hasToken = !!request.cookies.get("admin/auth_token")
|
|
|
|
|
// const isToAdmin = request.nextUrl.pathname.startsWith("/admin")
|
|
|
|
|
const protectedPaths = ["/", "/admin"]
|
|
|
|
|
const isProtectedPath = protectedPaths.some(
|
|
|
|
|
path =>
|
|
|
|
|
request.nextUrl.pathname === path ||
|
|
|
|
|
request.nextUrl.pathname.startsWith(`${path}/`),
|
|
|
|
|
)
|
|
|
|
|
if (!hasToken && isProtectedPath) {
|
2025-12-29 14:37:03 +08:00
|
|
|
return NextResponse.redirect(
|
|
|
|
|
`${request.nextUrl.origin}/login?redirect=${request.nextUrl.pathname}`,
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return NextResponse.next({ request })
|
|
|
|
|
}
|