qapinterface
Version:
Comprehensive API utilities for Node.js applications including authentication, security, request processing, and response handling with zero external dependencies
57 lines (47 loc) • 1.88 kB
JavaScript
/**
* Cookie API Key Authentication Middleware
* Single Responsibility: Authenticate API requests using cookie-based API keys ONLY
*/
const { NODE_ENV } = require('../../config/localVars');
/**
* Creates middleware for cookie-based API key authentication
* @param {object} options - Configuration options
* @param {string} [options.cookieName='apiKey'] - Name of the cookie containing the API key
* @param {string} [options.envKeyName='API_KEY'] - Environment variable name for the API key
* @param {boolean} [options.skipInDevelopment=true] - Skip authentication in development mode
* @returns {Function} Express middleware function
*/
function createCookieApiKeyMiddleware(options = {}) {
const {
cookieName = 'apiKey',
envKeyName = 'API_KEY',
skipInDevelopment = true
} = options;
return function cookieApiKeyAuth(req, res, next) {
// Skip API key authentication in development mode
if (skipInDevelopment && NODE_ENV === 'development') {
return next();
}
const API_KEY = process.env[envKeyName];
// Check if API key is configured on server
if (!API_KEY) {
console.error(`CRITICAL: No ${envKeyName} configured on the server. All API requests will be denied.`);
return res.status(500).json({ error: 'Server configuration error' });
}
// Extract API key from cookies
const providedApiKey = req.cookies?.[cookieName];
// If no API key cookie exists, deny access
if (!providedApiKey) {
return res.status(401).json({ error: 'Unauthorized: Missing API key' });
}
// Validate API key from cookie
if (providedApiKey !== API_KEY) {
return res.status(401).json({ error: 'Unauthorized: Invalid API key' });
}
// API key is valid, proceed to next middleware
next();
};
}
module.exports = {
createCookieApiKeyMiddleware
};