Files
tyc-server/app/main/api/internal/middleware/logging/jwtExtractor.go
2025-08-31 14:18:31 +08:00

57 lines
1.2 KiB
Go
Raw 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 logging
import (
"fmt"
"strings"
jwtx "tyc-server/common/jwt"
"github.com/zeromicro/go-zero/core/logx"
)
// jwtExtractor JWT用户信息提取器
type jwtExtractor struct {
jwtSecret string
}
// newJWTExtractor 创建JWT提取器
func newJWTExtractor(jwtSecret string) *jwtExtractor {
return &jwtExtractor{
jwtSecret: jwtSecret,
}
}
// ExtractUserInfo 从Authorization头部提取用户信息
func (e *jwtExtractor) ExtractUserInfo(authHeader string) (userID, username string) {
if authHeader == "" {
return "", ""
}
// 检查Bearer前缀
if !strings.HasPrefix(authHeader, "Bearer ") {
return "", ""
}
// 提取Token
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == "" {
return "", ""
}
// 解析JWT Token
userIDInt, err := jwtx.ParseJwtToken(tokenString, e.jwtSecret)
if err != nil {
logx.Errorf("解析JWT Token失败: %v", err)
return "", ""
}
// 提取用户信息
if userIDInt > 0 {
userID = fmt.Sprintf("%d", userIDInt)
// 由于JWT中只包含用户ID用户名需要从其他地方获取
// 这里可以调用用户服务获取用户名或者暂时使用用户ID
username = fmt.Sprintf("user_%d", userIDInt)
}
return userID, username
}