Spaces:
Paused
Paused
Create verify.js
Browse files
verify.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const manager = require('../lib/manager'); // 假设路径相对于此文件是正确的
|
| 2 |
+
|
| 3 |
+
const verify = async (req, res, next) => {
|
| 4 |
+
// 1. 从 x-api-key 请求头获取值
|
| 5 |
+
const apiKeyHeader = req.headers['x-api-key'];
|
| 6 |
+
|
| 7 |
+
// 2. 检查请求头是否存在
|
| 8 |
+
if (!apiKeyHeader) {
|
| 9 |
+
return res.status(401).json({ message: 'Unauthorized' }); // 保持原始错误消息
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
// 3. 准备用于比较的 token,如果存在 "Bearer " 前缀(不区分大小写),则移除
|
| 13 |
+
let tokenToCompare = apiKeyHeader;
|
| 14 |
+
if (apiKeyHeader.toLowerCase().startsWith('bearer ')) {
|
| 15 |
+
tokenToCompare = apiKeyHeader.substring(7); // "Bearer " 长度为 7
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// 4. 与环境变量中的 AUTH_TOKEN 进行比较
|
| 19 |
+
if (tokenToCompare === process.env.AUTH_TOKEN) {
|
| 20 |
+
try {
|
| 21 |
+
req.account = await manager.getAccount();
|
| 22 |
+
if (!req.account) {
|
| 23 |
+
// 保持原始错误结构
|
| 24 |
+
return res.status(503).json({
|
| 25 |
+
error: {
|
| 26 |
+
message: '服务暂时不可用,无法获取有效账户',
|
| 27 |
+
type: 'service_unavailable',
|
| 28 |
+
code: 'account_unavailable'
|
| 29 |
+
}
|
| 30 |
+
});
|
| 31 |
+
}
|
| 32 |
+
next();
|
| 33 |
+
} catch (error) {
|
| 34 |
+
console.error('获取账户时出错:', error); // 保持原始的 console.error
|
| 35 |
+
// 保持原始错误结构
|
| 36 |
+
return res.status(503).json({
|
| 37 |
+
error: {
|
| 38 |
+
message: '服务暂时不可用',
|
| 39 |
+
type: 'service_unavailable',
|
| 40 |
+
code: 'internal_error'
|
| 41 |
+
}
|
| 42 |
+
});
|
| 43 |
+
}
|
| 44 |
+
} else {
|
| 45 |
+
return res.status(401).json({ message: 'Unauthorized' }); // 保持原始错误消息
|
| 46 |
+
}
|
| 47 |
+
};
|
| 48 |
+
|
| 49 |
+
module.exports = verify;
|