39 lines
986 B
Go
39 lines
986 B
Go
package middleware
|
|
|
|
import (
|
|
"strings"
|
|
"time"
|
|
|
|
"kra/internal/server/httpx"
|
|
"kra/internal/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func SecurityRateLimit(settings *service.SecurityService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
path := strings.TrimSuffix(c.Request.URL.Path, "/")
|
|
if !strings.HasSuffix(path, "/base/login") && !strings.HasSuffix(path, "/base/captcha") {
|
|
c.Next()
|
|
return
|
|
}
|
|
config, err := settings.CurrentSecurity(c.Request.Context())
|
|
if err != nil || config == nil || !config.LimitEnable {
|
|
c.Next()
|
|
return
|
|
}
|
|
window := config.LimitWindow
|
|
if window < 1 {
|
|
window = 60
|
|
}
|
|
key := "KRA_SecLimit" + c.ClientIP() + c.FullPath()
|
|
count, cacheErr := settings.IncrementRateLimit(c.Request.Context(), key, time.Duration(window)*time.Second)
|
|
if cacheErr == nil && int(count) > config.LimitCount {
|
|
c.JSON(200, gin.H{"code": httpx.CodeError, "msg": "请求太过频繁,请稍后再试"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|