token.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package middleware
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "hongze/hrms_api/controller/resp"
  8. "hongze/hrms_api/global"
  9. "hongze/hrms_api/models/system"
  10. "hongze/hrms_api/utils"
  11. "time"
  12. )
  13. func Token() gin.HandlerFunc {
  14. return func(c *gin.Context) {
  15. token := c.Request.Header.Get("Authorization")
  16. if token == "" {
  17. token = c.DefaultQuery("authorization", "")
  18. if token == "" {
  19. token = c.DefaultQuery("Authorization", "")
  20. }
  21. }
  22. if token == "" {
  23. resp.TokenError(nil, "未登录或非法访问", "未登录或非法访问", c)
  24. c.Abort()
  25. return
  26. }
  27. sessionInfo := new(system.LoginTokenContent)
  28. content, _ := global.Redis.Get(context.TODO(), utils.HRSYSTEM_LOGIN_TOKEN+token).Result()
  29. if content == "" {
  30. resp.TokenError(nil, "信息已变更,请重新登陆!", "找不到对应session", c)
  31. c.Abort()
  32. return
  33. }
  34. err := json.Unmarshal([]byte(content), &sessionInfo)
  35. if sessionInfo == nil {
  36. resp.TokenError(nil, "信息已变更,请重新登陆!", "session解析失败", c)
  37. c.Abort()
  38. return
  39. }
  40. admin := new(system.SysAdmin)
  41. admin, err = admin.GetAdminByAdminId(sessionInfo.AdminId)
  42. if err != nil {
  43. if err == utils.ErrNoRow {
  44. resp.TokenError(nil, "信息已变更,请重新登陆!", "找不到对应账号", c)
  45. c.Abort()
  46. return
  47. }
  48. resp.TokenError(nil, "网络异常,请稍后重试!", err.Error(), c)
  49. c.Abort()
  50. return
  51. }
  52. if admin.Enabled == 0 {
  53. resp.SpecificFail(resp.HASFORBIDDEN_CODE, nil, "您的账号已被禁用,如需登录,请联系管理员", c)
  54. c.Abort()
  55. return
  56. }
  57. /*if admin.Password != sessionInfo.Password {
  58. resp.SpecificFail(resp.PASSWORDCHANGE_CODE, nil, "信息已变更,请重新登陆!", c)
  59. c.Abort()
  60. return
  61. }*/
  62. //更新token的有效期,重置为30秒
  63. global.Redis.SetEX(context.TODO(), utils.HRSYSTEM_LOGIN_TOKEN+token, content, 120*time.Minute)
  64. // 不信任名单也同步更新
  65. if !sessionInfo.IsRemember {
  66. noTrustLoginKey := fmt.Sprint(utils.HRSYSTEM_LOGIN_TOKEN_NO_TRUST, admin.AdminId)
  67. tokenContent, _ := global.Redis.Get(context.TODO(), noTrustLoginKey).Result()
  68. if tokenContent != "" {
  69. global.Redis.SetEX(context.TODO(), noTrustLoginKey, tokenContent, 120*time.Minute)
  70. }
  71. }
  72. c.Set("adminInfo", admin)
  73. c.Next()
  74. }
  75. }