home.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. const jsonwebtoken = require('jsonwebtoken');
  4. const { createProxyMiddleware, responseInterceptor } = require('http-proxy-middleware');
  5. class HomeController extends Controller {
  6. async index() {
  7. const { modules } = this.app.config;
  8. // 路径参数
  9. const { agent, service, module, method, item } = this.ctx.params;
  10. // 请求地址
  11. const address = modules[service];
  12. // 请求方法
  13. const requestMethod = this.ctx.request.method;
  14. // 请求路径
  15. const path = this.ctx.path;
  16. const exampleProxy = createProxyMiddleware(
  17. `/${agent}/${service}/`,
  18. {
  19. target: `${address}${path}`,
  20. changeOrigin: true,
  21. selfHandleResponse: true,
  22. onProxyRes: responseInterceptor(async (buffer, proxyRes, req, res) => {
  23. console.log(buffer, 'buffer');
  24. console.log(proxyRes, 'proxyRes');
  25. console.log(req, 'req');
  26. console.log(res, 'res');
  27. }),
  28. });
  29. this.app.use(exampleProxy);
  30. this.app.listen(3000);
  31. // // jwt 验证
  32. // const auth = await this.auth({ service, path });
  33. // // 验证失败
  34. // if (auth.errcode !== 0) {
  35. // this.ctx.status = 401;
  36. // this.ctx.body = { errcode: 401, errmsg: '身份验证失败', details: auth.details };
  37. // return false;
  38. // }
  39. this.ctx.body = 111;
  40. }
  41. // 日志记录
  42. async setLog({ agent, service, module, method, item, details, result, auth }) {
  43. // 配置
  44. const { modules, apipath } = this.app.config;
  45. // 请求路径
  46. const path = this.ctx.path;
  47. // 根据service类型 获取配置文件
  48. const logmodules = apipath[service];
  49. // 没有配置文件默认放过
  50. if (logmodules) {
  51. // const items = logmodules.find(e => e.url.includes(path));
  52. const items = await this.rewrite_path(logmodules, path);
  53. if (items && items.log) {
  54. // 此处开始记录日志
  55. let userName = null;
  56. let name = null;
  57. if (auth.decode) {
  58. userName = auth.decode.userName;
  59. name = auth.decode.name;
  60. }
  61. try {
  62. await this.ctx.curl(`${modules.log}/api/log/log/create`, {
  63. method: 'POST',
  64. dataType: 'json',
  65. data: { agent, service, module, method, item, details, result, userName, name },
  66. });
  67. } catch (error) {
  68. this.ctx.logger.error(`日志添加失败: ${error}`);
  69. }
  70. }
  71. }
  72. }
  73. // 验证函数
  74. async auth({ service, path }) {
  75. const { jwt, apipath } = this.app.config;
  76. // 根据service类型 获取配置文件
  77. const modules = apipath[service];
  78. // 没有配置文件默认放过
  79. if (!modules) return { errcode: 0, details: '' };
  80. // 获取与当前路径匹配的项
  81. // const item = modules.filter(e => e.url.includes(path));
  82. const item = await this.rewrite_path(modules, path);
  83. // 没有匹配数据 默认放过
  84. if (item) return { errcode: 0, details: '' };
  85. // 不验证jwt放过
  86. if (!item.jwt) return { errcode: 0, details: '' };
  87. // 获取token
  88. const token = this.ctx.header.authorization.split('Bearer ')[1];
  89. try {
  90. // 解密jwt
  91. const decode = jsonwebtoken.verify(token, jwt.secret);
  92. // 如果有验证签发者
  93. if (item && item.issuer) {
  94. // 比对签发者
  95. if (!item.issuer.includes(decode.iss)) return { errcode: -4001, details: 'issuer fail verification' };
  96. }
  97. return { errcode: 0, details: '', decode };
  98. } catch (error) {
  99. return { errcode: -4001, details: error.message };
  100. }
  101. }
  102. // 重写路径
  103. async rewrite_path(modules, path) {
  104. return modules.find(e => {
  105. const { url } = e;
  106. let data = null;
  107. const urlList = url.split('/');
  108. const pathIist = path.split('/');
  109. const urlItem = urlList.findIndex(j => j.includes(':'));
  110. if (urlItem > 0) data = pathIist[urlItem];
  111. if (data !== null) urlList[urlItem] = data;
  112. const pathItem = urlList.join('/');
  113. if (pathItem === path) return e;
  114. return false;
  115. });
  116. }
  117. }
  118. module.exports = HomeController;