auth_jwt.go 929 B

123456789101112131415161718192021222324252627282930313233343536
  1. package middlewares
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/runningwater/gohub/app/models/user"
  6. "github.com/runningwater/gohub/pkg/config"
  7. "github.com/runningwater/gohub/pkg/jwt"
  8. "github.com/runningwater/gohub/pkg/response"
  9. )
  10. func AuthJWT() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. // 从请求头中获取 Authorization 字段,并验证 JWT
  13. claims, err := jwt.NewJWT().ParseToken(c)
  14. if err != nil {
  15. response.Unauthorized(c, fmt.Sprintf("请查看 %v 相关的接口认证文档", config.GetString("app.name")))
  16. return
  17. }
  18. // JWT 验证通过,将用户信息存入上下文
  19. userModel := user.Get(claims.UserID)
  20. if userModel.ID == 0 {
  21. response.Unauthorized(c, "找不到对应用户,用户可能已删除")
  22. return
  23. }
  24. c.Set("current_user_id", userModel.GetStringID())
  25. c.Set("current_user_name", userModel.Name)
  26. c.Set("current_user", userModel)
  27. c.Next()
  28. }
  29. }