57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
|
|
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
|
|||
|
|
}
|