12345678910111213141516171819202122232425 |
- import { Context, Next } from 'koa';
- import config from '@config';
- export default () => {
- return async (ctx: Context, next: Next): Promise<void> => {
- const host: string = ctx.host;
- const domain = host.replace(/(:[^:]+)$/, '');
- const isMatch = config.checkHost.find(el => domain.match(el));
- console.log(host, config.checkHost, isMatch);
- if (!isMatch) {
- // 域名不对
- ctx.status = 403;
- ctx.throw(403, '请求出错');
- }
- const ip: string = ctx.ip;
- const key = `client_ip_limit_${ip}`;
- const limit: number = Number(await ctx.$redis.get(key)) || 0;
- if (limit > config.limit.times) {
- ctx.status = 403;
- ctx.throw(403, '请求频次过高');
- return;
- }
- ctx.$redis.setex(key, config.limit.time, String(limit + 1));
- await next();
- };
- };
|