user_hierarchy_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //go:build unit
  2. package service
  3. import (
  4. "context"
  5. "github.com/stretchr/testify/require"
  6. "testing"
  7. )
  8. func TestUserHierarchyRoleChangesRequireLiveSuperAdmin(t *testing.T) {
  9. for _, tt := range []struct {
  10. actor string
  11. active bool
  12. wantErr bool
  13. }{
  14. {RoleUser, true, true}, {RoleAdmin, true, true}, {RoleSuperAdmin, false, true}, {RoleSuperAdmin, true, false},
  15. } {
  16. t.Run(tt.actor+map[bool]string{true: "_active", false: "_disabled"}[tt.active], func(t *testing.T) {
  17. status := StatusDisabled
  18. if tt.active {
  19. status = StatusActive
  20. }
  21. repo := &userRepoStub{usersByID: map[int64]*User{1: {ID: 1, Role: tt.actor, Status: status}, 2: {ID: 2, Role: RoleUser, Status: StatusActive}}}
  22. svc := &adminServiceImpl{userRepo: repo}
  23. _, err := svc.UpdateUser(context.Background(), 2, &UpdateUserInput{ActorAdminID: 1, Role: RoleSuperAdmin})
  24. if tt.wantErr {
  25. require.Error(t, err)
  26. require.Empty(t, repo.updated)
  27. } else {
  28. require.NoError(t, err)
  29. require.Equal(t, RoleSuperAdmin, repo.updated[0].Role)
  30. }
  31. })
  32. }
  33. }
  34. func TestUserHierarchyAdminCannotEditSuperAdminOrSelfPromote(t *testing.T) {
  35. for _, target := range []int64{1, 2} {
  36. repo := &userRepoStub{usersByID: map[int64]*User{1: {ID: 1, Role: RoleAdmin, Status: StatusActive}, 2: {ID: 2, Role: RoleSuperAdmin, Status: StatusActive}}}
  37. svc := &adminServiceImpl{userRepo: repo}
  38. _, err := svc.UpdateUser(context.Background(), target, &UpdateUserInput{ActorAdminID: 1, Role: RoleSuperAdmin, Password: "changed-password"})
  39. require.Error(t, err)
  40. require.Empty(t, repo.updated)
  41. }
  42. }
  43. func TestUserHierarchyCreationCannotGrantAdminWithoutSuperAdmin(t *testing.T) {
  44. repo := &userRepoStub{usersByID: map[int64]*User{1: {ID: 1, Role: RoleAdmin, Status: StatusActive}}}
  45. svc := &adminServiceImpl{userRepo: repo}
  46. for _, role := range []string{RoleAdmin, RoleSuperAdmin} {
  47. _, err := svc.CreateUser(context.Background(), &CreateUserInput{ActorAdminID: 1, Role: role, Email: "created@example.invalid", Password: "test-password"})
  48. require.Error(t, err)
  49. require.Empty(t, repo.created)
  50. }
  51. _, err := svc.CreateUser(context.Background(), &CreateUserInput{ActorAdminID: 1, Role: RoleUser, Email: "created@example.invalid", Password: "test-password"})
  52. require.NoError(t, err)
  53. }