129 lines
3.8 KiB
Go
129 lines
3.8 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
configs "goGin/config"
|
|
database "goGin/app/database/config"
|
|
"goGin/app/database/models"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/redis/go-redis/v9"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type rateLimitRuntime struct {
|
|
Name string `json:"name"`
|
|
MaxRequests int64 `json:"max_requests"`
|
|
WindowSeconds int `json:"window_seconds"`
|
|
IsActive bool `json:"is_active"`
|
|
}
|
|
|
|
// RequireRateLimit applies Redis-backed per-IP rate limiting by setting name.
|
|
func RequireRateLimit(name string, fallbackMax int64, fallbackWindowSeconds int) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if database.DB == nil {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
setting, err := loadRateLimitRuntime(name, fallbackMax, fallbackWindowSeconds)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "rate limit configuration error"})
|
|
return
|
|
}
|
|
if !setting.IsActive {
|
|
c.Next()
|
|
return
|
|
}
|
|
if database.RedisClient == nil {
|
|
rateLimitLogf("[rate-limit][warn] redis unavailable, skipping enforcement name=%s", setting.Name)
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
ip := strings.TrimSpace(c.ClientIP())
|
|
if ip == "" {
|
|
ip = "unknown"
|
|
}
|
|
|
|
counterKey := fmt.Sprintf("ratelimit:%s:%s", setting.Name, ip)
|
|
count, err := database.RedisClient.Incr(context.Background(), counterKey).Result()
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "rate limit check failed"})
|
|
return
|
|
}
|
|
if count == 1 {
|
|
_ = database.RedisClient.Expire(context.Background(), counterKey, time.Duration(setting.WindowSeconds)*time.Second).Err()
|
|
}
|
|
|
|
if count > setting.MaxRequests {
|
|
ttl, _ := database.RedisClient.TTL(context.Background(), counterKey).Result()
|
|
retryAfter := int(ttl.Seconds())
|
|
if retryAfter < 1 {
|
|
retryAfter = setting.WindowSeconds
|
|
}
|
|
c.Header("Retry-After", strconv.Itoa(retryAfter))
|
|
log.Printf("[rate-limit][blocked] name=%s ip=%s count=%d max=%d window=%ds", setting.Name, ip, count, setting.MaxRequests, setting.WindowSeconds)
|
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
|
"error": "too many requests",
|
|
"retry_after": retryAfter,
|
|
})
|
|
return
|
|
}
|
|
|
|
rateLimitLogf("[rate-limit][allow] name=%s ip=%s count=%d max=%d window=%ds", setting.Name, ip, count, setting.MaxRequests, setting.WindowSeconds)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func loadRateLimitRuntime(name string, fallbackMax int64, fallbackWindowSeconds int) (*rateLimitRuntime, error) {
|
|
cacheKey := "ratelimit:setting:" + name
|
|
if cached, err := database.Get(cacheKey); err == nil {
|
|
var s rateLimitRuntime
|
|
if jsonErr := json.Unmarshal([]byte(cached), &s); jsonErr == nil {
|
|
return &s, nil
|
|
}
|
|
} else if !errors.Is(err, redis.Nil) {
|
|
return nil, err
|
|
}
|
|
|
|
setting := &rateLimitRuntime{
|
|
Name: name,
|
|
MaxRequests: fallbackMax,
|
|
WindowSeconds: fallbackWindowSeconds,
|
|
IsActive: true,
|
|
}
|
|
|
|
var dbSetting models.RateLimitSetting
|
|
if err := database.DB.Where("name = ?", name).First(&dbSetting).Error; err != nil {
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, err
|
|
}
|
|
rateLimitLogf("[rate-limit][config] setting=%s not found, using fallback max=%d window=%ds", name, fallbackMax, fallbackWindowSeconds)
|
|
} else {
|
|
setting.MaxRequests = dbSetting.MaxRequests
|
|
setting.WindowSeconds = dbSetting.WindowSeconds
|
|
setting.IsActive = dbSetting.IsActive
|
|
rateLimitLogf("[rate-limit][config] loaded from db name=%s active=%t max=%d window=%ds", name, setting.IsActive, setting.MaxRequests, setting.WindowSeconds)
|
|
}
|
|
|
|
cacheJSON, _ := json.Marshal(setting)
|
|
_ = database.SetEx(cacheKey, string(cacheJSON), 60)
|
|
|
|
return setting, nil
|
|
}
|
|
|
|
func rateLimitLogf(format string, args ...interface{}) {
|
|
if configs.AppConfig != nil && (configs.AppConfig.Debug || configs.AppConfig.CorsDebug) {
|
|
log.Printf(format, args...)
|
|
}
|
|
}
|