UNPKG

qapinterface

Version:

Comprehensive API utilities for Node.js applications including authentication, security, request processing, and response handling with zero external dependencies

57 lines (50 loc) 1.5 kB
/** * API Key Extraction * Single Responsibility: Extract API keys from requests ONLY */ /** * Extracts API key from request headers, query parameters, or body. * @param {object} req - Express request object. * @param {object} [options={}] - Extraction options. * @returns {string|null} - Extracted API key or null. */ function extractApiKey(req, options = {}) { const { headerNames = ['x-api-key', 'api-key'], queryParam = 'api_key', authorizationPrefix = 'Bearer ', checkBody = false } = options; // Check Authorization header for Bearer token if (req.headers.authorization) { const authHeader = req.headers.authorization; if (authHeader.startsWith(authorizationPrefix)) { return authHeader.slice(authorizationPrefix.length); } } // Check custom API key headers for (const headerName of headerNames) { const headerValue = req.headers[headerName.toLowerCase()]; if (headerValue && typeof headerValue === 'string') { return headerValue.trim(); } } // Check query parameters if (req.query && req.query[queryParam]) { const queryValue = req.query[queryParam]; if (typeof queryValue === 'string') { return queryValue.trim(); } } // Check request body if enabled if (checkBody && req.body && req.body[queryParam]) { const bodyValue = req.body[queryParam]; if (typeof bodyValue === 'string') { return bodyValue.trim(); } } return null; } module.exports = { extractApiKey };