import 'dotenv/config';
export function authMiddleware(req, res, next) {
const AUTH_ENABLED = process.env.AUTH_ENABLED === '1';
if (!AUTH_ENABLED) {
return next(req, res);
}
const AUTH_USERNAME = process.env.AUTH_USERNAME || 'admin';
const AUTH_PASSWORD = process.env.AUTH_PASSWORD || 'password';
const authHeader = req.headers.authorization;
if (!authHeader) {
res.writeHead(401, {
'Content-Type': 'text/plain',
'WWW-Authenticate': 'Basic realm="Probe Code Search"'
});
res.end('Authentication required');
return;
}
try {
const authParts = authHeader.split(' ');
if (authParts.length !== 2 || authParts[0] !== 'Basic') {
throw new Error('Invalid Authorization header format');
}
const credentials = Buffer.from(authParts[1], 'base64').toString('utf-8');
const [username, password] = credentials.split(':');
if (username === AUTH_USERNAME && password === AUTH_PASSWORD) {
return next(req, res);
} else {
res.writeHead(401, {
'Content-Type': 'text/plain',
'WWW-Authenticate': 'Basic realm="Probe Code Search"'
});
res.end('Invalid credentials');
return;
}
} catch (error) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Invalid Authorization header');
return;
}
}
export function withAuth(handler) {
return (req, res) => {
authMiddleware(req, res, () => handler(req, res));
};
}