home.js 5.3 KB

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