访问频率限制 优化

添加黑名单机制
This commit is contained in:
Shikong 2022-10-25 16:23:35 +08:00
parent f98e4af0a7
commit 37d46eda0e

View File

@ -6,6 +6,7 @@ import (
"gofiber.study.skcks.cn/common/config" "gofiber.study.skcks.cn/common/config"
"gofiber.study.skcks.cn/common/logger" "gofiber.study.skcks.cn/common/logger"
"gofiber.study.skcks.cn/global" "gofiber.study.skcks.cn/global"
"gofiber.study.skcks.cn/model/generic/models"
"time" "time"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -43,6 +44,19 @@ func InitService() {
func (w *Waf) Access(ip string) bool { func (w *Waf) Access(ip string) bool {
key := StoreName + Separator + "access" + Separator + ip key := StoreName + Separator + "access" + Separator + ip
wafModel := &models.Waf{Ip: ip}
ban, err := w.db.Get(wafModel)
if err != nil {
logger.Log.Errorf("[waf] access 出错 %s", err)
return false
}
if ban {
logger.Log.Infof("[waf] 阻止黑名单 ip:%s 访问", ip)
return false
}
ctx := context.Background() ctx := context.Background()
num, err := w.store.LLen(ctx, key).Result() num, err := w.store.LLen(ctx, key).Result()
if err != nil { if err != nil {
@ -52,15 +66,17 @@ func (w *Waf) Access(ip string) bool {
if num < w.config.RateLimit { if num < w.config.RateLimit {
w.store.LPush(ctx, key, time.Now().Unix()) w.store.LPush(ctx, key, time.Now().Unix())
w.store.Expire(ctx, key, 300*time.Second)
return true return true
} else { } else {
last, _ := w.store.LIndex(ctx, key, -1).Int64() last, _ := w.store.LIndex(ctx, key, -1).Int64()
if time.Now().Unix()-last < 60 { if time.Now().Unix()-last < 60 {
logger.Log.Infof("[waf] ip:%s 访问频率超过限制 %d", ip, w.config.RateLimit) logger.Log.Warnf("[waf] ip:%s 访问频率超过限制 %d", ip, w.config.RateLimit)
return false return false
} else { } else {
w.store.LPush(ctx, key, time.Now().Unix()) w.store.LPush(ctx, key, time.Now().Unix())
w.store.LTrim(ctx, key, 0, w.config.RateLimit-1) w.store.LTrim(ctx, key, 0, w.config.RateLimit-1)
w.store.Expire(ctx, key, 300*time.Second)
return true return true
} }
} }