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
  1. package system
  2. import (
  3. "context"
  4. "go.uber.org/zap"
  5. "time"
  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. }
  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.GVA_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.GVA_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: err error, redisJWT string
  41. func (jwtService *JwtService) GetRedisJWT(userName string) (err error, redisJWT string) {
  42. redisJWT, err = global.GVA_REDIS.Get(context.Background(), userName).Result()
  43. return err, redisJWT
  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. timer := time.Duration(global.GVA_CONFIG.JWT.ExpiresTime) * time.Second
  53. err = global.GVA_REDIS.Set(context.Background(), userName, jwt, timer).Err()
  54. return err
  55. }
  56. func LoadAll() {
  57. var data []string
  58. err := global.GVA_DB.Model(&system.JwtBlacklist{}).Select("jwt").Find(&data).Error
  59. if err != nil {
  60. global.GVA_LOG.Error("加载数据库jwt黑名单失败!", zap.Error(err))
  61. return
  62. }
  63. for i := 0; i < len(data); i++ {
  64. global.BlackCache.SetDefault(data[i], struct{}{})
  65. } // jwt黑名单 加入 BlackCache 中
  66. }