From 57a46767cd694430cb0211dc4867b91a63c06189 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mih=C3=A1ly=20Gy=C3=B6ngy=C3=B6si?= Date: Fri, 12 Aug 2022 09:47:47 +0200 Subject: [PATCH] AccessControl: Move GetCacheKey to SignedInUser (#53591) * Add HasUniqueId and IsApiKeyUser to SignedInUser * Improve GetCacheKey by explicit checks and error branch * Align SignedInUser to merged changes * change comparison method Co-authored-by: jguer --- pkg/services/user/model.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/pkg/services/user/model.go b/pkg/services/user/model.go index be2dbd139fe..44fa5ae4018 100644 --- a/pkg/services/user/model.go +++ b/pkg/services/user/model.go @@ -26,6 +26,7 @@ var ( ErrUserAlreadyExists = errors.New("user already exists") ErrLastGrafanaAdmin = errors.New("cannot remove last grafana admin") ErrProtectedUser = errors.New("cannot adopt protected user") + ErrNoUniqueID = errors.New("identifying id not found") ) type User struct { @@ -245,6 +246,7 @@ func (u *SignedInUser) ToUserDisplayDTO() *UserDisplayDTO { Name: u.Name, } } + func (u *SignedInUser) HasRole(role org.RoleType) bool { if u.IsGrafanaAdmin { return true @@ -254,7 +256,25 @@ func (u *SignedInUser) HasRole(role org.RoleType) bool { } func (u *SignedInUser) IsRealUser() bool { - return u.UserID != 0 + return u.UserID > 0 +} + +func (u *SignedInUser) IsApiKeyUser() bool { + return u.ApiKeyID > 0 +} + +func (u *SignedInUser) HasUniqueId() bool { + return u.IsRealUser() || u.IsApiKeyUser() +} + +func (u *SignedInUser) GetCacheKey() (string, error) { + if u.IsRealUser() { + return fmt.Sprintf("%d-user-%d", u.OrgID, u.UserID), nil + } + if u.IsApiKeyUser() { + return fmt.Sprintf("%d-apikey-%d", u.OrgID, u.ApiKeyID), nil + } + return "", ErrNoUniqueID } func (e *ErrCaseInsensitiveLoginConflict) Unwrap() error {