winupdate-neo/lib/middleware.ts
2025-06-28 15:16:06 +08:00

68 lines
2.0 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { config } from './config'
export function withAuth(handler: (req: NextRequest) => Promise<NextResponse>) {
return async (req: NextRequest) => {
const url = new URL(req.url)
// Skip auth for certain paths
if (
url.pathname.startsWith('/api/') ||
url.pathname.startsWith('/screenshots/') ||
url.pathname.startsWith('/downloads/') ||
url.pathname.includes('install') ||
url.pathname.includes('WinupdateCore') ||
req.method === 'POST'
) {
return handler(req)
}
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 handler(req)
} 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 function withCors(handler: (req: NextRequest) => Promise<NextResponse>) {
return async (req: NextRequest) => {
const response = await handler(req)
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
response.headers.set('Access-Control-Expose-Headers', 'Content-Range, X-Content-Range')
return response
}
}