token.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "hongze/hongze_yb/controller/response"
  6. "hongze/hongze_yb/models/tables/rddp/session"
  7. services "hongze/hongze_yb/services/user"
  8. "hongze/hongze_yb/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. response.TokenError(nil, "未登录或非法访问", "未登录或非法访问", c)
  21. c.Abort()
  22. return
  23. }
  24. utils.SetContextLogListByClaims(c, fmt.Sprint("Token:", token))
  25. sessionInfo, err := session.GetTokenByToken(token)
  26. if err != nil {
  27. if err == utils.ErrNoRow {
  28. response.TokenError(nil, "信息已变更,请重新登陆!", "找不到对应session", c)
  29. c.Abort()
  30. return
  31. }
  32. response.TokenError(nil, "网络异常,请稍后重试!", err.Error(), c)
  33. c.Abort()
  34. return
  35. }
  36. if sessionInfo == nil {
  37. response.TokenError(nil, "网络异常,请稍后重试1038!", "找不到对应session", c)
  38. c.Abort()
  39. return
  40. }
  41. var userInfo services.UserInfo
  42. if sessionInfo.OpenID != "" {
  43. tmpUserInfo, tmpErr := services.GetWxUserItemByOpenId(sessionInfo.OpenID)
  44. userInfo = tmpUserInfo
  45. err = tmpErr
  46. if err != nil && err != services.ERR_NO_USER_RECORD && err != services.ERR_USER_NOT_BIND {
  47. response.TokenError(nil, "数据异常!", "openid查询用户信息错误", c)
  48. c.Abort()
  49. return
  50. }
  51. } else {
  52. //判断pc端登录的情况
  53. tmpUserInfo, tmpErr := services.GetWxUserItemByUserId(int(sessionInfo.UserID), 3)
  54. userInfo = tmpUserInfo
  55. err = tmpErr
  56. if err != nil {
  57. response.TokenError(nil, "数据异常!", "userID查询用户信息错误", c)
  58. c.Abort()
  59. return
  60. }
  61. }
  62. if err != nil && err != services.ERR_USER_NOT_BIND {
  63. //用户openid查询出来发现没有绑定用户
  64. //if err == services.ERR_USER_NOT_BIND {
  65. // response.TokenError(nil, "信息已变更,请重新登陆1058!", err.Error(), c)
  66. // c.Abort()
  67. // return
  68. //}
  69. //没有找到记录
  70. if err == utils.ErrNoRow {
  71. response.TokenError(nil, "信息已变更,请重新登陆2064!", err.Error(), c)
  72. c.Abort()
  73. return
  74. }
  75. response.TokenError(nil, "网络异常,请稍后重试3069!", err.Error(), c)
  76. c.Abort()
  77. return
  78. }
  79. userInfo.LoginToken = token
  80. c.Set("userInfo", userInfo)
  81. c.Next()
  82. }
  83. }