12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package sso
- import (
- "encoding/json"
- "fmt"
- operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
- "gitee.com/xuyiping_admin/pkg/tool"
- "kpt-tmr-group/config"
- "time"
- "gitee.com/xuyiping_admin/pkg/xerr"
- "github.com/go-redis/redis"
- redisv7 "github.com/go-redis/redis/v7"
- )
- type Cache struct {
- Client *redisv7.Client
- Expiry time.Duration
- }
- func NewCache(cfg *config.AppConfig) *Cache {
- return &Cache{
- Client: NewClientLatest(cfg),
- Expiry: time.Duration(cfg.RedisSetting.SSOCache.Expiry) * time.Minute,
- }
- }
- func (c *Cache) Auth(userAuth *operationPb.UserAuthData) (string, error) {
- return c.get(fmt.Sprintf("sso:auth:%s", tool.Md5String(fmt.Sprintf("%s-%s", userAuth.UserName, userAuth.Password))))
- }
- func (c *Cache) CacheAuth(token string, res interface{}) error {
- return c.set(fmt.Sprintf("sso:auth:%s", token), res)
- }
- func (c *Cache) GetAccount(token string) (interface{}, error) {
- return c.get(fmt.Sprintf("sso:get_account:%s", token))
- }
- func (c *Cache) CacheSetAccount(token string, res interface{}) error {
- return c.set(fmt.Sprintf("sso:get_account:%s", token), res)
- }
- func (c *Cache) get(key string) (string, error) {
- bs, err := c.Client.Get(key).Bytes()
- if err != nil {
- return "", xerr.WithMessage(err, key)
- }
- if len(bs) == 0 {
- return "", xerr.WithStack(redis.Nil)
- }
- return string(bs), nil
- }
- func (c *Cache) set(key string, res interface{}) error {
- if res == nil {
- return nil
- }
- b, _ := json.Marshal(res)
- if err := c.Client.Set(key, string(b), c.Expiry).Err(); err != nil {
- return xerr.WithMessage(err, key, string(b))
- }
- return nil
- }
|