import type { Request, Response, NextFunction } from 'express';
import { config } from '../config.js';
import { logger } from '../utils/logger.js';
export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
// Skip auth for health, metrics, and dashboard API endpoints
if (req.path === '/health' || req.path === '/metrics' || req.path.startsWith('/api/')) {
next();
return;
}
const token = config.auth.token;
if (!token) {
next();
return;
}
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
logger.warn({ ip: req.ip, path: req.path }, 'Missing or invalid Authorization header');
res.status(401).json({ error: 'Unauthorized: Bearer token required' });
return;
}
const provided = authHeader.slice(7);
if (provided !== token) {
logger.warn({ ip: req.ip, path: req.path }, 'Invalid auth token');
res.status(401).json({ error: 'Unauthorized: Invalid token' });
return;
}
next();
}