package middleware import ( "context" "log/slog" "net/http" "strconv" "strings" "time" "github.com/jackc/pgx/v5/pgxpool" "github.com/yourorg/article-platform/internal/platform/auth" "github.com/yourorg/article-platform/internal/platform/cache" "github.com/yourorg/article-platform/internal/platform/httpx" "github.com/yourorg/article-platform/internal/platform/rbac" "github.com/yourorg/article-platform/internal/repo" ) type ctxKey string const ( ctxUserID ctxKey = "uid" ctxRole ctxKey = "role" ) // Auth 解析 Bearer token,把用户身份放进 context。 // 会话校验优先走 Valkey,未命中则视为游客(不做二次回源, // 因为会话本来就是粗粒度缓存,回源只会放大数据库压力)。 // AuthStats 认证层的指标钩子。用接口避免中间件反向依赖 metrics 包。 type AuthStats interface { AuthFailed(reason string) } type Auth struct { Cache *cache.Cache Users *repo.UserRepo Pool *pgxpool.Pool Log *slog.Logger Metrics AuthStats } func (a *Auth) failed(reason string) { if a.Metrics != nil { a.Metrics.AuthFailed(reason) } } func (a *Auth) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := bearer(r) if token == "" { next.ServeHTTP(w, asGuest(r)) return } th := auth.TokenHash(token) uid, ok := a.Cache.GetSession(r.Context(), th) if !ok { a.failed("session_expired") next.ServeHTTP(w, asGuest(r)) return } // 每次查库校验 status:封禁立即生效,旧 token 不能继续用。 // 这条查询走主键索引,是毫秒级的,不能省——否则「封禁无效」会成为安全漏洞。 u, err := a.Users.GetByID(r.Context(), a.Pool, uid) if err != nil { a.failed("user_not_found") a.Cache.DelSession(r.Context(), th) next.ServeHTTP(w, asGuest(r)) return } if u.Status != "active" { a.failed("user_banned") a.Cache.DelSession(r.Context(), th) next.ServeHTTP(w, asGuest(r)) return } ctx := context.WithValue(r.Context(), ctxUserID, u.ID) ctx = context.WithValue(ctx, ctxRole, rbac.Role(u.Role)) next.ServeHTTP(w, r.WithContext(ctx)) }) } func asGuest(r *http.Request) *http.Request { ctx := context.WithValue(r.Context(), ctxUserID, "") ctx = context.WithValue(ctx, ctxRole, rbac.RoleGuest) return r.WithContext(ctx) } func bearer(r *http.Request) string { h := r.Header.Get("Authorization") if strings.HasPrefix(h, "Bearer ") { return strings.TrimSpace(h[7:]) } return "" } func UserID(ctx context.Context) string { v, _ := ctx.Value(ctxUserID).(string) return v } func Role(ctx context.Context) rbac.Role { v, _ := ctx.Value(ctxRole).(rbac.Role) if v == "" { return rbac.RoleGuest } return v } // RequireAuth 要求已登录 func RequireAuth(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if UserID(r.Context()) == "" { httpx.WriteError(w, httpx.ErrUnauthorized) return } next(w, r) } } // Guard 要求具备某权限点。双参数形式,注册路由时直接内联: // // r.Post("/", middleware.Perm("article:create", d.createArticle)) func Perm(perm string, next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if UserID(r.Context()) == "" { httpx.WriteError(w, httpx.ErrUnauthorized) return } if !rbac.Has(Role(r.Context()), perm) { httpx.WriteError(w, httpx.ErrForbidden) return } next(w, r) } } // MinRole 要求达到某角色层级 func MinRole(min rbac.Role, next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if UserID(r.Context()) == "" { httpx.WriteError(w, httpx.ErrUnauthorized) return } if !Role(r.Context()).AtLeast(min) { httpx.WriteError(w, httpx.ErrForbidden) return } next(w, r) } } // ── 限流 ── // RateLimiter 固定窗口计数器。只对写操作生效: // 读请求由 CDN 和缓存层挡住,在应用层限流只会增加无谓的 Valkey 往返。 type RateLimiter struct { cache *cache.Cache anonN int userN int Metrics interface{ RateLimited() } } func NewRateLimiter(c *cache.Cache, anonN, userN int) *RateLimiter { return &RateLimiter{cache: c, anonN: anonN, userN: userN} } func (l *RateLimiter) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet, http.MethodHead, http.MethodOptions: next.ServeHTTP(w, r) return } key := UserID(r.Context()) limit := l.userN if key == "" { key = clientIP(r) limit = l.anonN } n, err := l.cache.IncrWindow(r.Context(), "rl:"+key, 60*time.Second) if err != nil { // 限流器故障时放行:宁可漏挡,不能因基础设施抖动把业务打挂 next.ServeHTTP(w, r) return } remaining := limit - int(n) if remaining < 0 { remaining = 0 } w.Header().Set("X-RateLimit-Limit", strconv.Itoa(limit)) w.Header().Set("X-RateLimit-Remaining", strconv.Itoa(remaining)) if int(n) > limit { if l.Metrics != nil { l.Metrics.RateLimited() } w.Header().Set("Retry-After", "60") httpx.WriteError(w, httpx.NewError(http.StatusTooManyRequests, httpx.CodeRateLimited, "请求过于频繁,请稍后再试")) return } next.ServeHTTP(w, r) }) } func clientIP(r *http.Request) string { if xff := r.Header.Get("X-Forwarded-For"); xff != "" { if i := strings.IndexByte(xff, ','); i > 0 { return strings.TrimSpace(xff[:i]) } return strings.TrimSpace(xff) } if xr := r.Header.Get("X-Real-IP"); xr != "" { return xr } if i := strings.LastIndexByte(r.RemoteAddr, ':'); i > 0 { return r.RemoteAddr[:i] } return r.RemoteAddr }