import { Request, Response, NextFunction } from "express"; /** * API Key authentication middleware */ export const apiKeyAuth = (req: Request, res: Response, next: NextFunction) => { const apiKey = req.headers["x-api-key"] || req.headers["authorization"]?.replace("Bearer ", ""); if (!apiKey) { return res.status(401).json({ error: "Unauthorized", message: "API key is required", }); } // Validate API key (in production, check against database) const validApiKeys = process.env.API_KEYS?.split(",") || []; if (!validApiKeys.includes(apiKey as string)) { return res.status(403).json({ error: "Forbidden", message: "Invalid API key", }); } // Attach API key info to request (req as any).apiKey = apiKey; next(); }; /** * Optional API key authentication (for public endpoints) */ export const optionalApiKeyAuth = (req: Request, res: Response, next: NextFunction) => { const apiKey = req.headers["x-api-key"] || req.headers["authorization"]?.replace("Bearer ", ""); if (apiKey) { const validApiKeys = process.env.API_KEYS?.split(",") || []; if (validApiKeys.includes(apiKey as string)) { (req as any).apiKey = apiKey; (req as any).authenticated = true; } } next(); };