| |
|
|
| const manager = require('../lib/manager'); |
|
|
| const verify = async (req, res, next) => { |
| console.log('[AUTH_MIDDLEWARE] Received request. Verifying API key...'); |
| console.log(`[AUTH_MIDDLEWARE] Request Headers: ${JSON.stringify(req.headers)}`); |
|
|
| const apiKeyHeaderValue = req.headers['x-api-key']; |
|
|
| if (!apiKeyHeaderValue) { |
| console.log('[AUTH_MIDDLEWARE] Unauthorized: x-api-key header is missing.'); |
| return res.status(401).json({ |
| error: { |
| message: 'Unauthorized: x-api-key header is missing.', |
| type: 'authentication_error', |
| code: 'api_key_missing' |
| } |
| }); |
| } |
|
|
| let apiKey = apiKeyHeaderValue; |
|
|
| |
| if (apiKeyHeaderValue.toLowerCase().startsWith('bearer ')) { |
| apiKey = apiKeyHeaderValue.substring(7); |
| console.log(`[AUTH_MIDDLEWARE] "Bearer " prefix found and stripped from x-api-key. Effective API key: "${apiKey}"`); |
| } else { |
| console.log(`[AUTH_MIDDLEWARE] No "Bearer " prefix found in x-api-key. Using as is: "${apiKeyHeaderValue}"`); |
| |
| } |
|
|
| console.log(`[AUTH_MIDDLEWARE] Processed x-api-key for comparison: "${apiKey}"`); |
|
|
| const expectedToken = process.env.AUTH_TOKEN; |
|
|
| if (!expectedToken) { |
| console.error('[AUTH_MIDDLEWARE] CRITICAL: AUTH_TOKEN environment variable is not set on the server!'); |
| return res.status(500).json({ |
| error: { |
| message: 'Internal Server Error: Authentication token not configured.', |
| type: 'server_error', |
| code: 'auth_token_not_set' |
| } |
| }); |
| } |
|
|
| if (apiKey === expectedToken) { |
| console.log('[AUTH_MIDDLEWARE] API key verification successful.'); |
| try { |
| console.log('[AUTH_MIDDLEWARE] Attempting to get account...'); |
| req.account = await manager.getAccount(); |
| if (!req.account) { |
| console.warn('[AUTH_MIDDLEWARE] Account not found after successful API key verification.'); |
| return res.status(503).json({ |
| error: { |
| message: '服务暂时不可用,无法获取有效账户 (Service temporarily unavailable, cannot retrieve a valid account)', |
| type: 'service_unavailable', |
| code: 'account_unavailable' |
| } |
| }); |
| } |
| console.log(`[AUTH_MIDDLEWARE] Account retrieved successfully. User: ${JSON.stringify(req.account)}`); |
| next(); |
| } catch (error) { |
| console.error('[AUTH_MIDDLEWARE] Error while getting account:', error); |
| return res.status(503).json({ |
| error: { |
| message: '服务暂时不可用 (Service temporarily unavailable)', |
| type: 'service_unavailable', |
| code: 'internal_error_account_retrieval' |
| } |
| }); |
| } |
| } else { |
| console.warn(`[AUTH_MIDDLEWARE] Unauthorized: Invalid API key. Received for comparison: "${apiKey}", Expected token (from env, length): ${expectedToken.length}`); |
| return res.status(401).json({ |
| error: { |
| message: 'Unauthorized: Invalid API Key.', |
| type: 'authentication_error', |
| code: 'invalid_api_key' |
| } |
| }); |
| } |
| }; |
|
|
| module.exports = verify; |