diff --git a/controller/role.go b/controller/role.go index fd13db7..e4f8deb 100644 --- a/controller/role.go +++ b/controller/role.go @@ -12,7 +12,7 @@ import ( ) type roleService interface { - All(ctx context.Context) ([]domain.Role, error) + All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error @@ -35,12 +35,13 @@ func NewRole(roleService roleService) Role { // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.RoleAllRequest true "Тело запроса" // @Success 200 {array} domain.Role // @Failure 400 {object} domain.GrpcError // @Failure 500 {object} domain.GrpcError // @Router /role/all [POST] -func (u Role) All(ctx context.Context) ([]domain.Role, error) { - users, err := u.roleService.All(ctx) +func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) { + users, err := u.roleService.All(ctx, req) if err != nil { return nil, errors.WithMessage(err, "get roles") } diff --git a/docs/swagger.json b/docs/swagger.json index 68327ff..e1543c0 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -385,6 +385,15 @@ "name": "X-AUTH-ADMIN", "in": "header", "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.RoleAllRequest" + } } ], "responses": { @@ -1564,6 +1573,10 @@ "domain.CreateRoleRequest": { "type": "object", "properties": { + "applicationGroup": { + "description": "Группа приложений", + "type": "string" + }, "changeMessage": { "description": "Причина изменений", "type": "string" @@ -1805,6 +1818,10 @@ "domain.Role": { "type": "object", "properties": { + "applicationGroup": { + "description": "Группа приложений", + "type": "string" + }, "changeMessage": { "description": "Причина изменений", "type": "string" @@ -1844,6 +1861,15 @@ } } }, + "domain.RoleAllRequest": { + "type": "object", + "properties": { + "applicationGroup": { + "description": "Фильтр по группе приложений", + "type": "string" + } + } + }, "domain.SecureAuthRequest": { "type": "object", "properties": { @@ -2049,6 +2075,10 @@ "domain.UpdateRoleRequest": { "type": "object", "properties": { + "applicationGroup": { + "description": "Группа приложений", + "type": "string" + }, "changeMessage": { "description": "Причина изменений", "type": "string" diff --git a/domain/role.go b/domain/role.go index b45a821..356064d 100644 --- a/domain/role.go +++ b/domain/role.go @@ -5,32 +5,39 @@ import ( ) type Role struct { - Id int // Идентификатор роли - Name string // Название роли - ExternalGroup string // Внешнее название группы - ChangeMessage string // Причина изменений - Permissions []string // Набор прав - Immutable bool - Exclusive bool - CreatedAt time.Time // Дата создания - UpdatedAt time.Time // Дата обновления + Id int // Идентификатор роли + Name string // Название роли + ExternalGroup string // Внешнее название группы + ApplicationGroup string // Группа приложений + ChangeMessage string // Причина изменений + Permissions []string // Набор прав + Immutable bool + Exclusive bool + CreatedAt time.Time // Дата создания + UpdatedAt time.Time // Дата обновления } type CreateRoleRequest struct { - Name string // Название роли - ExternalGroup string // Внешнее название группы - ChangeMessage string // Причина изменений - Permissions []string // Набор прав + Name string // Название роли + ExternalGroup string // Внешнее название группы + ApplicationGroup string // Группа приложений + ChangeMessage string // Причина изменений + Permissions []string // Набор прав } type UpdateRoleRequest struct { - Id int // Идентификатор роли - Name string // Название роли - ExternalGroup string // Внешнее название группы - ChangeMessage string // Причина изменений - Permissions []string // Набор прав + Id int // Идентификатор роли + Name string // Название роли + ExternalGroup string // Внешнее название группы + ApplicationGroup string // Группа приложений + ChangeMessage string // Причина изменений + Permissions []string // Набор прав } type DeleteRoleRequest struct { Id int // Идентификатор роли } + +type RoleAllRequest struct { + ApplicationGroup *string `validate:"omitnil,min=1"` // Фильтр по группе приложений +} diff --git a/entity/role.go b/entity/role.go index 894de51..a4a7ad2 100644 --- a/entity/role.go +++ b/entity/role.go @@ -13,14 +13,15 @@ const ( ) type Role struct { - Id int - Name string - ExternalGroup string - Permissions PermList - Immutable bool - Exclusive bool - CreatedAt time.Time - UpdatedAt time.Time + Id int + Name string + ExternalGroup string + ApplicationGroup string + Permissions PermList + Immutable bool + Exclusive bool + CreatedAt time.Time + UpdatedAt time.Time } type PermList []string diff --git a/migrations/20261118140525_add_role_application_group.sql b/migrations/20261118140525_add_role_application_group.sql new file mode 100644 index 0000000..85f7639 --- /dev/null +++ b/migrations/20261118140525_add_role_application_group.sql @@ -0,0 +1,5 @@ +-- +goose Up +ALTER TABLE roles ADD COLUMN application_group TEXT NOT NULL DEFAULT ''; + +-- +goose Down +ALTER TABLE roles DROP COLUMN application_group; diff --git a/repository/role.go b/repository/role.go index 2cb0f85..c15c537 100644 --- a/repository/role.go +++ b/repository/role.go @@ -25,6 +25,7 @@ const ( updatedAtRolesColumn = "updated_at" permissionsRolesColumn = "permissions" externalGroupRolesColumn = "external_group" + applicationGroupColumn = "application_group" immutableRolesColumn = "immutable" exclusiveRolesColumn = "exclusive" ) @@ -37,7 +38,7 @@ func (r Role) GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error) ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds") q, args, err := query.New(). - Select("id, name, external_group, permissions, created_at, updated_at"). + Select("id, name, external_group, application_group, permissions, created_at, updated_at"). From("roles"). Where(squirrel.Eq{"id": id}). ToSql() @@ -67,6 +68,7 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err updatedAtRolesColumn, permissionsRolesColumn, externalGroupRolesColumn, + applicationGroupColumn, immutableRolesColumn, exclusiveRolesColumn, ). @@ -101,6 +103,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e updatedAtRolesColumn, permissionsRolesColumn, externalGroupRolesColumn, + applicationGroupColumn, immutableRolesColumn, exclusiveRolesColumn, ). @@ -122,7 +125,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e func (r Role) All(ctx context.Context) ([]entity.Role, error) { ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All") - q := "select id, name, external_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at" + q := "select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at" roles := make([]entity.Role, 0) err := r.db.Select(ctx, &roles, q) if err != nil { @@ -131,12 +134,24 @@ func (r Role) All(ctx context.Context) ([]entity.Role, error) { return roles, nil } +func (r Role) AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Role.AllWithFilter") + roles := make([]entity.Role, 0) + err := r.db.Select(ctx, &roles, ` + select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at + from roles where application_group=$1 order by created_at`, applicationGroup) + if err != nil { + return nil, errors.WithMessage(err, "select all roles") + } + return roles, nil +} + func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) { ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole") q, args, err := query.New().Insert("roles"). - Columns("name", "permissions", "external_group"). - Values(role.Name, role.Permissions, role.ExternalGroup). + Columns("name", "permissions", "external_group", "application_group"). + Values(role.Name, role.Permissions, role.ExternalGroup, role.ApplicationGroup). Suffix("RETURNING *").ToSql() if err != nil { return nil, errors.WithMessage(err, "build query") @@ -158,6 +173,7 @@ func (r Role) Update(ctx context.Context, role entity.Role) (*entity.Role, error Set("name", role.Name). Set("permissions", role.Permissions). Set("external_group", role.ExternalGroup). + Set("application_group", role.ApplicationGroup). Where(squirrel.Eq{"id": role.Id}). Suffix("RETURNING *").ToSql() if err != nil { diff --git a/service/role.go b/service/role.go index 517cf60..252c3fd 100644 --- a/service/role.go +++ b/service/role.go @@ -13,6 +13,7 @@ import ( type roleRoleRepo interface { All(ctx context.Context) ([]entity.Role, error) + AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) Update(ctx context.Context, role entity.Role) (*entity.Role, error) Delete(ctx context.Context, id int) error @@ -32,8 +33,17 @@ func NewRole(roleRepo roleRoleRepo, audit auditService) Role { } } -func (u Role) All(ctx context.Context) ([]domain.Role, error) { - roles, err := u.roleRepo.All(ctx) +func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) { + var ( + roles []entity.Role + err error + ) + switch { + case req.ApplicationGroup != nil: + roles, err = u.roleRepo.AllWithFilter(ctx, *req.ApplicationGroup) + default: + roles, err = u.roleRepo.All(ctx) + } if err != nil { return nil, errors.WithMessage(err, "get all roles") } @@ -58,9 +68,10 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId } role, err = u.roleRepo.InsertRole(ctx, entity.Role{ - Name: req.Name, - ExternalGroup: req.ExternalGroup, - Permissions: req.Permissions, + Name: req.Name, + ExternalGroup: req.ExternalGroup, + ApplicationGroup: req.ApplicationGroup, + Permissions: req.Permissions, }) if err != nil { @@ -69,13 +80,15 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId slices.Sort(role.Permissions) diff := diffToString(map[string]any{ - "Название": "", - "Группа ЕСК": "", - "Разрешения": []int{}, + "Название": "", + "Группа ЕСК": "", + "Группа приложений": "", + "Разрешения": []int{}, }, map[string]any{ - "Название": role.Name, - "Группа ЕСК": role.ExternalGroup, - "Разрешения": role.Permissions, + "Название": role.Name, + "Группа ЕСК": role.ExternalGroup, + "Группа приложений": role.ApplicationGroup, + "Разрешения": role.Permissions, }) u.auditService.SaveAuditAsync(ctx, adminId, fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff), @@ -106,10 +119,11 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId oldRole := roles[0] role, err := u.roleRepo.Update(ctx, entity.Role{ - Id: req.Id, - Name: req.Name, - ExternalGroup: req.ExternalGroup, - Permissions: req.Permissions, + Id: req.Id, + Name: req.Name, + ExternalGroup: req.ExternalGroup, + ApplicationGroup: req.ApplicationGroup, + Permissions: req.Permissions, }) if err != nil { @@ -119,13 +133,15 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId slices.Sort(oldRole.Permissions) slices.Sort(role.Permissions) diff := diffToString(map[string]any{ - "Название": oldRole.Name, - "Группа ЕСК": oldRole.ExternalGroup, - "Разрешения": oldRole.Permissions, + "Название": oldRole.Name, + "Группа ЕСК": oldRole.ExternalGroup, + "Группа приложений": oldRole.ApplicationGroup, + "Разрешения": oldRole.Permissions, }, map[string]any{ - "Название": role.Name, - "Группа ЕСК": role.ExternalGroup, - "Разрешения": role.Permissions, + "Название": role.Name, + "Группа ЕСК": role.ExternalGroup, + "Группа приложений": role.ApplicationGroup, + "Разрешения": role.Permissions, }) u.auditService.SaveAuditAsync(ctx, adminId, fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff), @@ -148,13 +164,14 @@ func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId func (u Role) toDomain(role entity.Role) domain.Role { return domain.Role{ - Id: role.Id, - Name: role.Name, - ExternalGroup: role.ExternalGroup, - Permissions: role.Permissions, - Immutable: role.Immutable, - Exclusive: role.Exclusive, - CreatedAt: role.CreatedAt, - UpdatedAt: role.UpdatedAt, + Id: role.Id, + Name: role.Name, + ExternalGroup: role.ExternalGroup, + ApplicationGroup: role.ApplicationGroup, + Permissions: role.Permissions, + Immutable: role.Immutable, + Exclusive: role.Exclusive, + CreatedAt: role.CreatedAt, + UpdatedAt: role.UpdatedAt, } } diff --git a/tests/db_general_test.go b/tests/db_general_test.go index dcb5389..04005ec 100644 --- a/tests/db_general_test.go +++ b/tests/db_general_test.go @@ -42,9 +42,13 @@ func InsertRole(db *dbt.TestDb, role entity.Role) int64 { } q, args, err := query.New(). Insert("roles"). - Columns("name", "permissions"). - Values(role.Name, role.Permissions). - Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, permissions = EXCLUDED.permissions RETURNING id"). + Columns("name", "permissions", "application_group"). + Values(role.Name, role.Permissions, role.ApplicationGroup). + Suffix(`ON CONFLICT (name) DO UPDATE SET + name = EXCLUDED.name, + permissions = EXCLUDED.permissions, + application_group = EXCLUDED.application_group + RETURNING id`). ToSql() if err != nil { panic(errors.WithMessagef(err, "insert role")) diff --git a/tests/role_filter_test.go b/tests/role_filter_test.go new file mode 100644 index 0000000..5c6147a --- /dev/null +++ b/tests/role_filter_test.go @@ -0,0 +1,171 @@ +package tests_test + +import ( + "strconv" + "testing" + "time" + + "isp-admin-service/assembly" + "isp-admin-service/conf" + "isp-admin-service/domain" + "isp-admin-service/entity" + + "github.com/stretchr/testify/suite" + "github.com/txix-open/isp-kit/dbx" + "github.com/txix-open/isp-kit/errors" + "github.com/txix-open/isp-kit/grpc/client" + "github.com/txix-open/isp-kit/http/httpcli" + "github.com/txix-open/isp-kit/test" + "github.com/txix-open/isp-kit/test/dbt" + "github.com/txix-open/isp-kit/test/grpct" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestRoleTestSuite(t *testing.T) { + t.Parallel() + suite.Run(t, &RoleTestSuite{}) +} + +type RoleTestSuite struct { + suite.Suite + + test *test.Test + db *dbt.TestDb + grpcCli *client.Client + adminId int64 +} + +func (s *RoleTestSuite) SetupTest() { + testInstance, _ := test.New(s.T()) + s.test = testInstance + s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) + + remote := conf.Remote{ + ExpireSec: 0, + } + cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). + Config(s.T().Context(), remote, time.Minute) + s.Require().NoError(err) + + server, apiCli := grpct.TestServer(testInstance, cfg.Handler) + s.grpcCli = apiCli + + testInstance.T().Cleanup(func() { + server.Shutdown() + }) + + roleId := InsertRole(s.db, entity.Role{ + Name: "admin_test", + Permissions: []string{ + "role_view", + "role_add", + "role_update", + }, + }) + s.adminId = InsertUser(s.db, entity.User{ + Email: "admin@test.ru", + }) + InsertUserRole(s.db, entity.UserRole{ + UserId: int(s.adminId), + RoleId: int(roleId), + }) +} + +func (s *RoleTestSuite) TestAllRolesWithoutFilter() { + InsertRole(s.db, entity.Role{Name: "empty"}) + InsertRole(s.db, entity.Role{Name: "groupA_1", ApplicationGroup: "groupA"}) + InsertRole(s.db, entity.Role{Name: "groupA_2", ApplicationGroup: "groupA"}) + InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"}) + + roles := []domain.Role{} + s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{}, &roles)) + + groups := make(map[string]string, len(roles)) + for _, role := range roles { + groups[role.Name] = role.ApplicationGroup + } + + s.Require().Empty(groups["empty"]) + s.Require().Equal("groupA", groups["groupA_1"]) + s.Require().Equal("groupA", groups["groupA_2"]) + s.Require().Equal("groupB", groups["groupB"]) +} + +func (s *RoleTestSuite) TestAllRolesInvalidArgument() { + roles := []domain.Role{} + err := s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles) + + s.Require().Error(err) + st, ok := status.FromError(err) + s.Require().True(ok) + s.Require().Equal(codes.InvalidArgument, st.Code()) + s.Require().Empty(roles) +} + +func (s *RoleTestSuite) TestAllRolesFilterByApplicationGroup() { + InsertRole(s.db, entity.Role{Name: "groupA", ApplicationGroup: "groupA"}) + InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"}) + + roles := []domain.Role{} + s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles)) + + s.Require().Len(roles, 1) + s.Require().Equal("groupA", roles[0].ApplicationGroup) + + roles = []domain.Role{} + s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles)) + + s.Require().Empty(roles) +} + +func (s *RoleTestSuite) TestCreateRoleApplicationGroup() { + role := domain.Role{} + s.Require().NoError(s.invoke("admin/role/create", domain.CreateRoleRequest{ + Name: "role_new", + ApplicationGroup: "group", + Permissions: []string{}, + }, &role)) + + roleEmpty := domain.Role{} + s.Require().NoError(s.invoke("admin/role/create", domain.CreateRoleRequest{ + Name: "role_empty", + Permissions: []string{}, + }, &roleEmpty)) + + s.Require().Equal("role_new", role.Name) + s.Require().Equal("group", role.ApplicationGroup) + s.Require().Equal("role_empty", roleEmpty.Name) + s.Require().Empty(roleEmpty.ApplicationGroup) +} + +func (s *RoleTestSuite) TestUpdateRoleApplicationGroup() { + roleId := InsertRole(s.db, entity.Role{ + Name: "role_old", + ApplicationGroup: "group_old", + }) + + role := domain.Role{} + s.Require().NoError(s.invoke("admin/role/update", domain.UpdateRoleRequest{ + Id: int(roleId), + Name: "role_new", + ApplicationGroup: "group_new", + Permissions: []string{}, + }, &role)) + + s.Require().Equal("role_new", role.Name) + s.Require().Equal("group_new", role.ApplicationGroup) +} + +func (s *RoleTestSuite) invoke(path string, req, resp any) error { + err := s.grpcCli.Invoke(path). + JsonRequestBody(req). + JsonResponseBody(resp). + AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))). + Do(s.T().Context()) + if err != nil { + return errors.WithMessagef(err, "invoke %s", path) + } + + return nil +}