176 lines
4.3 KiB
Go
176 lines
4.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
|
|
"hfb_sys/backend/internal/modules/auth"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type rateLimitKeyFunc func(c *gin.Context) string
|
|
|
|
type rateLimitBucket struct {
|
|
count int
|
|
resetAt time.Time
|
|
lastSeen time.Time
|
|
}
|
|
|
|
type rateLimiter struct {
|
|
mu sync.Mutex
|
|
limit int
|
|
window time.Duration
|
|
buckets map[string]rateLimitBucket
|
|
}
|
|
|
|
type redisRateLimiter struct {
|
|
redis *redis.Client
|
|
fallback *rateLimiter
|
|
limit int
|
|
window time.Duration
|
|
}
|
|
|
|
func RateLimitPerMinute(limit int, rdb *redis.Client) gin.HandlerFunc {
|
|
return rateLimitPerMinute(limit, rdb, ipRateLimitKey)
|
|
}
|
|
|
|
// AdminAwareRateLimitPerMinute isolates authenticated admin traffic by admin ID.
|
|
// Login and other requests without a valid admin access token fall back to IP.
|
|
func AdminAwareRateLimitPerMinute(limit int, rdb *redis.Client, jwtManager *auth.JWTManager) gin.HandlerFunc {
|
|
return rateLimitPerMinute(limit, rdb, adminOrIPRateLimitKey(jwtManager))
|
|
}
|
|
|
|
func rateLimitPerMinute(limit int, rdb *redis.Client, keyFunc rateLimitKeyFunc) gin.HandlerFunc {
|
|
if limit <= 0 {
|
|
return func(c *gin.Context) {
|
|
c.Next()
|
|
}
|
|
}
|
|
limiter := &rateLimiter{
|
|
limit: limit,
|
|
window: time.Minute,
|
|
buckets: make(map[string]rateLimitBucket),
|
|
}
|
|
if rdb != nil {
|
|
return (&redisRateLimiter{
|
|
redis: rdb,
|
|
fallback: limiter,
|
|
limit: limit,
|
|
window: time.Minute,
|
|
}).handle(keyFunc)
|
|
}
|
|
return limiter.handle(keyFunc)
|
|
}
|
|
|
|
func (l *redisRateLimiter) handle(keyFunc rateLimitKeyFunc) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
now := time.Now()
|
|
key := keyFunc(c)
|
|
allowed, resetAt, err := l.allow(c.Request.Context(), key, now)
|
|
if err != nil {
|
|
allowed, resetAt = l.fallback.allow(key, now)
|
|
}
|
|
if !allowed {
|
|
writeRateLimited(c, now, resetAt)
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func (l *rateLimiter) handle(keyFunc rateLimitKeyFunc) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
now := time.Now()
|
|
key := keyFunc(c)
|
|
allowed, resetAt := l.allow(key, now)
|
|
if !allowed {
|
|
writeRateLimited(c, now, resetAt)
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func ipRateLimitKey(c *gin.Context) string {
|
|
return "ip:" + c.ClientIP()
|
|
}
|
|
|
|
func adminOrIPRateLimitKey(jwtManager *auth.JWTManager) rateLimitKeyFunc {
|
|
return func(c *gin.Context) string {
|
|
if value, ok := c.Get(ContextAdminID); ok {
|
|
if adminID, ok := value.(uint64); ok && adminID != 0 {
|
|
return "admin:" + strconv.FormatUint(adminID, 10)
|
|
}
|
|
}
|
|
if jwtManager != nil {
|
|
tokenText, _ := extractAdminToken(c)
|
|
if tokenText != "" {
|
|
claims, err := jwtManager.ParseSubject(tokenText, "access", "admin")
|
|
if err == nil && claims.UserID != 0 {
|
|
return "admin:" + strconv.FormatUint(claims.UserID, 10)
|
|
}
|
|
}
|
|
}
|
|
return ipRateLimitKey(c)
|
|
}
|
|
}
|
|
|
|
func (l *redisRateLimiter) allow(ctx context.Context, key string, now time.Time) (bool, time.Time, error) {
|
|
windowSeconds := int64(l.window / time.Second)
|
|
windowID := now.Unix() / windowSeconds
|
|
redisKey := "rate_limit:" + key + ":" + strconv.FormatInt(windowID, 10)
|
|
count, err := l.redis.Incr(ctx, redisKey).Result()
|
|
if err != nil {
|
|
return false, time.Time{}, err
|
|
}
|
|
if count == 1 {
|
|
_ = l.redis.Expire(ctx, redisKey, 2*l.window).Err()
|
|
}
|
|
resetAt := time.Unix((windowID+1)*windowSeconds, 0)
|
|
return count <= int64(l.limit), resetAt, nil
|
|
}
|
|
|
|
func (l *rateLimiter) allow(key string, now time.Time) (bool, time.Time) {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
|
|
l.cleanup(now)
|
|
bucket := l.buckets[key]
|
|
if bucket.resetAt.IsZero() || !now.Before(bucket.resetAt) {
|
|
bucket = rateLimitBucket{resetAt: now.Add(l.window)}
|
|
}
|
|
bucket.count++
|
|
bucket.lastSeen = now
|
|
l.buckets[key] = bucket
|
|
return bucket.count <= l.limit, bucket.resetAt
|
|
}
|
|
|
|
func (l *rateLimiter) cleanup(now time.Time) {
|
|
for key, bucket := range l.buckets {
|
|
if now.Sub(bucket.lastSeen) > 2*l.window {
|
|
delete(l.buckets, key)
|
|
}
|
|
}
|
|
}
|
|
|
|
func retryAfterSeconds(now time.Time, resetAt time.Time) string {
|
|
seconds := int(resetAt.Sub(now).Seconds())
|
|
if seconds < 1 {
|
|
seconds = 1
|
|
}
|
|
return strconv.Itoa(seconds)
|
|
}
|
|
|
|
func writeRateLimited(c *gin.Context, now time.Time, resetAt time.Time) {
|
|
c.Header("Retry-After", retryAfterSeconds(now, resetAt))
|
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
|
"code": "rate_limited",
|
|
"message": "请求过于频繁,请稍后再试",
|
|
})
|
|
}
|