73 lines
2.1 KiB
TypeScript
73 lines
2.1 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { config } from './lib/config'
|
|
|
|
export function middleware(req: NextRequest) {
|
|
const url = new URL(req.url)
|
|
|
|
// Skip auth for certain paths (same logic as original Express app)
|
|
if (
|
|
url.pathname.startsWith('/api/') ||
|
|
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' ||
|
|
url.pathname.startsWith('/_next/') || // Next.js static files
|
|
url.pathname.startsWith('/api-test') // API test page (for development)
|
|
) {
|
|
return NextResponse.next()
|
|
}
|
|
|
|
// For all other paths, require authentication
|
|
const authHeader = req.headers.get('authorization')
|
|
|
|
if (!authHeader) {
|
|
return new NextResponse('Authentication required', {
|
|
status: 401,
|
|
headers: {
|
|
'WWW-Authenticate': 'Basic realm="Restricted Access"'
|
|
}
|
|
})
|
|
}
|
|
|
|
try {
|
|
const auth = Buffer.from(authHeader.split(' ')[1], 'base64').toString()
|
|
const [username, password] = auth.split(':')
|
|
|
|
if (username === config.auth.username && password === config.auth.password) {
|
|
return NextResponse.next()
|
|
} else {
|
|
return new NextResponse('Authentication failed', {
|
|
status: 401,
|
|
headers: {
|
|
'WWW-Authenticate': 'Basic realm="Restricted Access"'
|
|
}
|
|
})
|
|
}
|
|
} catch {
|
|
return new NextResponse('Invalid authentication', {
|
|
status: 401,
|
|
headers: {
|
|
'WWW-Authenticate': 'Basic realm="Restricted Access"'
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// 配置中间件匹配的路径
|
|
export const config_middleware = {
|
|
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).*)',
|
|
],
|
|
}
|