token.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "hongze/hongze_yb_en_api/controller/resp"
  5. "hongze/hongze_yb_en_api/models/english_report_email"
  6. "hongze/hongze_yb_en_api/models/session"
  7. "hongze/hongze_yb_en_api/services"
  8. "hongze/hongze_yb_en_api/utils"
  9. )
  10. func Token() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. token := c.Request.Header.Get("Authorization")
  13. if token == "" {
  14. token = c.DefaultQuery("authorization", "")
  15. if token == "" {
  16. token = c.DefaultQuery("Authorization", "")
  17. }
  18. }
  19. if token == "" {
  20. resp.TokenError(nil, "未登录或非法访问", "未登录或非法访问", c)
  21. c.Abort()
  22. return
  23. }
  24. sessionInfo, err := session.GetTokenByToken(token)
  25. if err != nil {
  26. if err == utils.ErrNoRow {
  27. resp.TokenError(nil, "信息已变更,请重新登陆!", "找不到对应session", c)
  28. c.Abort()
  29. return
  30. }
  31. resp.TokenError(nil, "网络异常,请稍后重试!", err.Error(), c)
  32. c.Abort()
  33. return
  34. }
  35. if sessionInfo == nil {
  36. resp.TokenError(nil, "网络异常,请稍后重试1038!", "找不到对应session", c)
  37. c.Abort()
  38. return
  39. }
  40. emailItem := english_report_email.Email{Id: uint(sessionInfo.UserId)}
  41. userEmail, err := emailItem.GetById(sessionInfo.UserId)
  42. if err != nil && err != utils.ErrNoRow {
  43. resp.TokenError(nil, "数据异常!", "userID查询用户信息错误", c)
  44. c.Abort()
  45. return
  46. }
  47. if userEmail.Enable == 0 || userEmail.Status == 3 {
  48. resp.TokenError(nil, "User disabled", "User disabled", c)
  49. c.Abort()
  50. return
  51. }
  52. userInfo := services.UserInfo{
  53. Email: *userEmail,
  54. }
  55. userInfo.LoginToken = token
  56. c.Set("userInfo", userInfo)
  57. c.Next()
  58. }
  59. }