api_validate.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // 接口basic验证
  2. export const validateBasicAuth = (request, reply, done) => {
  3. if (!process.env.hasOwnProperty('API_AUTH_NAME') && !process.env.hasOwnProperty('API_AUTH_CODE')) {
  4. done();
  5. return
  6. }
  7. if (request.url.startsWith('/config/')) {
  8. let cf_path = request.url.slice(8).split('?')[0];
  9. // console.log(cf_path);
  10. if (!['index.js', 'index.js.md5', 'index.config.js', 'index.config.js.md5'].includes(cf_path)) {
  11. done();
  12. return
  13. }
  14. console.log(`[validateBasicAuth] 猫配置文件 ${cf_path} 进入Basic登录鉴权`);
  15. }
  16. // console.log('进入了basic验证');
  17. const authHeader = request.headers.authorization;
  18. if (!authHeader) {
  19. reply.header('WWW-Authenticate', 'Basic');
  20. return reply.code(401).send('Authentication required');
  21. }
  22. const base64Credentials = authHeader.split(' ')[1];
  23. const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
  24. const [username, password] = credentials.split(':');
  25. const validUsername = process.env.API_AUTH_NAME || '';
  26. const validPassword = process.env.API_AUTH_CODE || '';
  27. if (username === validUsername && password === validPassword) {
  28. done(); // 验证通过,继续处理请求
  29. } else {
  30. reply.header('WWW-Authenticate', 'Basic');
  31. return reply.code(401).send('Invalid credentials');
  32. }
  33. };
  34. // 接口密码验证
  35. export const validatePwd = async (request, reply) => {
  36. const apiPwd = process.env.API_PWD;
  37. if (!apiPwd) {
  38. return; // 如果未配置 API_PWD,直接通过
  39. }
  40. if (request.url.startsWith('/config/')) {
  41. let cf_path = request.url.slice(8).split('?')[0];
  42. // console.log(cf_path);
  43. if (['index.js', 'index.js.md5', 'index.config.js', 'index.config.js.md5'].includes(cf_path)) {
  44. console.log(`[validatePwd] 猫配置文件 ${cf_path} 跳过接口密码鉴权`);
  45. return
  46. }
  47. }
  48. // 从查询参数或请求体中获取 pwd
  49. const pwd = request.query.pwd || request.body?.pwd;
  50. // 如果 pwd 不存在或与 API_PWD 不匹配,返回 403
  51. if (pwd !== apiPwd) {
  52. return reply.code(403).send({error: 'Forbidden: Invalid or missing pwd'});
  53. }
  54. };