From 46f447447b8bf50a11f3e94bbd096d5fc18f1dfb Mon Sep 17 00:00:00 2001 From: d1slike Date: Tue, 26 Jul 2022 21:26:01 +0300 Subject: [PATCH] MSP-437 implement auth service --- service/authentication.go | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 service/authentication.go diff --git a/service/authentication.go b/service/authentication.go new file mode 100644 index 0000000..b217f63 --- /dev/null +++ b/service/authentication.go @@ -0,0 +1,55 @@ +package service + +import ( + "context" + + "github.com/pkg/errors" + "isp-gate-service/domain" +) + +type AuthenticationCache interface { + Get(ctx context.Context, token string) (*domain.AuthData, error) + Set(ctx context.Context, token string, data domain.AuthData) error +} + +type AuthenticationRepo interface { + Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) +} + +type Auth struct { + cache AuthenticationCache + repo AuthenticationRepo +} + +func NewAuthentication(cache AuthenticationCache, repo AuthenticationRepo) Auth { + return Auth{ + cache: cache, + repo: repo, + } +} + +func (s Auth) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) { + authData, err := s.cache.Get(ctx, token) + if errors.Is(err, domain.ErrAuthenticationCacheMiss) { + resp, err := s.repo.Authenticate(ctx, token) + if err != nil { + return nil, errors.WithMessage(err, "auth repo authenticate") + } + if !resp.Authenticated { + return resp, nil + } + err = s.cache.Set(ctx, token, *resp.AuthData) + if err != nil { + return nil, errors.WithMessage(err, "auth cache set") + } + return resp, nil + } + if err != nil { + return nil, errors.WithMessage(err, "auth cache get") + } + return &domain.AuthenticateResponse{ + Authenticated: true, + ErrorReason: "", + AuthData: authData, + }, nil +}