From a6c7ff3af35b1c1efa52ceee2b4a020739a6002c Mon Sep 17 00:00:00 2001 From: d1slike Date: Tue, 26 Jul 2022 21:27:17 +0300 Subject: [PATCH] MSP-437 implement authz service --- service/authorization.go | 51 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 service/authorization.go diff --git a/service/authorization.go b/service/authorization.go new file mode 100644 index 0000000..29b296f --- /dev/null +++ b/service/authorization.go @@ -0,0 +1,51 @@ +package service + +import ( + "context" + + "github.com/pkg/errors" +) + +type AuthorizationCache interface { + Get(ctx context.Context, applicationId int, endpoint string) (bool, error) + SetAuthorized(ctx context.Context, applicationId int, endpoint string) error +} + +type AuthorizationRepo interface { + Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) +} + +type Authorization struct { + cache AuthorizationCache + repo AuthorizationRepo +} + +func NewAuthorization(cache AuthorizationCache, repo AuthorizationRepo) Authorization { + return Authorization{ + cache: cache, + repo: repo, + } +} + +func (s Authorization) Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) { + ok, err := s.cache.Get(ctx, applicationId, endpoint) + if err != nil { + return false, errors.WithMessage(err, "authz cache get") + } + if ok { + return ok, nil + } + + ok, err = s.repo.Authorize(ctx, applicationId, endpoint) + if err != nil { + return false, errors.WithMessagef(err, "authz repo authorize") + } + if ok { + err = s.cache.SetAuthorized(ctx, applicationId, endpoint) + if err != nil { + return false, errors.WithMessagef(err, "authz cache set") + } + } + + return ok, nil +}