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.1 KiB

3 years ago
3 years ago
3 years ago
  1. package system
  2. import (
  3. "context"
  4. "time"
  5. "github.com/flipped-aurora/gin-vue-admin/server/global"
  6. "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  7. )
  8. type JwtService struct {
  9. }
  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. }{})
  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.Find(&system.JwtBlacklist{}).Select("jwt").Find(&data).Error
  59. if err != nil {
  60. // 从db加载jwt数据
  61. for i := range data {
  62. global.BlackCache.SetDefault(data[i], struct {
  63. }{})
  64. }
  65. }
  66. }