feat: 实现日志追踪链路 #185

Merged
huanghaosheng merged 30 commits from feature/log-track into develop 2026-06-21 23:23:23 +08:00
Showing only changes of commit 0a59173476 - Show all commits

View File

@@ -5,6 +5,8 @@ import (
"strings" "strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/hhs/camtalk/internal/trace"
) )
// contextKey 用于在 Gin context 中存储 Claims 的 key。 // contextKey 用于在 Gin context 中存储 Claims 的 key。
@@ -17,8 +19,13 @@ const (
// 校验成功后将 user_id 和 username 写入 Gin Context。 // 校验成功后将 user_id 和 username 写入 Gin Context。
func AuthMiddleware(tokenMgr *TokenManager) gin.HandlerFunc { func AuthMiddleware(tokenMgr *TokenManager) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
log := trace.FromContext(c.Request.Context())
authHeader := c.GetHeader("Authorization") authHeader := c.GetHeader("Authorization")
if authHeader == "" { if authHeader == "" {
log.Warnw("auth rejected",
"client_ip", c.ClientIP(),
"path", c.Request.URL.Path,
"reason", "missing authorization header")
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": "INVALID_TOKEN", "code": "INVALID_TOKEN",
"message": "missing authorization header", "message": "missing authorization header",
@@ -29,6 +36,10 @@ func AuthMiddleware(tokenMgr *TokenManager) gin.HandlerFunc {
// 提取 Bearer token // 提取 Bearer token
parts := strings.SplitN(authHeader, " ", 2) parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
log.Warnw("auth rejected",
"client_ip", c.ClientIP(),
"path", c.Request.URL.Path,
"reason", "invalid authorization format")
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": "INVALID_TOKEN", "code": "INVALID_TOKEN",
"message": "invalid authorization format", "message": "invalid authorization format",
@@ -38,6 +49,11 @@ func AuthMiddleware(tokenMgr *TokenManager) gin.HandlerFunc {
claims, err := tokenMgr.ValidateAccess(parts[1]) claims, err := tokenMgr.ValidateAccess(parts[1])
if err != nil { if err != nil {
log.Warnw("auth rejected",
"client_ip", c.ClientIP(),
"path", c.Request.URL.Path,
"reason", "invalid or expired token",
"error", err)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": "INVALID_TOKEN", "code": "INVALID_TOKEN",
"message": "invalid or expired token", "message": "invalid or expired token",