Files
labelmain-demo/middleware.ts
2026-04-23 14:47:14 +08:00

66 lines
2.0 KiB
TypeScript

import {
getSessionRedisKeyFromCookieValue,
SESSION_COOKIE_NAME,
} from "@/components/login/libs/session-common"
import { NextRequest, NextResponse } from "next/server"
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. Resolve the session key from the cookie
const session = getSessionRedisKeyFromCookieValue(
req.cookies.get(SESSION_COOKIE_NAME)?.value
)
// 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`,
`/login?auto=true`,
req.nextUrl
)
)
} else {
return NextResponse.redirect(
// new URL(`${process.env.NEXT_PUBLIC_BASE_PATH}/login`, req.nextUrl)
new URL(`/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$).*)"],
}