rk.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. //
  7. class RkService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'rk');
  10. this.redis = this.app.redis;
  11. this.keyPrefix = 'requestKey:';
  12. }
  13. // 检测,使用key
  14. async urk() {
  15. // 针对项目检测.如果检测到project字段,且字段在设置中,则放行
  16. const project = _.get(this.ctx, 'request.header.project');
  17. if (project) {
  18. const projects = this.app.config.projects;
  19. if (projects.includes(project)) return;
  20. }
  21. const key = _.get(this.ctx, 'request.header.rk');
  22. const keyName = this.getKeyName(key);
  23. const value = await this.redis.get(keyName);
  24. if (!value) throw new BusinessError(ErrorCode.SERVICE_FAULT, '未找到请求key');
  25. await this.redis.del(keyName);
  26. const keyInfo = JSON.parse(value);
  27. const obj = this.getKeyInfo();
  28. if (!_.isEqual(keyInfo, obj)) throw new BusinessError(ErrorCode.DATA_INVALID, 'key校验错误,拒绝请求', { keyInfo, obj });
  29. }
  30. // 生成key
  31. async crk() {
  32. const obj = this.getKeyInfo();
  33. const str = JSON.stringify(obj);
  34. const key = Math.random().toString(36).substr(2, 15);
  35. await this.redis.set(this.getKeyName(key), str, 'EX', 180);
  36. return key;
  37. }
  38. getKeyInfo() {
  39. const request = this.ctx.request;
  40. const ip = _.get(request, 'header.x-real-ip');
  41. const forward = _.get(request, 'header.x-forwarded-for');
  42. const host = _.get(request, 'header.host');
  43. const referer = _.get(request, 'header.referer');
  44. const query = this.ctx.query;
  45. const userAgent = _.get(request, 'header.user-agent');
  46. const views = _.get(request, 'header.views');
  47. const obj = {};
  48. if (!ip) throw new BusinessError(ErrorCode.DATA_INVALID, '1-缺少生成key的参数');
  49. if (!referer) throw new BusinessError(ErrorCode.DATA_INVALID, '2-缺少生成key的参数');
  50. if (forward) obj.forward = forward;
  51. if (host) obj.host = host;
  52. if (query) obj.query = query;
  53. if (userAgent) obj.userAgent = userAgent;
  54. if (views) obj.views = views;
  55. obj.ip = ip;
  56. obj.referer = referer;
  57. return obj;
  58. }
  59. getKeyName(key) {
  60. return `${this.keyPrefix}${key}`;
  61. }
  62. }
  63. module.exports = RkService;