deploy-hxtesting / build-and-deploy (push) Successful in 1m14s
规则:1.签到要校验是否为培训当天签到,如果不是当天扫码签到则进行友好提示;2. 签到需提供员工工号及随机时间戳(超过签到二维码有效期后需重新扫码签到);3.签到二维码每5分钟自动更新一次(更新后之前扫码签到自动作废需重新扫码); 补充说明:1.签到页面需展示该签到课程相关信息;2.展示签到倒计时还有多久过期,过期后需重新扫码进行优化提示;3.签到后提示签到成功!自动登录进入平台系统并进入该课程详情页面
157 lines
5.1 KiB
Go
157 lines
5.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
apperrors "academy/internal/errors"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// auth_public_ratelimit.go — sliding-window IP rate limiter for the
|
|
// unauthenticated share-link endpoints (/auth/invitations/lookup and
|
|
// /auth/register-by-invite). Both surfaces accept a plaintext token
|
|
// from the request and either reveal tenant context (lookup) or
|
|
// create an account (register-by-invite); without a limiter an
|
|
// attacker can brute-force token guesses and hammer registration.
|
|
//
|
|
// The token is 256-bit so guessing the space is infeasible regardless,
|
|
// but the limiter still narrows the abuse window for partial-token
|
|
// leaks (e.g. via referrer / clipboard managers / accidental commits)
|
|
// and bounds the noise this endpoint can add to the user-create path.
|
|
//
|
|
// Local in-memory only — fine for typical deployments since both
|
|
// endpoints handle low absolute volumes; if/when Academy horizontally
|
|
// scales the auth surface, swap to the Redis-backed limiter in
|
|
// internal/ratelimit (shared with IM + embed surfaces).
|
|
|
|
// publicAuthRateLimitWindow is the rolling window length per IP.
|
|
const publicAuthRateLimitWindow = 60 * time.Second
|
|
|
|
// publicAuthRateLimitMax is the request budget per IP per window for
|
|
// each endpoint instance. 30/min comfortably covers a real user
|
|
// retrying a failed registration while clamping enumeration
|
|
// throughput to ~half a request per second.
|
|
const publicAuthRateLimitMax = 30
|
|
|
|
// publicAuthRateLimitCleanupInterval bounds map growth from one-off
|
|
// IPs that never come back.
|
|
const publicAuthRateLimitCleanupInterval = 2 * time.Minute
|
|
|
|
type ipBucket struct {
|
|
mu sync.Mutex
|
|
timestamps []time.Time
|
|
}
|
|
|
|
type ipRateLimiter struct {
|
|
window time.Duration
|
|
max int
|
|
buckets sync.Map // string (IP) -> *ipBucket
|
|
}
|
|
|
|
func newIPRateLimiter(window time.Duration, max int) *ipRateLimiter {
|
|
l := &ipRateLimiter{window: window, max: max}
|
|
go l.cleanupLoop()
|
|
return l
|
|
}
|
|
|
|
// allow returns true if the IP is within budget for the current
|
|
// window. Empty IP (proxy stripped X-Forwarded-For) is treated as a
|
|
// shared bucket — slightly over-restrictive vs. dropping the limit
|
|
// entirely, which would let a misconfigured proxy bypass the gate.
|
|
func (l *ipRateLimiter) allow(ip string) bool {
|
|
if ip == "" {
|
|
ip = "_unknown_"
|
|
}
|
|
now := time.Now()
|
|
cutoff := now.Add(-l.window)
|
|
|
|
val, _ := l.buckets.LoadOrStore(ip, &ipBucket{})
|
|
b := val.(*ipBucket)
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
kept := b.timestamps[:0]
|
|
for _, t := range b.timestamps {
|
|
if t.After(cutoff) {
|
|
kept = append(kept, t)
|
|
}
|
|
}
|
|
b.timestamps = kept
|
|
if len(b.timestamps) >= l.max {
|
|
return false
|
|
}
|
|
b.timestamps = append(b.timestamps, now)
|
|
return true
|
|
}
|
|
|
|
func (l *ipRateLimiter) cleanupLoop() {
|
|
t := time.NewTicker(publicAuthRateLimitCleanupInterval)
|
|
defer t.Stop()
|
|
for range t.C {
|
|
cutoff := time.Now().Add(-l.window)
|
|
l.buckets.Range(func(k, v any) bool {
|
|
b := v.(*ipBucket)
|
|
b.mu.Lock()
|
|
drop := len(b.timestamps) == 0 ||
|
|
b.timestamps[len(b.timestamps)-1].Before(cutoff)
|
|
b.mu.Unlock()
|
|
if drop {
|
|
l.buckets.Delete(k)
|
|
}
|
|
return true
|
|
})
|
|
}
|
|
}
|
|
|
|
// publicAuthLimiter — package-singleton so each route registration
|
|
// shares a single bucket map per process. Each route still gets its
|
|
// own Gin handler that calls into this same limiter; per-route
|
|
// isolation isn't important here (real users don't hit both
|
|
// endpoints in the same window) but the shared state makes total
|
|
// budget per IP intuitive: 30/min across all share-link surfaces.
|
|
var publicAuthLimiter = newIPRateLimiter(
|
|
publicAuthRateLimitWindow, publicAuthRateLimitMax)
|
|
|
|
// PublicAuthRateLimit returns a Gin middleware that rate-limits the
|
|
// unauthenticated share-link endpoints by client IP. 429 is mapped
|
|
// through the project's AppError type so it flows through the same
|
|
// error middleware as the rest of the auth surface.
|
|
func PublicAuthRateLimit() gin.HandlerFunc {
|
|
return rateLimitWith(publicAuthLimiter)
|
|
}
|
|
|
|
// wecomCheckinRateLimitMax 培训扫码免登专用预算:教室场景几十名学员共享同一
|
|
// 办公网出口 IP,若复用 30/min 的共享 auth 限流,集中扫码会整批 429。签到
|
|
// 链路独立限流器放宽到 600/min/IP(百人级课堂在 5 分钟轮换窗口内仍宽裕),
|
|
// 同时保留对脚本刷 code/token 的约束。
|
|
const wecomCheckinRateLimitMax = 600
|
|
|
|
// wecomCheckinLimiter 独立桶,不与 share-link/auth 端点共享预算。
|
|
var wecomCheckinLimiter = newIPRateLimiter(publicAuthRateLimitWindow, wecomCheckinRateLimitMax)
|
|
|
|
// WecomCheckinRateLimit rate-limits the anonymous WeCom scan-checkin endpoints
|
|
// (checkin-auth / checkin-session) by client IP.
|
|
func WecomCheckinRateLimit() gin.HandlerFunc {
|
|
return rateLimitWith(wecomCheckinLimiter)
|
|
}
|
|
|
|
// rateLimitWith adapts an ipRateLimiter into Gin middleware; 429 flows through
|
|
// the project's AppError middleware like the rest of the auth surface.
|
|
func rateLimitWith(l *ipRateLimiter) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
ip := c.ClientIP()
|
|
if !l.allow(ip) {
|
|
c.Error(&apperrors.AppError{
|
|
Code: apperrors.ErrTooManyRequests,
|
|
Message: "too many requests; please retry shortly",
|
|
HTTPCode: http.StatusTooManyRequests,
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|