MSP-8976 Add application_group field and filter

This commit is contained in:
Иван Перлов committed 2026-11-20 15:18:00 +03:00
1 parent 67e9b563b4
commit df0f769aa8
9 files changed
+325 -65

No files matched your search

+4 -3
View File
@@ -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")
}
+30
View File
@@ -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"
+25 -18
View File
@@ -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 // Фильтр по группе приложений
}
+9 -8
View File
@@ -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
@@ -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;
+39 -4
View File
@@ -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,43 @@ 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")
q := query.New().
Select(
idRolesColumn,
nameRolesColumn,
externalGroupRolesColumn,
applicationGroupColumn,
permissionsRolesColumn,
immutableRolesColumn,
exclusiveRolesColumn,
createdAtRolesColumn,
updatedAtRolesColumn,
).
From("roles").
Where(squirrel.Eq{applicationGroupColumn: applicationGroup}).
OrderBy(createdAtRolesColumn)
query, args, err := q.ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
roles := make([]entity.Role, 0)
err = r.db.Select(ctx, &roles, query, args...)
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 +192,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 {
+46 -29
View File
@@ -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,
}
}
+7 -3
View File
@@ -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"))
+160
View File
@@ -0,0 +1,160 @@
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"
)
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) TestAllRolesFilterByApplicationGroup() {
InsertRole(s.db, entity.Role{Name: "groupA", ApplicationGroup: "groupA"})
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
groupA := "groupA"
roles := []domain.Role{}
s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: &groupA}, &roles))
s.Require().Len(roles, 1)
s.Require().Equal("groupA", roles[0].ApplicationGroup)
groupC := "groupC"
roles = []domain.Role{}
s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: &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
}