added basic auth
This commit is contained in:
55
src/middleware.ts
Normal file
55
src/middleware.ts
Normal 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).*)',
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user