cache.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package sso
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
  6. "gitee.com/xuyiping_admin/pkg/tool"
  7. "kpt-tmr-group/config"
  8. "time"
  9. "gitee.com/xuyiping_admin/pkg/xerr"
  10. "github.com/go-redis/redis"
  11. redisv7 "github.com/go-redis/redis/v7"
  12. )
  13. type Cache struct {
  14. Client *redisv7.Client
  15. Expiry time.Duration
  16. }
  17. func NewCache(cfg *config.AppConfig) *Cache {
  18. return &Cache{
  19. Client: NewClientLatest(cfg),
  20. Expiry: time.Duration(cfg.RedisSetting.SSOCache.Expiry) * time.Minute,
  21. }
  22. }
  23. func (c *Cache) Auth(userAuth *operationPb.UserAuthData) (string, error) {
  24. return c.get(fmt.Sprintf("sso:auth:%s", tool.Md5String(fmt.Sprintf("%s-%s", userAuth.UserName, userAuth.Password))))
  25. }
  26. func (c *Cache) CacheAuth(token string, res interface{}) error {
  27. return c.set(fmt.Sprintf("sso:auth:%s", token), res)
  28. }
  29. func (c *Cache) GetAccount(token string) (interface{}, error) {
  30. return c.get(fmt.Sprintf("sso:get_account:%s", token))
  31. }
  32. func (c *Cache) CacheSetAccount(token string, res interface{}) error {
  33. return c.set(fmt.Sprintf("sso:get_account:%s", token), res)
  34. }
  35. func (c *Cache) get(key string) (string, error) {
  36. bs, err := c.Client.Get(key).Bytes()
  37. if err != nil {
  38. return "", xerr.WithMessage(err, key)
  39. }
  40. if len(bs) == 0 {
  41. return "", xerr.WithStack(redis.Nil)
  42. }
  43. return string(bs), nil
  44. }
  45. func (c *Cache) set(key string, res interface{}) error {
  46. if res == nil {
  47. return nil
  48. }
  49. b, _ := json.Marshal(res)
  50. if err := c.Client.Set(key, string(b), c.Expiry).Err(); err != nil {
  51. return xerr.WithMessage(err, key, string(b))
  52. }
  53. return nil
  54. }