12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose-free/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const _ = require('lodash');
- const assert = require('assert');
- //
- class RkService extends CrudService {
- constructor(ctx) {
- super(ctx, 'rk');
- this.redis = this.app.redis;
- this.keyPrefix = 'requestKey:';
- }
- // 检测,使用key
- async urk() {
- // 针对项目检测.如果检测到project字段,且字段在设置中,则放行
- const project = _.get(this.ctx, 'request.header.project');
- if (project) {
- const projects = this.app.config.projects;
- if (projects.includes(project)) return;
- }
- const key = _.get(this.ctx, 'request.header.rk');
- const keyName = this.getKeyName(key);
- const value = await this.redis.get(keyName);
- if (!value) throw new BusinessError(ErrorCode.SERVICE_FAULT, '未找到请求key');
- await this.redis.del(keyName);
- const keyInfo = JSON.parse(value);
- const obj = this.getKeyInfo();
- if (!_.isEqual(keyInfo, obj)) throw new BusinessError(ErrorCode.DATA_INVALID, 'key校验错误,拒绝请求', { keyInfo, obj });
- }
- // 生成key
- async crk() {
- const obj = this.getKeyInfo();
- const str = JSON.stringify(obj);
- const key = Math.random().toString(36).substr(2, 15);
- await this.redis.set(this.getKeyName(key), str, 'EX', 180);
- return key;
- }
- getKeyInfo() {
- const request = this.ctx.request;
- const ip = _.get(request, 'header.x-real-ip');
- const forward = _.get(request, 'header.x-forwarded-for');
- const host = _.get(request, 'header.host');
- const referer = _.get(request, 'header.referer');
- const query = this.ctx.query;
- const userAgent = _.get(request, 'header.user-agent');
- const views = _.get(request, 'header.views');
- const obj = {};
- if (!ip) throw new BusinessError(ErrorCode.DATA_INVALID, '1-缺少生成key的参数');
- if (!referer) throw new BusinessError(ErrorCode.DATA_INVALID, '2-缺少生成key的参数');
- if (forward) obj.forward = forward;
- if (host) obj.host = host;
- if (query) obj.query = query;
- if (userAgent) obj.userAgent = userAgent;
- if (views) obj.views = views;
- obj.ip = ip;
- obj.referer = referer;
- return obj;
- }
- getKeyName(key) {
- return `${this.keyPrefix}${key}`;
- }
- }
- module.exports = RkService;
|