jwt_black_list.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package system
  2. import (
  3. "context"
  4. "github.com/sirupsen/logrus"
  5. "go.uber.org/zap"
  6. "lc-base-frame/global"
  7. "lc-base-frame/model/system"
  8. "lc-base-frame/utils"
  9. )
  10. type JwtService struct{}
  11. //@author: [piexlmax](https://github.com/piexlmax)
  12. //@function: JsonInBlacklist
  13. //@description: 拉黑jwt
  14. //@param: jwtList model.JwtBlacklist
  15. //@return: err error
  16. func (jwtService *JwtService) JsonInBlacklist(jwtList system.JwtBlacklist) (err error) {
  17. err = global.Db.Create(&jwtList).Error
  18. if err != nil {
  19. return
  20. }
  21. global.BlackCache.SetDefault(jwtList.Jwt, struct{}{})
  22. return
  23. }
  24. //@author: [piexlmax](https://github.com/piexlmax)
  25. //@function: IsBlacklist
  26. //@description: 判断JWT是否在黑名单内部
  27. //@param: jwt string
  28. //@return: bool
  29. func (jwtService *JwtService) IsBlacklist(jwt string) bool {
  30. _, ok := global.BlackCache.Get(jwt)
  31. return ok
  32. // err := global.Db.Where("jwt = ?", jwt).First(&system.JwtBlacklist{}).Error
  33. // isNotFound := errors.Is(err, gorm.ErrRecordNotFound)
  34. // return !isNotFound
  35. }
  36. //@author: [piexlmax](https://github.com/piexlmax)
  37. //@function: GetRedisJWT
  38. //@description: 从redis取jwt
  39. //@param: userName string
  40. //@return: redisJWT string, err error
  41. func (jwtService *JwtService) GetRedisJWT(userName string) (redisJWT string, err error) {
  42. redisJWT, err = global.GVA_REDIS.Get(context.Background(), userName).Result()
  43. return redisJWT, err
  44. }
  45. //@author: [piexlmax](https://github.com/piexlmax)
  46. //@function: SetRedisJWT
  47. //@description: jwt存入redis并设置过期时间
  48. //@param: jwt string, userName string
  49. //@return: err error
  50. func (jwtService *JwtService) SetRedisJWT(jwt string, userName string) (err error) {
  51. // 此处过期时间等于jwt过期时间
  52. dr, err := utils.ParseDuration(global.Config.JWT.ExpiresTime)
  53. if err != nil {
  54. return err
  55. }
  56. timer := dr
  57. err = global.GVA_REDIS.Set(context.Background(), userName, jwt, timer).Err()
  58. return err
  59. }
  60. func LoadAll() {
  61. var data []string
  62. err := global.Db.Model(&system.JwtBlacklist{}).Select("jwt").Find(&data).Error
  63. if err != nil {
  64. logrus.Error("加载数据库jwt黑名单失败!", zap.Error(err))
  65. return
  66. }
  67. for i := 0; i < len(data); i++ {
  68. global.BlackCache.SetDefault(data[i], struct{}{})
  69. } // jwt黑名单 加入 BlackCache 中
  70. }