|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"gofaster/internal/shared/jwt"
|
|
|
|
"gofaster/internal/shared/response"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
// JWTConfig JWT中间件配置
|
|
|
|
type JWTConfig struct {
|
|
|
|
SecretKey string
|
|
|
|
Issuer string
|
|
|
|
}
|
|
|
|
|
|
|
|
// JWTAuth JWT认证中间件
|
|
|
|
func JWTAuth(config JWTConfig) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
fmt.Printf("🚀 JWTAuth中间件开始执行 - 路径: %s\n", c.Request.URL.Path)
|
|
|
|
fmt.Printf("🔑 JWT配置: SecretKey=%s, Issuer=%s\n", config.SecretKey[:10]+"...", config.Issuer)
|
|
|
|
|
|
|
|
// 获取Authorization头部
|
|
|
|
authHeader := c.GetHeader("Authorization")
|
|
|
|
fmt.Printf("📋 Authorization头部: %s\n", authHeader)
|
|
|
|
|
|
|
|
if authHeader == "" {
|
|
|
|
fmt.Printf("❌ JWTAuth中间件 - Authorization头部缺失\n")
|
|
|
|
response.Unauthorized(c, "未提供认证令牌", "Authorization头部缺失")
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// 检查Bearer前缀
|
|
|
|
if !strings.HasPrefix(authHeader, "Bearer ") {
|
|
|
|
fmt.Printf("❌ JWTAuth中间件 - Bearer前缀缺失\n")
|
|
|
|
response.Unauthorized(c, "认证令牌格式错误", "令牌必须以Bearer开头")
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// 提取令牌
|
|
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
|
|
|
if len(tokenString) > 20 {
|
|
|
|
fmt.Printf("JWTAuth中间件 - 提取的令牌: %s...\n", tokenString[:20])
|
|
|
|
} else {
|
|
|
|
fmt.Printf("JWTAuth中间件 - 提取的令牌: %s\n", tokenString)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 创建JWT管理器
|
|
|
|
jwtManager := jwt.NewJWTManager(config.SecretKey, config.Issuer)
|
|
|
|
|
|
|
|
// 验证令牌
|
|
|
|
fmt.Printf("JWTAuth中间件 - 开始验证令牌\n")
|
|
|
|
claims, err := jwtManager.ValidateToken(tokenString)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("JWTAuth中间件 - 令牌验证失败: %v\n", err)
|
|
|
|
response.Unauthorized(c, "认证令牌无效", err.Error())
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Printf("✅ JWTAuth中间件 - 令牌验证成功\n")
|
|
|
|
fmt.Printf("📊 JWTAuth中间件 - 解析的claims: %+v\n", claims)
|
|
|
|
fmt.Printf("🔍 JWTAuth中间件 - claims类型: %T\n", claims)
|
|
|
|
fmt.Printf("📏 JWTAuth中间件 - claims长度: %d\n", len(claims))
|
|
|
|
|
|
|
|
// 遍历所有claims键值对
|
|
|
|
for key, value := range claims {
|
|
|
|
fmt.Printf("🔑 JWTAuth中间件 - claim[%s]: 类型=%T, 值=%v\n", key, value, value)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 安全地存储用户信息到上下文中
|
|
|
|
if userID, exists := claims["user_id"]; exists {
|
|
|
|
fmt.Printf("✅ JWTAuth中间件 - user_id类型: %T, 值: %v\n", userID, userID)
|
|
|
|
// 直接存储原始值,不进行类型转换
|
|
|
|
c.Set("user_id", userID)
|
|
|
|
fmt.Printf("💾 JWTAuth中间件 - 已存储user_id到上下文\n")
|
|
|
|
} else {
|
|
|
|
fmt.Printf("❌ JWTAuth中间件 - claims中未找到user_id\n")
|
|
|
|
// 尝试其他可能的键名
|
|
|
|
if userID, exists := claims["userID"]; exists {
|
|
|
|
fmt.Printf("✅ JWTAuth中间件 - 找到userID: 类型=%T, 值=%v\n", userID, userID)
|
|
|
|
c.Set("user_id", userID)
|
|
|
|
fmt.Printf("💾 JWTAuth中间件 - 已存储userID到上下文\n")
|
|
|
|
} else if userID, exists := claims["userId"]; exists {
|
|
|
|
fmt.Printf("✅ JWTAuth中间件 - 找到userId: 类型=%T, 值=%v\n", userID, userID)
|
|
|
|
c.Set("user_id", userID)
|
|
|
|
fmt.Printf("💾 JWTAuth中间件 - 已存储userId到上下文\n")
|
|
|
|
} else {
|
|
|
|
fmt.Printf("❌ JWTAuth中间件 - 所有可能的用户ID键都未找到\n")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if username, exists := claims["username"]; exists {
|
|
|
|
fmt.Printf("JWTAuth中间件 - username类型: %T, 值: %v\n", username, username)
|
|
|
|
c.Set("username", username)
|
|
|
|
}
|
|
|
|
|
|
|
|
if email, exists := claims["email"]; exists {
|
|
|
|
fmt.Printf("JWTAuth中间件 - email类型: %T, 值: %v\n", email, email)
|
|
|
|
c.Set("email", email)
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Printf("JWTAuth中间件 - 准备调用c.Next()\n")
|
|
|
|
// 继续处理请求
|
|
|
|
c.Next()
|
|
|
|
fmt.Printf("JWTAuth中间件 - c.Next()执行完成\n")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// OptionalJWTAuth 可选的JWT认证中间件(不强制要求认证)
|
|
|
|
func OptionalJWTAuth(config JWTConfig) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
// 获取Authorization头部
|
|
|
|
authHeader := c.GetHeader("Authorization")
|
|
|
|
if authHeader == "" {
|
|
|
|
// 没有令牌,继续处理请求
|
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// 检查Bearer前缀
|
|
|
|
if !strings.HasPrefix(authHeader, "Bearer ") {
|
|
|
|
// 令牌格式错误,继续处理请求(不强制要求)
|
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// 提取令牌
|
|
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
|
|
|
|
|
|
|
// 创建JWT管理器
|
|
|
|
jwtManager := jwt.NewJWTManager(config.SecretKey, config.Issuer)
|
|
|
|
|
|
|
|
// 验证令牌
|
|
|
|
claims, err := jwtManager.ValidateToken(tokenString)
|
|
|
|
if err != nil {
|
|
|
|
// 令牌无效,继续处理请求(不强制要求)
|
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// 将用户信息存储到上下文中
|
|
|
|
if userID, exists := claims["user_id"]; exists {
|
|
|
|
c.Set("user_id", userID)
|
|
|
|
}
|
|
|
|
if username, exists := claims["username"]; exists {
|
|
|
|
c.Set("username", username)
|
|
|
|
}
|
|
|
|
if email, exists := claims["email"]; exists {
|
|
|
|
c.Set("email", email)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 继续处理请求
|
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetUserID 从上下文中获取用户ID
|
|
|
|
func GetUserID(c *gin.Context) (uint, bool) {
|
|
|
|
fmt.Printf("🔍 GetUserID函数开始执行\n")
|
|
|
|
|
|
|
|
userID, exists := c.Get("user_id")
|
|
|
|
if !exists {
|
|
|
|
fmt.Printf("❌ GetUserID - user_id不存在于上下文中\n")
|
|
|
|
return 0, false
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Printf("✅ GetUserID - 从上下文获取的user_id类型: %T, 值: %v\n", userID, userID)
|
|
|
|
|
|
|
|
// 安全地进行类型转换,避免panic
|
|
|
|
switch v := userID.(type) {
|
|
|
|
case uint:
|
|
|
|
fmt.Printf("GetUserID - 类型匹配uint: %d\n", v)
|
|
|
|
return v, true
|
|
|
|
case int:
|
|
|
|
if v >= 0 {
|
|
|
|
fmt.Printf("GetUserID - 类型匹配int: %d, 转换为uint: %d\n", v, uint(v))
|
|
|
|
return uint(v), true
|
|
|
|
} else {
|
|
|
|
fmt.Printf("GetUserID - 类型匹配int: %d, 但值为负数,无法转换为uint\n", v)
|
|
|
|
}
|
|
|
|
case int64:
|
|
|
|
if v >= 0 {
|
|
|
|
fmt.Printf("GetUserID - 类型匹配int64: %d, 转换为uint: %d\n", v, uint(v))
|
|
|
|
return uint(v), true
|
|
|
|
} else {
|
|
|
|
fmt.Printf("GetUserID - 类型匹配int64: %d, 但值为负数,无法转换为uint\n", v)
|
|
|
|
}
|
|
|
|
case float64:
|
|
|
|
if v >= 0 && v <= float64(^uint(0)) {
|
|
|
|
fmt.Printf("GetUserID - 类型匹配float64: %f, 转换为uint: %d\n", v, uint(v))
|
|
|
|
return uint(v), true
|
|
|
|
} else {
|
|
|
|
fmt.Printf("GetUserID - 类型匹配float64: %f, 但值超出uint范围,无法转换\n", v)
|
|
|
|
}
|
|
|
|
case string:
|
|
|
|
if parsed, err := strconv.ParseUint(v, 10, 32); err == nil {
|
|
|
|
fmt.Printf("GetUserID - 类型匹配string: %s, 解析为uint: %d\n", v, uint(parsed))
|
|
|
|
return uint(parsed), true
|
|
|
|
} else {
|
|
|
|
fmt.Printf("GetUserID - 类型匹配string: %s, 但解析失败: %v\n", v, err)
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
fmt.Printf("GetUserID - 未知类型: %T, 值: %v\n", userID, userID)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 如果所有类型转换都失败,返回0和false
|
|
|
|
fmt.Printf("GetUserID - 所有类型转换都失败,返回0\n")
|
|
|
|
return 0, false
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetUsername 从上下文中获取用户名
|
|
|
|
func GetUsername(c *gin.Context) (string, bool) {
|
|
|
|
username, exists := c.Get("username")
|
|
|
|
if !exists {
|
|
|
|
return "", false
|
|
|
|
}
|
|
|
|
if str, ok := username.(string); ok {
|
|
|
|
return str, true
|
|
|
|
}
|
|
|
|
return "", false
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetEmail 从上下文中获取邮箱
|
|
|
|
func GetEmail(c *gin.Context) (string, bool) {
|
|
|
|
email, exists := c.Get("email")
|
|
|
|
if !exists {
|
|
|
|
return "", false
|
|
|
|
}
|
|
|
|
if str, ok := email.(string); ok {
|
|
|
|
return str, true
|
|
|
|
}
|
|
|
|
return "", false
|
|
|
|
}
|