All files / postcardotp-backend/src/middleware apiKeyMiddleware.js

29.41% Statements 5/17
0% Branches 0/4
0% Functions 0/1
29.41% Lines 5/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32    1x 1x 1x   1x                                               1x  
// middleware/apiKeyMiddleware.js
 
const apiKeyService = require("../services/apiKeyService");
const logger = require("../utils/logger");
const { ApiError } = require("../utils/errorHandler");
 
const apiKeyMiddleware = async (req, res, next) => {
  try {
    const token = req.headers["x-api-key"];
 
    if (!token) {
      throw new ApiError("API Key is required", 401);
    }
 
    const apiKey = await apiKeyService.validateApiKey(token);
 
    if (!apiKey) {
      throw new ApiError("Invalid or revoked API Key", 403);
    }
 
    req.apiKey = apiKey; // Pass key info downstream
    await apiKeyService.logApiKeyUsage(apiKey.id, req.originalUrl, req.ip);
 
    next();
  } catch (error) {
    logger.error("API Key Auth Error:", error);
    next(error);
  }
};
 
module.exports = apiKeyMiddleware;