39 lines
1007 B
Go
39 lines
1007 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"kra/internal/server/httpx"
|
|
"kra/internal/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func SecurityRateLimit(system *service.SystemService, settings *service.SettingsService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if isBootstrapPath(c.Request.URL.Path) {
|
|
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
|
|
}
|
|
bucket := time.Now().Unix() / int64(window)
|
|
key := "rate:" + c.ClientIP() + ":" + strconv.FormatInt(bucket, 10)
|
|
count, cacheErr := system.CacheIncrement(c.Request.Context(), key, time.Duration(window+1)*time.Second)
|
|
if cacheErr == nil && int(count) > config.LimitCount {
|
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, httpx.Response{Code: httpx.CodeError, Data: nil, Msg: "请求过于频繁"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|