Files
jh-monitor/src/middleware.ts
2025-09-15 16:29:49 +08:00

35 lines
966 B
TypeScript

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export const config = {
matcher: [
'/((?!_next|.well-known|favicon.ico|sitemap.xml|robots.txt).*(?<!\.svg|\.webp|\.jpg)$)',
],
}
const isIgnored = [
'/login',
"/api/auth/login"
]
export async function middleware(request: NextRequest) {
const session = request.cookies.get('session')
// 检查用户是否未登录
if (!session?.value) {
// 如果访问的是无需登录的页面,直接允许访问
if (isIgnored.some(path => request.nextUrl.pathname.startsWith(path))) {
return NextResponse.next()
}
// 其他路径都视为受保护路径,重定向到登录页
return NextResponse.redirect(new URL('/login', request.url))
}
// 给没有页面的路径添加跳转页面
if (request.nextUrl.pathname === '/') {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
return NextResponse.next()
}