feat: JWT 中间件添加 Token 黑名单检查
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
a1b42b9ccd
commit
c026e3b8e7
@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/topfans/backend/gateway/pkg/response"
|
"github.com/topfans/backend/gateway/pkg/response"
|
||||||
|
"github.com/topfans/backend/pkg/database"
|
||||||
"github.com/topfans/backend/pkg/jwt"
|
"github.com/topfans/backend/pkg/jwt"
|
||||||
"github.com/topfans/backend/pkg/logger"
|
"github.com/topfans/backend/pkg/logger"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
@ -46,7 +47,30 @@ func AuthMiddleware() gin.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 将用户信息存入 gin.Context
|
// 4. 检查 Token 是否在黑名单
|
||||||
|
isBlacklisted, bannedUserID, banReason, err := database.IsBlacklisted(c.Request.Context(), token)
|
||||||
|
if err != nil {
|
||||||
|
// Redis 错误时 fail-closed(安全策略),拒绝请求
|
||||||
|
logger.Logger.Error("Failed to check blacklist, rejecting request for security",
|
||||||
|
zap.String("path", c.Request.URL.Path),
|
||||||
|
zap.Error(err),
|
||||||
|
)
|
||||||
|
response.Unauthorized(c, "认证服务异常,请稍后重试")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if isBlacklisted {
|
||||||
|
logger.Logger.Warn("Token is blacklisted",
|
||||||
|
zap.Int64("banned_user_id", bannedUserID),
|
||||||
|
zap.String("ban_reason", banReason),
|
||||||
|
zap.String("path", c.Request.URL.Path),
|
||||||
|
)
|
||||||
|
response.Unauthorized(c, "账号已被封禁")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 将用户信息存入 gin.Context
|
||||||
c.Set("user_id", claims.UserID)
|
c.Set("user_id", claims.UserID)
|
||||||
c.Set("star_id", claims.StarID)
|
c.Set("star_id", claims.StarID)
|
||||||
c.Set("token_updated_at", claims.UpdatedAt)
|
c.Set("token_updated_at", claims.UpdatedAt)
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user