User: Clean up update functions (#86341)

* User: remove unused function

* User: Remove UpdatePermissions and support IsGrafanaAdmin flag in Update function instead

* User: Remove Disable function and use Update instead
This commit is contained in:
Karl Persson 2024-04-16 16:33:50 +02:00 committed by GitHub
parent 8c8885ef23
commit 0f06120b56
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 91 additions and 267 deletions

View File

@ -185,15 +185,17 @@ func (hs *HTTPServer) AdminUpdateUserPermissions(c *contextmodel.ReqContext) res
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
} }
getAuthQuery := login.GetAuthInfoQuery{UserId: userID} if authInfo, err := hs.authInfoService.GetAuthInfo(c.Req.Context(), &login.GetAuthInfoQuery{UserId: userID}); err == nil && authInfo != nil {
if authInfo, err := hs.authInfoService.GetAuthInfo(c.Req.Context(), &getAuthQuery); err == nil && authInfo != nil {
oauthInfo := hs.SocialService.GetOAuthInfoProvider(authInfo.AuthModule) oauthInfo := hs.SocialService.GetOAuthInfoProvider(authInfo.AuthModule)
if login.IsGrafanaAdminExternallySynced(hs.Cfg, oauthInfo, authInfo.AuthModule) { if login.IsGrafanaAdminExternallySynced(hs.Cfg, oauthInfo, authInfo.AuthModule) {
return response.Error(http.StatusForbidden, "Cannot change Grafana Admin role for externally synced user", nil) return response.Error(http.StatusForbidden, "Cannot change Grafana Admin role for externally synced user", nil)
} }
} }
err = hs.userService.UpdatePermissions(c.Req.Context(), userID, form.IsGrafanaAdmin) err = hs.userService.Update(c.Req.Context(), &user.UpdateUserCommand{
UserID: userID,
IsGrafanaAdmin: &form.IsGrafanaAdmin,
})
if err != nil { if err != nil {
if errors.Is(err, user.ErrLastGrafanaAdmin) { if errors.Is(err, user.ErrLastGrafanaAdmin) {
return response.Error(http.StatusBadRequest, user.ErrLastGrafanaAdmin.Error(), nil) return response.Error(http.StatusBadRequest, user.ErrLastGrafanaAdmin.Error(), nil)
@ -318,8 +320,8 @@ func (hs *HTTPServer) AdminDisableUser(c *contextmodel.ReqContext) response.Resp
return response.Error(http.StatusInternalServerError, "Could not disable external user", nil) return response.Error(http.StatusInternalServerError, "Could not disable external user", nil)
} }
disableCmd := user.DisableUserCommand{UserID: userID, IsDisabled: true} isDisabled := true
if err := hs.userService.Disable(c.Req.Context(), &disableCmd); err != nil { if err := hs.userService.Update(c.Req.Context(), &user.UpdateUserCommand{UserID: userID, IsDisabled: &isDisabled}); err != nil {
if errors.Is(err, user.ErrUserNotFound) { if errors.Is(err, user.ErrUserNotFound) {
return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil) return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil)
} }
@ -361,8 +363,8 @@ func (hs *HTTPServer) AdminEnableUser(c *contextmodel.ReqContext) response.Respo
return response.Error(http.StatusInternalServerError, "Could not enable external user", nil) return response.Error(http.StatusInternalServerError, "Could not enable external user", nil)
} }
disableCmd := user.DisableUserCommand{UserID: userID, IsDisabled: false} isDisabled := true
if err := hs.userService.Disable(c.Req.Context(), &disableCmd); err != nil { if err := hs.userService.Update(c.Req.Context(), &user.UpdateUserCommand{UserID: userID, IsDisabled: &isDisabled}); err != nil {
if errors.Is(err, user.ErrUserNotFound) { if errors.Is(err, user.ErrUserNotFound) {
return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil) return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil)
} }

View File

@ -195,7 +195,8 @@ func (s *UserSync) EnableUserHook(ctx context.Context, identity *authn.Identity,
return nil return nil
} }
return s.userService.Disable(ctx, &user.DisableUserCommand{UserID: userID, IsDisabled: false}) isDisabled := false
return s.userService.Update(ctx, &user.UpdateUserCommand{UserID: userID, IsDisabled: &isDisabled})
} }
func (s *UserSync) upsertAuthConnection(ctx context.Context, userID int64, identity *authn.Identity, createConnection bool) error { func (s *UserSync) upsertAuthConnection(ctx context.Context, userID int64, identity *authn.Identity, createConnection bool) error {
@ -258,6 +259,13 @@ func (s *UserSync) updateUserAttributes(ctx context.Context, usr *user.User, id
needsUpdate = true needsUpdate = true
} }
// Sync isGrafanaAdmin permission
if id.IsGrafanaAdmin != nil && *id.IsGrafanaAdmin != usr.IsAdmin {
updateCmd.IsGrafanaAdmin = id.IsGrafanaAdmin
usr.IsAdmin = *id.IsGrafanaAdmin
needsUpdate = true
}
if needsUpdate { if needsUpdate {
s.log.FromContext(ctx).Debug("Syncing user info", "id", id.ID, "update", fmt.Sprintf("%v", updateCmd)) s.log.FromContext(ctx).Debug("Syncing user info", "id", id.ID, "update", fmt.Sprintf("%v", updateCmd))
if err := s.userService.Update(ctx, updateCmd); err != nil { if err := s.userService.Update(ctx, updateCmd); err != nil {
@ -265,14 +273,6 @@ func (s *UserSync) updateUserAttributes(ctx context.Context, usr *user.User, id
} }
} }
// Sync isGrafanaAdmin permission
if id.IsGrafanaAdmin != nil && *id.IsGrafanaAdmin != usr.IsAdmin {
usr.IsAdmin = *id.IsGrafanaAdmin
if errPerms := s.userService.UpdatePermissions(ctx, usr.ID, *id.IsGrafanaAdmin); errPerms != nil {
return errPerms
}
}
return s.upsertAuthConnection(ctx, usr.ID, id, userAuth == nil) return s.upsertAuthConnection(ctx, usr.ID, id, userAuth == nil)
} }

View File

@ -509,7 +509,7 @@ func TestUserSync_EnableDisabledUserHook(t *testing.T) {
t.Run(tt.desc, func(t *testing.T) { t.Run(tt.desc, func(t *testing.T) {
userSvc := usertest.NewUserServiceFake() userSvc := usertest.NewUserServiceFake()
called := false called := false
userSvc.DisableFn = func(ctx context.Context, cmd *user.DisableUserCommand) error { userSvc.UpdateFn = func(ctx context.Context, cmd *user.UpdateUserCommand) error {
called = true called = true
return nil return nil
} }

View File

@ -99,7 +99,8 @@ func (c *LDAP) disableUser(ctx context.Context, username string) (*authn.Identit
// Disable the user // Disable the user
c.logger.Debug("User was removed from the LDAP directory tree, disabling it", "username", username, "authID", authinfo.AuthId) c.logger.Debug("User was removed from the LDAP directory tree, disabling it", "username", username, "authID", authinfo.AuthId)
if errDisable := c.userService.Disable(ctx, &user.DisableUserCommand{UserID: dbUser.ID, IsDisabled: true}); errDisable != nil { isDiabled := true
if errDisable := c.userService.Update(ctx, &user.UpdateUserCommand{UserID: dbUser.ID, IsDisabled: &isDiabled}); errDisable != nil {
return nil, errDisable return nil, errDisable
} }

View File

@ -187,7 +187,7 @@ func setupLDAPTestCase(tt *ldapTestCase) *LDAP {
userService := &usertest.FakeUserService{ userService := &usertest.FakeUserService{
ExpectedError: tt.expectedUserErr, ExpectedError: tt.expectedUserErr,
ExpectedUser: &tt.expectedUser, ExpectedUser: &tt.expectedUser,
DisableFn: func(ctx context.Context, cmd *user.DisableUserCommand) error { UpdateFn: func(ctx context.Context, cmd *user.UpdateUserCommand) error {
tt.disableCalled = true tt.disableCalled = true
return nil return nil
}, },

View File

@ -212,7 +212,8 @@ func (s *Service) PostSyncUserWithLDAP(c *contextmodel.ReqContext) response.Resp
return response.Error(http.StatusBadRequest, errMsg, err) return response.Error(http.StatusBadRequest, errMsg, err)
} }
if err := s.userService.Disable(c.Req.Context(), &user.DisableUserCommand{IsDisabled: true, UserID: usr.ID}); err != nil { isDisabled := true
if err := s.userService.Update(c.Req.Context(), &user.UpdateUserCommand{UserID: usr.ID, IsDisabled: &isDisabled}); err != nil {
return response.Error(http.StatusInternalServerError, "Failed to disable the user", err) return response.Error(http.StatusInternalServerError, "Failed to disable the user", err)
} }

View File

@ -82,8 +82,10 @@ type UpdateUserCommand struct {
Login string `json:"login"` Login string `json:"login"`
Theme string `json:"theme"` Theme string `json:"theme"`
UserID int64 `json:"-"` UserID int64 `json:"-"`
EmailVerified *bool `json:"-"` IsDisabled *bool `json:"-"`
EmailVerified *bool `json:"-"`
IsGrafanaAdmin *bool `json:"-"`
} }
type ChangeUserPasswordCommand struct { type ChangeUserPasswordCommand struct {
@ -176,11 +178,6 @@ func (auth *AuthModuleConversion) ToDB() ([]byte, error) {
return []byte{}, nil return []byte{}, nil
} }
type DisableUserCommand struct {
UserID int64 `xorm:"user_id"`
IsDisabled bool
}
type BatchDisableUsersCommand struct { type BatchDisableUsersCommand struct {
UserIDs []int64 `xorm:"user_ids"` UserIDs []int64 `xorm:"user_ids"`
IsDisabled bool IsDisabled bool

View File

@ -21,11 +21,8 @@ type Service interface {
SetUsingOrg(context.Context, *SetUsingOrgCommand) error SetUsingOrg(context.Context, *SetUsingOrgCommand) error
GetSignedInUserWithCacheCtx(context.Context, *GetSignedInUserQuery) (*SignedInUser, error) GetSignedInUserWithCacheCtx(context.Context, *GetSignedInUserQuery) (*SignedInUser, error)
GetSignedInUser(context.Context, *GetSignedInUserQuery) (*SignedInUser, error) GetSignedInUser(context.Context, *GetSignedInUserQuery) (*SignedInUser, error)
NewAnonymousSignedInUser(context.Context) (*SignedInUser, error)
Search(context.Context, *SearchUsersQuery) (*SearchUserQueryResult, error) Search(context.Context, *SearchUsersQuery) (*SearchUserQueryResult, error)
Disable(context.Context, *DisableUserCommand) error
BatchDisableUsers(context.Context, *BatchDisableUsersCommand) error BatchDisableUsers(context.Context, *BatchDisableUsersCommand) error
UpdatePermissions(context.Context, int64, bool) error
SetUserHelpFlag(context.Context, *SetUserHelpFlagCommand) error SetUserHelpFlag(context.Context, *SetUserHelpFlagCommand) error
GetProfile(context.Context, *GetUserProfileQuery) (*UserProfileDTO, error) GetProfile(context.Context, *GetUserProfileQuery) (*UserProfileDTO, error)
} }

View File

@ -34,11 +34,8 @@ type store interface {
UpdateUser(context.Context, *user.User) error UpdateUser(context.Context, *user.User) error
GetProfile(context.Context, *user.GetUserProfileQuery) (*user.UserProfileDTO, error) GetProfile(context.Context, *user.GetUserProfileQuery) (*user.UserProfileDTO, error)
SetHelpFlag(context.Context, *user.SetUserHelpFlagCommand) error SetHelpFlag(context.Context, *user.SetUserHelpFlagCommand) error
UpdatePermissions(context.Context, int64, bool) error
BatchDisableUsers(context.Context, *user.BatchDisableUsersCommand) error BatchDisableUsers(context.Context, *user.BatchDisableUsersCommand) error
Disable(context.Context, *user.DisableUserCommand) error
Search(context.Context, *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) Search(context.Context, *user.SearchUsersQuery) (*user.SearchUserQueryResult, error)
Count(ctx context.Context) (int64, error) Count(ctx context.Context) (int64, error)
CountUserAccountsWithEmptyRole(ctx context.Context) (int64, error) CountUserAccountsWithEmptyRole(ctx context.Context) (int64, error)
} }
@ -317,11 +314,21 @@ func (ss *sqlStore) Update(ctx context.Context, cmd *user.UpdateUserCommand) err
q := sess.ID(cmd.UserID).Where(ss.notServiceAccountFilter()) q := sess.ID(cmd.UserID).Where(ss.notServiceAccountFilter())
if cmd.IsDisabled != nil {
sess.UseBool("is_disabled")
user.IsDisabled = *cmd.IsDisabled
}
if cmd.EmailVerified != nil { if cmd.EmailVerified != nil {
q.UseBool("email_verified") q.UseBool("email_verified")
user.EmailVerified = *cmd.EmailVerified user.EmailVerified = *cmd.EmailVerified
} }
if cmd.IsGrafanaAdmin != nil {
q.UseBool("is_admin")
user.IsAdmin = *cmd.IsGrafanaAdmin
}
if _, err := q.Update(&user); err != nil { if _, err := q.Update(&user); err != nil {
return err return err
} }
@ -330,6 +337,13 @@ func (ss *sqlStore) Update(ctx context.Context, cmd *user.UpdateUserCommand) err
return err return err
} }
if cmd.IsGrafanaAdmin != nil && !*cmd.IsGrafanaAdmin {
// validate that after update there is at least one server admin
if err := validateOneAdminLeft(ctx, sess); err != nil {
return err
}
}
sess.PublishAfterCommit(&events.UserUpdated{ sess.PublishAfterCommit(&events.UserUpdated{
Timestamp: user.Created, Timestamp: user.Created,
Id: user.ID, Id: user.ID,
@ -476,28 +490,6 @@ func (ss *sqlStore) SetHelpFlag(ctx context.Context, cmd *user.SetUserHelpFlagCo
}) })
} }
// UpdatePermissions sets the user Server Admin flag
func (ss *sqlStore) UpdatePermissions(ctx context.Context, userID int64, isAdmin bool) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var user user.User
if _, err := sess.ID(userID).Where(ss.notServiceAccountFilter()).Get(&user); err != nil {
return err
}
user.IsAdmin = isAdmin
sess.UseBool("is_admin")
_, err := sess.ID(user.ID).Update(&user)
if err != nil {
return err
}
// validate that after update there is at least one server admin
if err := validateOneAdminLeft(ctx, sess); err != nil {
return err
}
return nil
})
}
func (ss *sqlStore) Count(ctx context.Context) (int64, error) { func (ss *sqlStore) Count(ctx context.Context) (int64, error) {
type result struct { type result struct {
Count int64 Count int64
@ -570,25 +562,6 @@ func (ss *sqlStore) BatchDisableUsers(ctx context.Context, cmd *user.BatchDisabl
}) })
} }
func (ss *sqlStore) Disable(ctx context.Context, cmd *user.DisableUserCommand) error {
return ss.db.WithDbSession(ctx, func(dbSess *db.Session) error {
usr := user.User{}
sess := dbSess.Table("user")
if has, err := sess.ID(cmd.UserID).Where(ss.notServiceAccountFilter()).Get(&usr); err != nil {
return err
} else if !has {
return user.ErrUserNotFound
}
usr.IsDisabled = cmd.IsDisabled
sess.UseBool("is_disabled")
_, err := sess.ID(cmd.UserID).Update(&usr)
return err
})
}
func (ss *sqlStore) Search(ctx context.Context, query *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) { func (ss *sqlStore) Search(ctx context.Context, query *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) {
result := user.SearchUserQueryResult{ result := user.SearchUserQueryResult{
Users: make([]*user.UserSearchHitDTO, 0), Users: make([]*user.UserSearchHitDTO, 0),

View File

@ -479,54 +479,47 @@ func TestIntegrationUserDataAccess(t *testing.T) {
t.Run("Testing DB - grafana admin users", func(t *testing.T) { t.Run("Testing DB - grafana admin users", func(t *testing.T) {
ss := db.InitTestDB(t) ss := db.InitTestDB(t)
_, usrSvc := createOrgAndUserSvc(t, ss, ss.Cfg) _, usrSvc := createOrgAndUserSvc(t, ss, ss.Cfg)
createUserCmd := user.CreateUserCommand{ usr, err := usrSvc.Create(context.Background(), &user.CreateUserCommand{
Email: fmt.Sprint("admin", "@test.com"), Email: "admin@test.com",
Name: "admin", Name: "admin",
Login: "admin", Login: "admin",
IsAdmin: true, IsAdmin: true,
} })
usr, err := usrSvc.Create(context.Background(), &createUserCmd)
require.Nil(t, err) require.Nil(t, err)
// Cannot make themselves a non-admin // Cannot make user non grafana admin if it is the last one
updatePermsError := userStore.UpdatePermissions(context.Background(), usr.ID, false) err = userStore.Update(context.Background(), &user.UpdateUserCommand{
require.Equal(t, user.ErrLastGrafanaAdmin, updatePermsError) UserID: usr.ID,
IsGrafanaAdmin: boolPtr(false),
})
require.ErrorIs(t, user.ErrLastGrafanaAdmin, err)
query := user.GetUserByIDQuery{ID: usr.ID} usr, err = userStore.GetByID(context.Background(), usr.ID)
queryResult, getUserError := userStore.GetByID(context.Background(), query.ID) require.NoError(t, err)
require.Nil(t, getUserError) require.True(t, usr.IsAdmin)
require.True(t, queryResult.IsAdmin)
// One user // Create another admin user
const email = "user@test.com" _, err = usrSvc.Create(context.Background(), &user.CreateUserCommand{
const username = "user" Email: "admin2@test.com",
createUserCmd = user.CreateUserCommand{ Name: "admin2",
Email: email, Login: "admin2",
Name: "user", IsAdmin: true,
Login: username, })
} require.NoError(t, err)
_, err = usrSvc.Create(context.Background(), &createUserCmd)
require.Nil(t, err)
// When trying to create a new user with the same email, an error is returned // Now first admin user should be able to be downgraded
createUserCmd = user.CreateUserCommand{ err = userStore.Update(context.Background(), &user.UpdateUserCommand{
Email: email, UserID: usr.ID,
Name: "user2", IsGrafanaAdmin: boolPtr(false),
Login: "user2", })
SkipOrgSetup: true, require.NoError(t, err)
}
_, err = usrSvc.Create(context.Background(), &createUserCmd)
require.Equal(t, user.ErrUserAlreadyExists, err)
// When trying to create a new user with the same login, an error is returned updated, err := userStore.GetByID(context.Background(), usr.ID)
createUserCmd = user.CreateUserCommand{ require.NoError(t, err)
Email: "user2@test.com", require.False(t, updated.IsAdmin)
Name: "user2", require.Equal(t, usr.Email, updated.Email)
Login: username, require.Equal(t, usr.Login, updated.Login)
SkipOrgSetup: true, require.Equal(t, usr.Name, updated.Name)
}
_, err = usrSvc.Create(context.Background(), &createUserCmd)
require.Equal(t, user.ErrUserAlreadyExists, err)
}) })
t.Run("GetProfile", func(t *testing.T) { t.Run("GetProfile", func(t *testing.T) {
@ -787,8 +780,16 @@ func TestIntegrationUserDataAccess(t *testing.T) {
Updated: time.Now(), Updated: time.Now(),
}) })
require.NoError(t, err) require.NoError(t, err)
err = userStore.Disable(context.Background(), &user.DisableUserCommand{UserID: id})
err = userStore.Update(context.Background(), &user.UpdateUserCommand{
UserID: id,
IsDisabled: boolPtr(true),
})
require.NoError(t, err) require.NoError(t, err)
usr, err := userStore.GetByID(context.Background(), id)
require.NoError(t, err)
require.True(t, usr.IsDisabled)
}) })
t.Run("Testing DB - multiple users", func(t *testing.T) { t.Run("Testing DB - multiple users", func(t *testing.T) {
@ -1041,3 +1042,7 @@ func createOrgAndUserSvc(t *testing.T, store db.DB, cfg *setting.Cfg) (org.Servi
return orgService, usrSvc return orgService, usrSvc
} }
func boolPtr(b bool) *bool {
return &b
}

View File

@ -9,7 +9,6 @@ import (
"github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/localcache" "github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/models/roletype"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/quota" "github.com/grafana/grafana/pkg/services/quota"
@ -319,47 +318,14 @@ func (s *Service) GetSignedInUser(ctx context.Context, query *user.GetSignedInUs
return signedInUser, err return signedInUser, err
} }
func (s *Service) NewAnonymousSignedInUser(ctx context.Context) (*user.SignedInUser, error) {
if !s.cfg.AnonymousEnabled {
return nil, fmt.Errorf("anonymous access is disabled")
}
usr := &user.SignedInUser{
IsAnonymous: true,
OrgRole: roletype.RoleType(s.cfg.AnonymousOrgRole),
}
if s.cfg.AnonymousOrgName == "" {
return usr, nil
}
getOrg := org.GetOrgByNameQuery{Name: s.cfg.AnonymousOrgName}
anonymousOrg, err := s.orgService.GetByName(ctx, &getOrg)
if err != nil {
return nil, err
}
usr.OrgID = anonymousOrg.ID
usr.OrgName = anonymousOrg.Name
return usr, nil
}
func (s *Service) Search(ctx context.Context, query *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) { func (s *Service) Search(ctx context.Context, query *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) {
return s.store.Search(ctx, query) return s.store.Search(ctx, query)
} }
func (s *Service) Disable(ctx context.Context, cmd *user.DisableUserCommand) error {
return s.store.Disable(ctx, cmd)
}
func (s *Service) BatchDisableUsers(ctx context.Context, cmd *user.BatchDisableUsersCommand) error { func (s *Service) BatchDisableUsers(ctx context.Context, cmd *user.BatchDisableUsersCommand) error {
return s.store.BatchDisableUsers(ctx, cmd) return s.store.BatchDisableUsers(ctx, cmd)
} }
func (s *Service) UpdatePermissions(ctx context.Context, userID int64, isAdmin bool) error {
return s.store.UpdatePermissions(ctx, userID, isAdmin)
}
func (s *Service) SetUserHelpFlag(ctx context.Context, cmd *user.SetUserHelpFlagCommand) error { func (s *Service) SetUserHelpFlag(ctx context.Context, cmd *user.SetUserHelpFlagCommand) error {
return s.store.SetHelpFlag(ctx, cmd) return s.store.SetHelpFlag(ctx, cmd)
} }

View File

@ -10,7 +10,6 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/localcache" "github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/models/roletype"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgtest" "github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/services/team/teamtest" "github.com/grafana/grafana/pkg/services/team/teamtest"
@ -127,41 +126,6 @@ func TestUserService(t *testing.T) {
assert.Equal(t, query2.OrgID, result2.OrgID) assert.Equal(t, query2.OrgID, result2.OrgID)
}) })
t.Run("NewAnonymousSignedInUser", func(t *testing.T) {
t.Run("should error when anonymous access is disabled", func(t *testing.T) {
userService.cfg = setting.NewCfg()
userService.cfg.AnonymousEnabled = false
_, err := userService.NewAnonymousSignedInUser(context.Background())
require.Error(t, err)
})
t.Run("should return user when anonymous access is enabled and org is not set", func(t *testing.T) {
userService.cfg = setting.NewCfg()
userService.cfg.AnonymousEnabled = true
u, err := userService.NewAnonymousSignedInUser(context.Background())
require.NoError(t, err)
require.Equal(t, true, u.IsAnonymous)
require.Equal(t, int64(0), u.UserID)
require.Equal(t, "", u.OrgName)
require.Equal(t, roletype.RoleType(""), u.OrgRole)
})
t.Run("should return user with org info when anonymous access is enabled and org is set", func(t *testing.T) {
userService.cfg = setting.NewCfg()
userService.cfg.AnonymousEnabled = true
userService.cfg.AnonymousOrgName = "anonymous"
userService.cfg.AnonymousOrgRole = "anonymous"
orgService.ExpectedOrg = &org.Org{Name: "anonymous", ID: 123}
u, err := userService.NewAnonymousSignedInUser(context.Background())
require.NoError(t, err)
require.Equal(t, true, u.IsAnonymous)
require.Equal(t, int64(0), u.UserID)
require.Equal(t, orgService.ExpectedOrg.ID, u.OrgID)
require.Equal(t, orgService.ExpectedOrg.Name, u.OrgName)
require.Equal(t, roletype.RoleType(userService.cfg.AnonymousOrgRole), u.OrgRole)
})
})
t.Run("Can set using org", func(t *testing.T) { t.Run("Can set using org", func(t *testing.T) {
cmd := user.SetUsingOrgCommand{UserID: 2, OrgID: 1} cmd := user.SetUsingOrgCommand{UserID: 2, OrgID: 1}
orgService.ExpectedUserOrgDTO = []*org.UserOrgDTO{{OrgID: 1}} orgService.ExpectedUserOrgDTO = []*org.UserOrgDTO{{OrgID: 1}}
@ -302,10 +266,6 @@ func (f *FakeUserStore) BatchDisableUsers(ctx context.Context, cmd *user.BatchDi
return f.ExpectedError return f.ExpectedError
} }
func (f *FakeUserStore) Disable(ctx context.Context, cmd *user.DisableUserCommand) error {
return f.ExpectedError
}
func (f *FakeUserStore) Search(ctx context.Context, query *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) { func (f *FakeUserStore) Search(ctx context.Context, query *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) {
return f.ExpectedSearchUserQueryResult, f.ExpectedError return f.ExpectedSearchUserQueryResult, f.ExpectedError
} }

View File

@ -19,7 +19,6 @@ type FakeUserService struct {
UpdateFn func(ctx context.Context, cmd *user.UpdateUserCommand) error UpdateFn func(ctx context.Context, cmd *user.UpdateUserCommand) error
GetSignedInUserFn func(ctx context.Context, query *user.GetSignedInUserQuery) (*user.SignedInUser, error) GetSignedInUserFn func(ctx context.Context, query *user.GetSignedInUserQuery) (*user.SignedInUser, error)
CreateFn func(ctx context.Context, cmd *user.CreateUserCommand) (*user.User, error) CreateFn func(ctx context.Context, cmd *user.CreateUserCommand) (*user.User, error)
DisableFn func(ctx context.Context, cmd *user.DisableUserCommand) error
BatchDisableUsersFn func(ctx context.Context, cmd *user.BatchDisableUsersCommand) error BatchDisableUsersFn func(ctx context.Context, cmd *user.BatchDisableUsersCommand) error
counter int counter int
@ -102,13 +101,6 @@ func (f *FakeUserService) Search(ctx context.Context, query *user.SearchUsersQue
return &f.ExpectedSearchUsers, f.ExpectedError return &f.ExpectedSearchUsers, f.ExpectedError
} }
func (f *FakeUserService) Disable(ctx context.Context, cmd *user.DisableUserCommand) error {
if f.DisableFn != nil {
return f.DisableFn(ctx, cmd)
}
return f.ExpectedError
}
func (f *FakeUserService) BatchDisableUsers(ctx context.Context, cmd *user.BatchDisableUsersCommand) error { func (f *FakeUserService) BatchDisableUsers(ctx context.Context, cmd *user.BatchDisableUsersCommand) error {
if f.BatchDisableUsersFn != nil { if f.BatchDisableUsersFn != nil {
return f.BatchDisableUsersFn(ctx, cmd) return f.BatchDisableUsersFn(ctx, cmd)
@ -116,10 +108,6 @@ func (f *FakeUserService) BatchDisableUsers(ctx context.Context, cmd *user.Batch
return f.ExpectedError return f.ExpectedError
} }
func (f *FakeUserService) UpdatePermissions(ctx context.Context, userID int64, isAdmin bool) error {
return f.ExpectedError
}
func (f *FakeUserService) SetUserHelpFlag(ctx context.Context, cmd *user.SetUserHelpFlagCommand) error { func (f *FakeUserService) SetUserHelpFlag(ctx context.Context, cmd *user.SetUserHelpFlagCommand) error {
return f.ExpectedError return f.ExpectedError
} }

View File

@ -1,4 +1,4 @@
// Code generated by mockery v2.40.1. DO NOT EDIT. // Code generated by mockery v2.42.2. DO NOT EDIT.
package usertest package usertest
@ -128,24 +128,6 @@ func (_m *MockService) Delete(_a0 context.Context, _a1 *user.DeleteUserCommand)
return r0 return r0
} }
// Disable provides a mock function with given fields: _a0, _a1
func (_m *MockService) Disable(_a0 context.Context, _a1 *user.DisableUserCommand) error {
ret := _m.Called(_a0, _a1)
if len(ret) == 0 {
panic("no return value specified for Disable")
}
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *user.DisableUserCommand) error); ok {
r0 = rf(_a0, _a1)
} else {
r0 = ret.Error(0)
}
return r0
}
// GetByEmail provides a mock function with given fields: _a0, _a1 // GetByEmail provides a mock function with given fields: _a0, _a1
func (_m *MockService) GetByEmail(_a0 context.Context, _a1 *user.GetUserByEmailQuery) (*user.User, error) { func (_m *MockService) GetByEmail(_a0 context.Context, _a1 *user.GetUserByEmailQuery) (*user.User, error) {
ret := _m.Called(_a0, _a1) ret := _m.Called(_a0, _a1)
@ -346,36 +328,6 @@ func (_m *MockService) GetUsageStats(ctx context.Context) map[string]interface{}
return r0 return r0
} }
// NewAnonymousSignedInUser provides a mock function with given fields: _a0
func (_m *MockService) NewAnonymousSignedInUser(_a0 context.Context) (*user.SignedInUser, error) {
ret := _m.Called(_a0)
if len(ret) == 0 {
panic("no return value specified for NewAnonymousSignedInUser")
}
var r0 *user.SignedInUser
var r1 error
if rf, ok := ret.Get(0).(func(context.Context) (*user.SignedInUser, error)); ok {
return rf(_a0)
}
if rf, ok := ret.Get(0).(func(context.Context) *user.SignedInUser); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*user.SignedInUser)
}
}
if rf, ok := ret.Get(1).(func(context.Context) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// Search provides a mock function with given fields: _a0, _a1 // Search provides a mock function with given fields: _a0, _a1
func (_m *MockService) Search(_a0 context.Context, _a1 *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) { func (_m *MockService) Search(_a0 context.Context, _a1 *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) {
ret := _m.Called(_a0, _a1) ret := _m.Called(_a0, _a1)
@ -478,24 +430,6 @@ func (_m *MockService) UpdateLastSeenAt(_a0 context.Context, _a1 *user.UpdateUse
return r0 return r0
} }
// UpdatePermissions provides a mock function with given fields: _a0, _a1, _a2
func (_m *MockService) UpdatePermissions(_a0 context.Context, _a1 int64, _a2 bool) error {
ret := _m.Called(_a0, _a1, _a2)
if len(ret) == 0 {
panic("no return value specified for UpdatePermissions")
}
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, int64, bool) error); ok {
r0 = rf(_a0, _a1, _a2)
} else {
r0 = ret.Error(0)
}
return r0
}
// NewMockService creates a new instance of MockService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // NewMockService creates a new instance of MockService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value. // The first argument is typically a *testing.T value.
func NewMockService(t interface { func NewMockService(t interface {