home.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. const jsonwebtoken = require('jsonwebtoken');
  4. const FormStream = require('formstream');
  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. let msg = null;
  17. let details = null;
  18. let result = null;
  19. // jwt 验证
  20. const auth = await this.auth({ service, path });
  21. // 验证失败
  22. if (auth.errcode !== 0) {
  23. this.ctx.status = 401;
  24. this.ctx.body = { errcode: 401, errmsg: '身份验证失败', details: auth.details };
  25. return false;
  26. }
  27. // 发送的数据
  28. let data = requestMethod === 'GET' ? this.ctx.query : this.ctx.request.body;
  29. if (requestMethod === 'DELETE') data = this.ctx.params.item;
  30. // 参数定义
  31. let form = {};
  32. const options = {
  33. method: requestMethod,
  34. data,
  35. nestedQuerystring: true,
  36. };
  37. // 如果是文件上传
  38. if (method === 'upload') {
  39. const stream = await this.ctx.getFileStream();
  40. form = new FormStream();
  41. form.stream(stream.fieldname, stream, stream.filename);
  42. options.stream = form;
  43. options.headers = form.headers();
  44. }
  45. // 发送请求
  46. const res = await this.ctx.curl(`${address}${path}`, options);
  47. // 默认返回值
  48. msg = res.data;
  49. // 日志详情默认值
  50. details = data;
  51. result = '成功';
  52. // 错误异常处理(返回值)
  53. // 缺少字段检测返回asser
  54. if (res.status === 500 && res.data.name === 'AssertionError') {
  55. msg = { errcode: -1002, errmsg: res.data.message, data: '' };
  56. details = res.data.message;
  57. result = '失败';
  58. }
  59. // 异常抛出检测
  60. if (res.status === 500 && (res.data.name === 'ValidationError' || res.data.name === 'CastError')) {
  61. msg = { errcode: -1002, errmsg: '系统错误', details: res.data.message };
  62. details = res.data.message;
  63. result = '失败';
  64. }
  65. await this.setLog({ agent, service, module, method, item, details: JSON.stringify(details), result, auth });
  66. // 默认返回状态 = 当前请求返回状态
  67. this.ctx.response.type = res.headers['content-type'];
  68. this.ctx.status = res.status;
  69. this.ctx.body = msg;
  70. }
  71. // 日志记录
  72. async setLog({ agent, service, module, method, item, details, result, auth }) {
  73. // 配置
  74. const { modules, apipath } = this.app.config;
  75. // 请求路径
  76. const path = this.ctx.path;
  77. // 根据service类型 获取配置文件
  78. const logmodules = apipath[service];
  79. // 没有配置文件默认放过
  80. if (logmodules) {
  81. // const items = logmodules.find(e => e.url.includes(path));
  82. const items = await this.rewrite_path(logmodules, path);
  83. if (items && items.log) {
  84. // 此处开始记录日志
  85. let userName = null;
  86. let name = null;
  87. if (auth.decode) {
  88. userName = auth.decode.userName;
  89. name = auth.decode.name;
  90. }
  91. try {
  92. await this.ctx.curl(`${modules.log}/api/log/log/create`, {
  93. method: 'POST',
  94. dataType: 'json',
  95. data: { agent, service, module, method, item, details, result, userName, name },
  96. });
  97. } catch (error) {
  98. this.ctx.logger.error(`日志添加失败: ${error}`);
  99. }
  100. }
  101. }
  102. }
  103. // 验证函数
  104. async auth({ service, path }) {
  105. const { jwt, apipath } = this.app.config;
  106. // 根据service类型 获取配置文件
  107. const modules = apipath[service];
  108. // 没有配置文件默认放过
  109. if (!modules) return { errcode: 0, details: '' };
  110. // 获取与当前路径匹配的项
  111. // const item = modules.filter(e => e.url.includes(path));
  112. const item = await this.rewrite_path(modules, path);
  113. // 没有匹配数据 默认放过 不验证jwt放过
  114. if (!item || !item.jwt) return { errcode: 0, details: '' };
  115. // 获取token
  116. const token = this.ctx.header.authorization;
  117. try {
  118. // 解密jwt
  119. const decode = jsonwebtoken.verify(token, jwt.secret);
  120. // 如果有验证签发者
  121. if (item && item.issuer) {
  122. // 比对签发者
  123. if (!item.issuer.includes(decode.iss)) return { errcode: -4001, details: 'issuer fail verification' };
  124. }
  125. return { errcode: 0, details: '', decode: decode._doc };
  126. } catch (error) {
  127. return { errcode: -4001, details: error.message };
  128. }
  129. }
  130. // 重写路径
  131. async rewrite_path(modules, path) {
  132. return modules.find(e => {
  133. const { url } = e;
  134. let data = null;
  135. const urlList = url.split('/');
  136. const pathIist = path.split('/');
  137. const urlItem = urlList.findIndex(j => j.includes(':'));
  138. if (urlItem > 0) data = pathIist[urlItem];
  139. if (data !== null) urlList[urlItem] = data;
  140. const pathItem = urlList.join('/');
  141. if (pathItem === path) return e;
  142. return false;
  143. });
  144. }
  145. }
  146. module.exports = HomeController;