| const ApiKey = require('../models/ApiKey'); | |
| const User = require('../models/User'); | |
| const apiKeyAuth = async (req, res, next) => { | |
| let key; | |
| // Check for API key in headers | |
| if (req.headers['x-api-key']) { | |
| key = req.headers['x-api-key']; | |
| } else if (req.headers.authorization && req.headers.authorization.startsWith('Bearer sk-cdx-')) { | |
| key = req.headers.authorization.split(' ')[1]; | |
| } | |
| if (!key) { | |
| return next(); // Proceed to next middleware (maybe regular JWT auth) | |
| } | |
| try { | |
| const apiKeyDoc = await ApiKey.findOne({ key, isActive: true }); | |
| if (!apiKeyDoc) { | |
| return res.status(401).json({ success: false, error: 'Invalid or inactive API key' }); | |
| } | |
| // Attach user to request | |
| const user = await User.findById(apiKeyDoc.userId); | |
| if (!user) { | |
| return res.status(401).json({ success: false, error: 'User associated with this key not found' }); | |
| } | |
| req.user = user; | |
| req.isApiKey = true; | |
| // Update last used | |
| apiKeyDoc.lastUsed = Date.now(); | |
| await apiKeyDoc.save(); | |
| next(); | |
| } catch (err) { | |
| console.error('API Key Auth Error:', err); | |
| res.status(500).json({ success: false, error: 'Server Error' }); | |
| } | |
| }; | |
| module.exports = apiKeyAuth; | |