You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.2 KiB

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