home.js 5.4 KB

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