68 lines
2.0 KiB
TypeScript
68 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { verifyToken, AUTH_COOKIE_NAME } from './lib/auth'
|
|
|
|
export async function middleware(req: NextRequest) {
|
|
const url = new URL(req.url)
|
|
|
|
// Skip auth for certain paths
|
|
if (
|
|
url.pathname.startsWith('/api/auth/login') || // Allow login API
|
|
url.pathname.startsWith('/api/') || // Other APIs might need their own auth or be public
|
|
url.pathname.startsWith('/screenshots/') ||
|
|
url.pathname.startsWith('/downloads/') ||
|
|
url.pathname.startsWith('/manifest.json') ||
|
|
url.pathname.startsWith('/sw.js') ||
|
|
url.pathname.includes('favicon.png') ||
|
|
url.pathname.includes('install') ||
|
|
url.pathname.includes('WinupdateCore') ||
|
|
req.method === 'POST' || // Remove this blanket allowance for POST
|
|
url.pathname.startsWith('/_next/') ||
|
|
url.pathname.startsWith('/api-test')
|
|
) {
|
|
return NextResponse.next()
|
|
}
|
|
|
|
const authCookie = req.cookies.get(AUTH_COOKIE_NAME)
|
|
const isLoginPage = url.pathname === '/login'
|
|
let isValidToken = false
|
|
|
|
if (authCookie) {
|
|
isValidToken = await verifyToken(authCookie.value)
|
|
}
|
|
|
|
// Handle Login Page
|
|
if (isLoginPage) {
|
|
if (isValidToken) {
|
|
// If already logged in, redirect to home
|
|
return NextResponse.redirect(new URL('/', req.url))
|
|
}
|
|
// Allow access to login page
|
|
return NextResponse.next()
|
|
}
|
|
|
|
// Handle Protected Routes
|
|
if (!isValidToken) {
|
|
// Redirect to login page if not authenticated
|
|
const loginUrl = new URL('/login', req.url)
|
|
// Optional: Add return URL support
|
|
// loginUrl.searchParams.set('from', url.pathname)
|
|
return NextResponse.redirect(loginUrl)
|
|
}
|
|
|
|
return NextResponse.next()
|
|
}
|
|
|
|
// 配置中间件匹配的路径
|
|
export const config = {
|
|
matcher: [
|
|
/*
|
|
* Match all request paths except for the ones starting with:
|
|
* - api (API routes)
|
|
* - _next/static (static files)
|
|
* - _next/image (image optimization files)
|
|
* - favicon.ico (favicon file)
|
|
*/
|
|
'/((?!_next/static|_next/image|favicon.ico|manifest.json|sw.js).*)',
|
|
],
|
|
}
|