rk.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. const key = _.get(this.ctx, 'request.header.rk');
  16. const keyName = this.getKeyName(key);
  17. const value = await this.redis.get(keyName);
  18. if (!value) throw new BusinessError(ErrorCode.SERVICE_FAULT, '未找到请求key');
  19. await this.redis.del(keyName);
  20. const keyInfo = JSON.parse(value);
  21. const obj = this.getKeyInfo();
  22. if (!_.isEqual(keyInfo, obj)) throw new BusinessError(ErrorCode.DATA_INVALID, 'key校验错误,拒绝请求', { keyInfo, obj });
  23. }
  24. // 生成key
  25. async crk() {
  26. const obj = this.getKeyInfo();
  27. const str = JSON.stringify(obj);
  28. const key = Math.random().toString(36).substr(2, 15);
  29. await this.redis.set(this.getKeyName(key), str, 'EX', 180);
  30. return key;
  31. }
  32. getKeyInfo() {
  33. const request = this.ctx.request;
  34. const ip = _.get(request, 'header.x-real-ip');
  35. const forward = _.get(request, 'header.x-forwarded-for');
  36. const host = _.get(request, 'header.host');
  37. const referer = _.get(request, 'header.referer');
  38. const query = this.ctx.query;
  39. const body = _.get(request, 'body');
  40. const userAgent = _.get(request, 'header.user-agent');
  41. const obj = {};
  42. const ut = _.get(request, 'header.token');
  43. const at = _.get(request, 'header.admin-token');
  44. if (!ip) throw new BusinessError(ErrorCode.DATA_INVALID, '1-缺少生成key的参数');
  45. if (!referer) throw new BusinessError(ErrorCode.DATA_INVALID, '2-缺少生成key的参数');
  46. if (forward) obj.forward = forward;
  47. if (host) obj.host = host;
  48. if (query) obj.query = query;
  49. if (body) obj.body = body;
  50. if (userAgent) obj.userAgent = userAgent;
  51. if (ut) obj.ut = ut;
  52. if (at) obj.at = at;
  53. obj.ip = ip;
  54. obj.referer = referer;
  55. return obj;
  56. }
  57. getKeyName(key) {
  58. return `${this.keyPrefix}${key}`;
  59. }
  60. }
  61. module.exports = RkService;