Files
labelmain/middleware.ts
2026-02-05 18:19:45 +08:00

62 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server"
import { cookies } from "next/headers"
const publicRoutes = ["/login", "/"]
// 1. Specify protected and public routes
// const protectedRoutes = ["/dashboard"]
export default async function middleware(req: NextRequest) {
if (process.env.NEXT_PUBLIC_OUTPUT_TYPE !== "standalone")
return NextResponse.next()
const ua = req.headers.get("user-agent") || "Unknown"
const userAgentLower = ua.toLowerCase()
const isLark =
userAgentLower.includes("lark") || userAgentLower.includes("feishu")
// 2. Check if the current route is protected or public
const path = req.nextUrl.pathname
// const isProtectedRoute = protectedRoutes.includes(path)
const isPublicRoute = publicRoutes.includes(path)
// 3. Decrypt the session from the cookie
const cookie = (await cookies()).get("session")?.value
const session = cookie ? JSON.parse(cookie) : ""
// 4. Redirect to /login if the user is not authenticated
if (!isPublicRoute && !session) {
if (isLark) {
// 直接登录
console.log("Lark environment detected, redirecting with auto login")
return NextResponse.redirect(
new URL(
`${process.env.NEXT_PUBLIC_BASE_PATH}/login?auto=true`,
req.nextUrl
)
)
} else {
return NextResponse.redirect(
new URL(`${process.env.NEXT_PUBLIC_BASE_PATH}/login`, req.nextUrl)
)
}
}
// 5. Redirect to /dashboard if the user is authenticated
if (isPublicRoute && session && !path.startsWith("/management")) {
return NextResponse.redirect(
new URL(`${process.env.NEXT_PUBLIC_BASE_PATH}/management`, req.nextUrl)
)
}
return NextResponse.next()
}
// Routes Middleware should not run on
export const config = {
matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
}