Pro2API / verify.js
krinlove's picture
Update verify.js
40b9a93 verified
raw
history blame
3.27 kB
// verify.js
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']; // Get the raw header value
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; // Initialize apiKey with the full header value
// Check if the header value starts with "Bearer " (case-insensitive) and remove it
if (apiKeyHeaderValue.toLowerCase().startsWith('bearer ')) {
apiKey = apiKeyHeaderValue.substring(7); // "Bearer " is 7 characters long
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}"`);
// apiKey remains 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;