api_validate.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. }
  15. // console.log('进入了basic验证');
  16. const authHeader = request.headers.authorization;
  17. if (!authHeader) {
  18. reply.header('WWW-Authenticate', 'Basic');
  19. return reply.code(401).send('Authentication required');
  20. }
  21. const base64Credentials = authHeader.split(' ')[1];
  22. const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
  23. const [username, password] = credentials.split(':');
  24. const validUsername = process.env.API_AUTH_NAME || '';
  25. const validPassword = process.env.API_AUTH_CODE || '';
  26. if (username === validUsername && password === validPassword) {
  27. done(); // 验证通过,继续处理请求
  28. } else {
  29. reply.header('WWW-Authenticate', 'Basic');
  30. return reply.code(401).send('Invalid credentials');
  31. }
  32. };
  33. // 接口密码验证
  34. export const validatePwd = async (request, reply) => {
  35. const apiPwd = process.env.API_PWD;
  36. if (!apiPwd) {
  37. return; // 如果未配置 API_PWD,直接通过
  38. }
  39. // 从查询参数或请求体中获取 pwd
  40. const pwd = request.query.pwd || request.body?.pwd;
  41. // 如果 pwd 不存在或与 API_PWD 不匹配,返回 403
  42. if (pwd !== apiPwd) {
  43. return reply.code(403).send({error: 'Forbidden: Invalid or missing pwd'});
  44. }
  45. };