From 2ca358a4eacda605465d69b41bea5ed4995efeff Mon Sep 17 00:00:00 2001 From: d1slike Date: Tue, 26 Jul 2022 21:25:44 +0300 Subject: [PATCH] MSP-437 implement auth cache repository --- domain/cache.go | 9 ++++++ repository/authentication_cache.go | 49 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 domain/cache.go create mode 100644 repository/authentication_cache.go diff --git a/domain/cache.go b/domain/cache.go new file mode 100644 index 0000000..9436b4f --- /dev/null +++ b/domain/cache.go @@ -0,0 +1,9 @@ +package domain + +import ( + "github.com/pkg/errors" +) + +var ( + ErrAuthenticationCacheMiss = errors.New("authentication not found in cache") +) diff --git a/repository/authentication_cache.go b/repository/authentication_cache.go new file mode 100644 index 0000000..20b9dca --- /dev/null +++ b/repository/authentication_cache.go @@ -0,0 +1,49 @@ +package repository + +import ( + "context" + "time" + + "github.com/integration-system/isp-kit/json" + "github.com/pkg/errors" + "isp-gate-service/cache" + "isp-gate-service/domain" +) + +type AuthenticationCache struct { + cache *cache.Cache + duration time.Duration +} + +func NewAuthenticationCache(duration time.Duration) AuthenticationCache { + return AuthenticationCache{ + duration: duration, + cache: cache.New(), + } +} + +func (r AuthenticationCache) Get(ctx context.Context, token string) (*domain.AuthData, error) { + data, ok := r.cache.Get(token) + if !ok { + return nil, domain.ErrAuthenticationCacheMiss + } + + result := domain.AuthData{} + err := json.Unmarshal(data, &result) + if err != nil { + return nil, errors.WithMessage(err, "json unmarshal auth data") + } + + return &result, nil +} + +func (r AuthenticationCache) Set(ctx context.Context, token string, data domain.AuthData) error { + value, err := json.Marshal(data) + if err != nil { + return errors.WithMessage(err, "json marshal auth data") + } + + r.cache.Set(token, value, r.duration) + + return nil +}