import type { Request, Response, NextFunction } from 'express'; import { config } from '../config'; import { logger } from '../utils/logger'; import type { ErrorResponse } from '../types/api-types'; export const authMiddleware = (req: Request, res: Response, _next: NextFunction): void => { const apiKey = req.headers['x-api-key'] as string || req.headers.authorization?.replace('Bearer ', ''); if (!apiKey) { const error: ErrorResponse = { error: 'missing_api_key', message: 'API key is required', status_code: 401 }; logger.warn('Authentication failed: Missing API key', { path: req.path }); res.status(401).json(error); return; } if (!config.apiKeys.includes(apiKey)) { const error: ErrorResponse = { error: 'invalid_api_key', message: 'Invalid API key provided', status_code: 401 }; logger.warn('Authentication failed: Invalid API key', { path: req.path, apiKey: apiKey.substring(0, 8) + '...' }); res.status(401).json(error); return; } // Add API key to request for use in services (req as { apiKey?: string }).apiKey = apiKey; logger.debug('Authentication successful', { path: req.path, apiKey: apiKey.substring(0, 8) + '...' }); next(); };