token.go 2.4 KB

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