feat(project): init
This commit is contained in:
61
middleware.ts
Normal file
61
middleware.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
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("/show")) {
|
||||
return NextResponse.redirect(
|
||||
new URL(`${process.env.NEXT_PUBLIC_BASE_PATH}/show`, req.nextUrl)
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
// Routes Middleware should not run on
|
||||
export const config = {
|
||||
matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
|
||||
}
|
||||
Reference in New Issue
Block a user