rk.js 2.2 KB

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