added basic auth

This commit is contained in:
2025-08-17 14:13:58 +01:00
parent 1bf8e1a055
commit 4cafa1fb0b
3 changed files with 68 additions and 1 deletions

55
src/middleware.ts Normal file
View File

@@ -0,0 +1,55 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Very simple single-user HTTP Basic Auth.
// Set BASIC_AUTH_USER and BASIC_AUTH_PASS in the environment to enable.
// If these are not set, auth is disabled and all requests pass through.
export function middleware(req: NextRequest) {
const user = process.env.BASIC_AUTH_USER;
const pass = process.env.BASIC_AUTH_PASS;
if (!user || !pass) {
// Auth disabled
return NextResponse.next();
}
const header = req.headers.get('authorization') || '';
const prefix = 'Basic ';
if (!header.startsWith(prefix)) {
return unauthorized('Authentication required');
}
try {
const decoded = atob(header.slice(prefix.length));
const idx = decoded.indexOf(':');
const u = decoded.slice(0, idx);
const p = decoded.slice(idx + 1);
if (u === user && p === pass) {
return NextResponse.next();
}
} catch {
// fallthrough
}
return unauthorized('Invalid credentials');
}
function unauthorized(message: string) {
return new NextResponse(message, {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Restricted", charset="UTF-8"',
'Content-Type': 'text/plain; charset=utf-8',
},
});
}
// Apply to all routes (including API). Static assets will also be behind auth; browsers will reuse credentials.
export const config = {
matcher: [
// Exclude Next static assets and image optimizer
'/((?!_next/static|_next/image).*)',
],
};