|
|
@@ -0,0 +1,25 @@
|
|
|
+import { ExtendableContext, Next } from 'koa'
|
|
|
+import redis from '@/app/database/redis'
|
|
|
+import config from 'config'
|
|
|
+// 业务需求,登陆之后根据id判断 超级管理员和开发可以登陆,其他不可以
|
|
|
+// ip 白名单中间件
|
|
|
+const redisKey = config.get<string>('app.cache.prefix')
|
|
|
+const ipWhitesKey = `${redisKey}:IP_WHITE_LIST:ALLOW_IP`
|
|
|
+
|
|
|
+const defaultIpWhiteList = config.get<string[]>('app.ip_white_list')
|
|
|
+
|
|
|
+export class IpFilter {
|
|
|
+ static async handle (ctx: ExtendableContext, next: Next): Promise<unknown> {
|
|
|
+ const ip = ctx.header.ip
|
|
|
+ if (Array.isArray(ip)) {
|
|
|
+ ctx.body = { code: 403, msg: 'ip 地址有误' }
|
|
|
+ return
|
|
|
+ }
|
|
|
+ await redis.sadd(ipWhitesKey, ip)
|
|
|
+ const allowedIp = await redis.smembers(ipWhitesKey) || defaultIpWhiteList
|
|
|
+ if (ip && allowedIp.includes(ip)) {
|
|
|
+ return next()
|
|
|
+ }
|
|
|
+ ctx.body = { code: 403, msg: `未授权的ip:${ctx.header.ip},请联系管理员` }
|
|
|
+ }
|
|
|
+}
|