home.js 5.5 KB

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