This repository has been archived on 2026-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MetaLab/internal/middleware/ratelimit.go
Victor_Jay 7fdea90ded feat: 敏感操作增加IP维度限流
- RateLimiter 新增 AllowSensitive 方法(1分钟5次,超限封禁5分钟)
- 新增 SensitiveRateLimit Gin 中间件
- 改密(PUT /api/settings/password)增加限流保护
- 注销(POST /api/settings/delete-account)增加限流保护
- 签到(POST /api/level/checkin)增加限流保护
2026-06-02 19:03:04 +08:00

40 lines
1.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import "sync"
// RateLimiter 双维度滑动窗口登录限流
// 维度一(账户):同邮箱 1 分钟内失败 3 次 → 锁定 1 分钟
// 维度二IP同 IP 1 分钟内失败 10 次 → 锁定 1 分钟
type RateLimiter struct {
mu sync.RWMutex
accountFailures map[string]*windowState
ipFailures map[string]*windowState
}
// NewRateLimiter 创建限流器并启动后台清理
func NewRateLimiter() *RateLimiter {
rl := &RateLimiter{
accountFailures: make(map[string]*windowState),
ipFailures: make(map[string]*windowState),
}
go rl.cleanupLoop()
return rl
}
// AllowAccount 原子检查+递增帐户维度。未被封禁则递增失败计数并返回允许。
// 调用方在操作成功(如登录成功)时应调用 Clear 清除计数。
func (rl *RateLimiter) AllowAccount(email string) RateLimitResult {
return rl.try(rl.accountFailures, email, accountWindow, accountBlockDur, accountMaxFails, true)
}
// AllowIP 原子检查+递增 IP 维度。未被封禁则递增失败计数并返回允许。
// 调用方在操作成功时应调用 Clear 清除计数。
func (rl *RateLimiter) AllowIP(ip string) RateLimitResult {
return rl.try(rl.ipFailures, ip, ipWindow, ipBlockDur, ipMaxFails, false)
}
// AllowSensitive 敏感操作限流(改密/注销/签到),基于 IP1 分钟最多 5 次,超限封禁 5 分钟。
func (rl *RateLimiter) AllowSensitive(ip string) RateLimitResult {
return rl.try(rl.ipFailures, "sensitive:"+ip, sensitiveWindow, sensitiveBlockDur, sensitiveMaxRequests, false)
}