From 960ad5a253f2c029f0309e78032fff724cddffc3 Mon Sep 17 00:00:00 2001 From: d1slike Date: Tue, 14 Nov 2023 12:36:25 +0300 Subject: [PATCH] MSP-2370 implement admin authz in service --- service/admin.go | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/service/admin.go b/service/admin.go index fbed76e..9330613 100644 --- a/service/admin.go +++ b/service/admin.go @@ -2,6 +2,7 @@ package service import ( "context" + "isp-gate-service/domain" "github.com/pkg/errors" @@ -9,22 +10,48 @@ import ( type AdminAuth interface { Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) + Authorize(ctx context.Context, adminId int, permission string) (bool, error) } type Admin struct { - admin AdminAuth + cache AuthorizationCache + repo AdminAuth } -func NewAdmin(adminAuth AdminAuth) Admin { +func NewAdmin(cache AuthorizationCache, adminAuth AdminAuth) Admin { return Admin{ - admin: adminAuth, + cache: cache, + repo: adminAuth, } } func (s Admin) AdminAuthenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) { - resp, err := s.admin.Authenticate(ctx, token) + resp, err := s.repo.Authenticate(ctx, token) if err != nil { return nil, errors.WithMessage(err, "get admin token data from admin service") } return resp, nil } + +func (s Admin) AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error) { + ok, err := s.cache.Get(ctx, adminId, permission) + if err != nil { + return false, errors.WithMessage(err, "authz cache get") + } + if ok { + return ok, nil + } + + ok, err = s.repo.Authorize(ctx, adminId, permission) + if err != nil { + return false, errors.WithMessagef(err, "authz repo authorize") + } + if ok { + err = s.cache.SetAuthorized(ctx, adminId, permission) + if err != nil { + return false, errors.WithMessagef(err, "authz cache set") + } + } + + return ok, nil +}