package middlewares import ( "fmt" "github.com/gin-gonic/gin" "github.com/runningwater/gohub/app/models/user" "github.com/runningwater/gohub/pkg/config" "github.com/runningwater/gohub/pkg/jwt" "github.com/runningwater/gohub/pkg/response" ) func AuthJWT() gin.HandlerFunc { return func(c *gin.Context) { // 从请求头中获取 Authorization 字段,并验证 JWT claims, err := jwt.NewJWT().ParseToken(c) if err != nil { response.Unauthorized(c, fmt.Sprintf("请查看 %v 相关的接口认证文档", config.GetString("app.name"))) return } // JWT 验证通过,将用户信息存入上下文 userModel := user.Get(claims.UserID) if userModel.ID == 0 { response.Unauthorized(c, "找不到对应用户,用户可能已删除") return } c.Set("current_user_id", userModel.GetStringID()) c.Set("current_user_name", userModel.Name) c.Set("current_user", userModel) c.Next() } }