Compare commits

..
28 Commits
Author SHA1 Message Date
txix c2563cb294 2026-09-10 14:19:17: merge [main:bca4b4adaf452bdfab6997387a60cbbc7aa04a9d]; 2026-09-10 14:19:17 +03:00
txix 5cb3885330 2026-09-10 14:15:13: merge [main:14224c2de53289839839d51f5885722051e41349]; 2026-09-10 14:15:13 +03:00
txix 554123722d 2026-07-27 16:33:48: merge [main:45bc24711ece7ebd62203cf9a04ff41b355098ea];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-07-27 16:33:48 +03:00
txix a791e0f678 2026-07-07 10:21:18: merge [main:b1c4322c987c054b93e065b5fef6bac895227c71];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-07-07 10:21:18 +03:00
txix c1bb2cf4ed 2026-03-23 17:08:40: merge [main:2d7adad8000642a271d9ea575fab87f8373d2e5d];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-03-23 17:08:40 +03:00
txix 0ad3e3dead 2026-02-16 16:26:43: merge [main:5ee9d8568258a2e35dfce4aba80a607d007c2f0c];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-02-16 16:26:43 +03:00
txix aebc53174b 2026-02-13 17:10:15: merge [main:b1d5aae316b6f02c6bdd8e85b62db55e229923e1];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-02-13 17:10:15 +03:00
txix 88e5ffedad 2025-10-29 15:09:22: merge [main:2637770d8299ca2f29cca8cba4524bb3865137cd]; 2025-10-29 15:09:22 +03:00
txix 71a841fee0 2025-10-27 15:14:18: merge [main:187e1f07a0e8912d7c10f6568ea8ee6489639912];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-10-27 15:14:18 +03:00
txix 3029e084ce 2025-09-16 17:00:10: merge [main:20f3fb7b5e4ca72a712c054d9a33187b91a5ed70];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-09-16 17:00:10 +03:00
txix 14bd29e48f 2025-08-21 15:04:39: merge [main:601a690901951343a4dc145282f04732093acfac];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-08-21 15:04:39 +03:00
txix 32466576b0 2025-08-11 12:00:22: merge [main:3f65b11a657597e5ef5911d611c3372392863c7f];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-08-11 12:00:22 +03:00
txix 121f63f57a 2025-07-25 15:09:56: merge [main:fb882e5c5c84ea63967c2aa6e330dab7a9521182];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-25 15:09:56 +03:00
txix 7c9e12685d 2025-05-27 15:10:01: merge [main:40b37f8900eeca355e037028acaeb9fedd104390];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-05-27 15:10:01 +03:00
txix 2b167919b1 2025-05-13 18:09:48: merge [main:0cb61c184a6c69aa64fcace2d6bd4b925b481fa3]; 2025-05-13 18:09:48 +03:00
txix f10153a53b 2025-04-23 15:25:43: merge [main:9bf05f1e9d4984be8f59c2a7a136167d726bb36d]; 2025-04-23 15:25:43 +03:00
txix 83b10f368c 2025-04-18 12:59:04: merge [main:1746acd55926fd1a3b1110ae11dd8c9e64c1c97d]; 2025-04-18 12:59:04 +03:00
txix 8789f8a5ec 2025-04-18 12:28:20: merge [main:b16ac80053672e9bcd62341d2d76fb563f7ef310]; 2025-04-18 12:28:20 +03:00
txix 3bbe1c3952 2025-03-26 11:35:49: merge [main:635046d221d1e642ece7da4fcc3c8cb5a946ef9d]; 2025-03-26 11:35:49 +03:00
txix e1de1c31d8 2025-03-03 11:22:49: merge [main:f5a38117b1ead323fc68342b2134f5eb8c7b5beb]; 2025-03-03 11:22:49 +03:00
txix 0166d4a050 2024-12-27 18:24:10: merge [main:c966a2cca577311764b432ad43216d533a149cf7]; 2024-12-27 18:24:10 +03:00
txix 5d7c8f48c3 2024-12-11 12:38:48: merge [main:2343940930ccae4f562e8192a2f6965e08e8d2df]; 2024-12-11 12:38:48 +03:00
txix 8ec71761d3 2024-11-15 14:27:02: merge [main:2d6398224fd919eaab82510637a78384e651391e]; 2024-11-15 14:27:02 +03:00
txix f8074400a1 2024-11-15 13:39:23: merge [main:ac1457e534d62c78d515db685ff817ffd1998a06]; 2024-11-15 13:39:23 +03:00
txix daf35df301 2024-06-28 14:05:29: merge [main:4352c400b4b09ee33cd26798e0fb43fbb6ed859f]; 2024-06-28 14:05:29 +03:00
txix 1efb8fa354 2024-06-28 13:34:13: merge [main:1653289e0144e4c1405ae492b43310a8592a6959]; 2024-06-28 13:34:13 +03:00
txix 17747f5b74 2024-06-20 10:45:03: merge [main:e4755abdc84b002eec3c2871d1161ea669541291]; 2024-06-20 10:45:03 +03:00
txix ed8a4eef5d 2024-03-25 16:24:48: merge [main:72a62d1996eb71f9a1ab21643bf294148b87ae99]; 2024-03-25 16:24:48 +03:00
23 changed files with 108 additions and 140 deletions

No files matched your search

-9
View File
@@ -20,17 +20,11 @@ linters:
- wsl_v5 # расставление пробелов очень индивидуально - wsl_v5 # расставление пробелов очень индивидуально
- godoclint # ругается на // nolint, не удобно - godoclint # ругается на // nolint, не удобно
- prealloc # слишком аггресивный, в большинстве случаев не требуется - prealloc # слишком аггресивный, в большинстве случаев не требуется
- gomodguard # deprecated
settings: settings:
exhaustruct_v5:
allow-empty: true
explicit-mode: true
cyclop: cyclop:
max-complexity: 15 # по умолчанию 10 мало max-complexity: 15 # по умолчанию 10 мало
funlen: funlen:
lines: 80 lines: 80
goconst:
ignore-tests: true # тестовые фикстуры не выносим в константы
lll: lll:
line-length: 150 line-length: 150
revive: revive:
@@ -66,9 +60,6 @@ linters:
- unqueryvet - unqueryvet
- prealloc - prealloc
path: ".*_test\\.go$" path: ".*_test\\.go$"
- linters:
- goconst
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
paths: paths:
- third_party$ - third_party$
- builtin$ - builtin$
+2 -2
View File
@@ -1,6 +1,6 @@
module isp-admin-service module isp-admin-service
go 1.27 go 1.26.0
require ( require (
github.com/Masterminds/squirrel v1.5.4 github.com/Masterminds/squirrel v1.5.4
@@ -8,7 +8,7 @@ require (
github.com/iancoleman/strcase v0.3.0 github.com/iancoleman/strcase v0.3.0
github.com/stretchr/testify v1.12.1 github.com/stretchr/testify v1.12.1
github.com/txix-open/bgjob v1.6.0 github.com/txix-open/bgjob v1.6.0
github.com/txix-open/isp-kit v1.75.0 github.com/txix-open/isp-kit v1.74.1
github.com/txix-open/jsonschema v1.3.0 github.com/txix-open/jsonschema v1.3.0
golang.org/x/crypto v0.55.0 golang.org/x/crypto v0.55.0
golang.org/x/sync v0.22.0 golang.org/x/sync v0.22.0
+2 -2
View File
@@ -153,8 +153,8 @@ github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlf
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM= github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y= github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE= github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.75.0 h1:0/qJoDTyjsVkQTCsQ7FAilKo7a5Y5pDI4tfMXloHYCg= github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw=
github.com/txix-open/isp-kit v1.75.0/go.mod h1:LEBYertzXLJ3gSuxjeJTUcSGLtf28PZWDHFH9lccCHk= github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78=
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4= github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00= github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0= github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
+1 -1
View File
@@ -21,7 +21,7 @@ var version = "1.0.0"
// @host localhost:9000 // @host localhost:9000
// @BasePath /api/admin // @BasePath /api/admin
//go:generate swag init -pd -ot json //go:generate swag init -pd -ot json -eot json
func main() { func main() {
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport) boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport)
app := boot.App app := boot.App
@@ -1,44 +0,0 @@
-- +goose Up
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_PROD',
'["profile_view", "profile_change_password", "application_group_view", "application_group_add", "application_group_edit", "application_group_delete", "application_group_app_add", "application_group_app_edit", "application_group_app_delete", "application_group_token_view", "application_group_token_add", "application_group_token_delete", "app_access_view", "app_access_edit", "variable_view", "variable_add", "variable_edit", "variable_delete", "module_view", "module_delete", "module_configuration_save_unsafe", "module_configuration_set_active", "module_history_set", "module_history_delete_version", "module_configuration_edit", "module_configuration_add"]'::jsonb,
'cn=sudir_prod_int_kkd_tech_admin,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_STAGE',
'["profile_view", "profile_change_password", "application_group_view", "application_group_add", "application_group_edit", "application_group_delete", "application_group_app_add", "application_group_app_edit", "application_group_app_delete", "application_group_token_view", "application_group_token_add", "application_group_token_delete", "app_access_view", "app_access_edit", "variable_view", "variable_add", "variable_edit", "variable_delete", "module_view", "module_delete", "module_configuration_save_unsafe", "module_configuration_set_active", "module_history_set", "module_history_delete_version", "module_configuration_edit", "module_configuration_add"]'::jsonb,
'cn=sudir_stage_int_kkd_tech_admin,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_IB_PROD',
'["session_view", "user_view", "user_block", "user_create", "user_update", "user_delete", "session_revoke", "session_delete", "security_log_view", "profile_view", "profile_edit", "role_view", "role_add", "role_update", "role_delete", "role_link_user", "role_link_external_group", "supervisor_view"]'::jsonb,
'cn=sudir_prod_int_kkd_tech_admin_ib,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_IB_STAGE',
'["session_view", "user_view", "user_block", "user_create", "user_update", "user_delete", "session_revoke", "session_delete", "security_log_view", "profile_view", "profile_edit", "role_view", "role_add", "role_update", "role_delete", "role_link_user", "role_link_external_group", "supervisor_view"]'::jsonb,
'cn=sudir_stage_int_kkd_tech_admin_ib,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_READ_ONLY_PROD',
'["profile_view", "application_group_view", "application_group_token_view", "app_access_view", "module_view"]'::jsonb,
'cn=sudir_prod_int_kkd_tech_operator_ro,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_READ_ONLY_STAGE',
'["profile_view", "application_group_view", "application_group_token_view", "app_access_view", "module_view"]'::jsonb,
'cn=sudir_stage_int_kkd_tech_operator_ro,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
-- +goose Down
+4 -4
View File
@@ -38,7 +38,7 @@ func (r Audit) Insert(ctx context.Context, log entity.Audit) (int, error) {
query, args, err := query.New(). query, args, err := query.New().
Insert("audit"). Insert("audit").
Columns(userIdAuditColumn, "message", "event", createdAtAuditColumn). Columns("user_id", "message", "event", "created_at").
Values(log.UserId, log.Message, log.Event, log.CreatedAt). Values(log.UserId, log.Message, log.Event, log.CreatedAt).
Suffix("returning id"). Suffix("returning id").
ToSql() ToSql()
@@ -134,7 +134,7 @@ func reqAuditQuery(q squirrel.SelectBuilder, reqQuery *domain.AuditQuery) squirr
} }
if reqQuery.UserId != nil { if reqQuery.UserId != nil {
q = q.Where(squirrel.Eq{userIdAuditColumn: reqQuery.UserId}) q = q.Where(squirrel.Eq{"user_id": reqQuery.UserId})
} }
if reqQuery.Message != nil { if reqQuery.Message != nil {
@@ -142,8 +142,8 @@ func reqAuditQuery(q squirrel.SelectBuilder, reqQuery *domain.AuditQuery) squirr
} }
if reqQuery.CreatedAt != nil { if reqQuery.CreatedAt != nil {
q = q.Where(squirrel.GtOrEq{createdAtAuditColumn: reqQuery.CreatedAt.From}). q = q.Where(squirrel.GtOrEq{"created_at": reqQuery.CreatedAt.From}).
Where(squirrel.Lt{createdAtAuditColumn: reqQuery.CreatedAt.To}) Where(squirrel.Lt{"created_at": reqQuery.CreatedAt.To})
} }
return q return q
+6 -6
View File
@@ -205,10 +205,10 @@ func (r Token) LastAccessByUserIds(ctx context.Context, userIds []int) (map[int6
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessByUserIds") ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessByUserIds")
query, args, err := query.New(). query, args, err := query.New().
Select(userIdTokensColumn, "max(created_at) as created_at"). Select("user_id", "max(created_at) as created_at").
From("tokens"). From("tokens").
Where(squirrel.Eq{userIdTokensColumn: userIds}). Where(squirrel.Eq{"user_id": userIds}).
GroupBy(userIdTokensColumn). GroupBy("user_id").
ToSql() ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
@@ -238,7 +238,7 @@ func reqTokenQuery(q squirrel.SelectBuilder, reqQuery *domain.SessionQuery) squi
} }
if reqQuery.UserId != nil { if reqQuery.UserId != nil {
q = q.Where(squirrel.Eq{userIdTokensColumn: reqQuery.UserId}) q = q.Where(squirrel.Eq{"user_id": reqQuery.UserId})
} }
if reqQuery.Status != nil { if reqQuery.Status != nil {
@@ -246,8 +246,8 @@ func reqTokenQuery(q squirrel.SelectBuilder, reqQuery *domain.SessionQuery) squi
} }
if reqQuery.CreatedAt != nil { if reqQuery.CreatedAt != nil {
q = q.Where(squirrel.GtOrEq{createdAtTokensColumn: reqQuery.CreatedAt.From}). q = q.Where(squirrel.GtOrEq{"created_at": reqQuery.CreatedAt.From}).
Where(squirrel.Lt{createdAtTokensColumn: reqQuery.CreatedAt.To}) Where(squirrel.Lt{"created_at": reqQuery.CreatedAt.To})
} }
if reqQuery.ExpiredAt != nil { if reqQuery.ExpiredAt != nil {
+2 -2
View File
@@ -48,7 +48,7 @@ func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, e
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn). fullNameUsersColumn).
From("users"). From("users").
Where(squirrel.Eq{emailUsersColumn: email}). Where(squirrel.Eq{"email": email}).
ToSql() ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
@@ -217,7 +217,7 @@ func (u User) GetUsersByEmail(ctx context.Context, email string) ([]entity.User,
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn). fullNameUsersColumn).
From("users"). From("users").
Where(squirrel.Eq{emailUsersColumn: email}). Where(squirrel.Eq{"email": email}).
ToSql() ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
+4 -8
View File
@@ -12,10 +12,6 @@ import (
"github.com/txix-open/isp-kit/metrics/sql_metrics" "github.com/txix-open/isp-kit/metrics/sql_metrics"
) )
const (
userIdUserRolesColumn = "user_id"
)
type UserRole struct { type UserRole struct {
db db.DB db db.DB
} }
@@ -27,8 +23,8 @@ func NewUserRole(db db.DB) UserRole {
func (u UserRole) GetRolesByUserIds(ctx context.Context, identity []int) ([]entity.UserRole, error) { func (u UserRole) GetRolesByUserIds(ctx context.Context, identity []int) ([]entity.UserRole, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.GetRolesByUserIds") ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.GetRolesByUserIds")
rolesQ, args, err := query.New().Select("role_id", userIdUserRolesColumn). rolesQ, args, err := query.New().Select("role_id", "user_id").
From("user_roles").Where(squirrel.Eq{userIdUserRolesColumn: identity}).ToSql() From("user_roles").Where(squirrel.Eq{"user_id": identity}).ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
} }
@@ -71,7 +67,7 @@ func (u UserRole) UpsertUserRoleLinks(ctx context.Context, id int, roleIds []int
ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.UpsertUserRoleLinks") ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.UpsertUserRoleLinks")
deleteQ, args, err := query.New(). deleteQ, args, err := query.New().
Delete("user_roles").Where(squirrel.Eq{userIdUserRolesColumn: id}).ToSql() Delete("user_roles").Where(squirrel.Eq{"user_id": id}).ToSql()
if err != nil { if err != nil {
return errors.WithMessage(err, "build query") return errors.WithMessage(err, "build query")
} }
@@ -87,7 +83,7 @@ func (u UserRole) UpsertUserRoleLinks(ctx context.Context, id int, roleIds []int
rolesQ := query.New(). rolesQ := query.New().
Insert("user_roles"). Insert("user_roles").
Columns(userIdUserRolesColumn, "role_id") Columns("user_id", "role_id")
for _, roleId := range roleIds { for _, roleId := range roleIds {
rolesQ = rolesQ.Values(id, roleId) rolesQ = rolesQ.Values(id, roleId)
} }
+12 -18
View File
@@ -11,12 +11,6 @@ import (
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
) )
const (
roleNameLabel = "Название"
roleGroupLabel = "Группа ЕСК"
rolePermissionsLabel = "Разрешения"
)
type roleRoleRepo interface { type roleRoleRepo interface {
All(ctx context.Context) ([]entity.Role, error) All(ctx context.Context) ([]entity.Role, error)
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
@@ -75,13 +69,13 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
slices.Sort(role.Permissions) slices.Sort(role.Permissions)
diff := diffToString(map[string]any{ diff := diffToString(map[string]any{
roleNameLabel: "", "Название": "",
roleGroupLabel: "", "Группа ЕСК": "",
rolePermissionsLabel: []int{}, "Разрешения": []int{},
}, map[string]any{ }, map[string]any{
roleNameLabel: role.Name, "Название": role.Name,
roleGroupLabel: role.ExternalGroup, "Группа ЕСК": role.ExternalGroup,
rolePermissionsLabel: role.Permissions, "Разрешения": role.Permissions,
}) })
u.auditService.SaveAuditAsync(ctx, adminId, u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff), fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
@@ -125,13 +119,13 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
slices.Sort(oldRole.Permissions) slices.Sort(oldRole.Permissions)
slices.Sort(role.Permissions) slices.Sort(role.Permissions)
diff := diffToString(map[string]any{ diff := diffToString(map[string]any{
roleNameLabel: oldRole.Name, "Название": oldRole.Name,
roleGroupLabel: oldRole.ExternalGroup, "Группа ЕСК": oldRole.ExternalGroup,
rolePermissionsLabel: oldRole.Permissions, "Разрешения": oldRole.Permissions,
}, map[string]any{ }, map[string]any{
roleNameLabel: role.Name, "Название": role.Name,
roleGroupLabel: role.ExternalGroup, "Группа ЕСК": role.ExternalGroup,
rolePermissionsLabel: role.Permissions, "Разрешения": role.Permissions,
}) })
u.auditService.SaveAuditAsync(ctx, adminId, u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff), fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
+16 -23
View File
@@ -16,13 +16,6 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
const (
userFullNameLabel = "ФИО"
userDescriptionLabel = "Описание"
userEmailLabel = "Email"
userRolesLabel = "Роли (ID)"
)
type UserTransaction interface { type UserTransaction interface {
UserRepo UserRepo
UserRoleRepo UserRoleRepo
@@ -260,15 +253,15 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
slices.Sort(req.Roles) slices.Sort(req.Roles)
diff := diffToString(map[string]any{ diff := diffToString(map[string]any{
userFullNameLabel: "", "ФИО": "",
userDescriptionLabel: "", "Описание": "",
userEmailLabel: "", "Email": "",
userRolesLabel: []int{}, "Роли (ID)": []int{},
}, map[string]any{ }, map[string]any{
userFullNameLabel: usr.FullName, "ФИО": usr.FullName,
userDescriptionLabel: req.Description, "Описание": req.Description,
userEmailLabel: req.Email, "Email": req.Email,
userRolesLabel: req.Roles, "Роли (ID)": req.Roles,
}) })
u.auditService.SaveAuditAsync(ctx, adminId, u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Пользователь. Создание пользователя %d. \n %s", usr.Id, diff), fmt.Sprintf("Пользователь. Создание пользователя %d. \n %s", usr.Id, diff),
@@ -349,15 +342,15 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
slices.Sort(req.Roles) slices.Sort(req.Roles)
diff := diffToString(map[string]any{ diff := diffToString(map[string]any{
userFullNameLabel: user.FullName, "ФИО": user.FullName,
userDescriptionLabel: user.Description, "Описание": user.Description,
userEmailLabel: user.Email, "Email": user.Email,
userRolesLabel: RolesIds(oldRoles), "Роли (ID)": RolesIds(oldRoles),
}, map[string]any{ }, map[string]any{
userFullNameLabel: updatedUser.FullName, "ФИО": updatedUser.FullName,
userDescriptionLabel: req.Description, "Описание": req.Description,
userEmailLabel: req.Email, "Email": req.Email,
userRolesLabel: req.Roles, "Роли (ID)": req.Roles,
}) })
u.auditService.SaveAuditAsync(ctx, adminId, u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Пользователь. Изменение пользователя %d.\n %s", updatedUser.Id, diff), fmt.Sprintf("Пользователь. Изменение пользователя %d.\n %s", updatedUser.Id, diff),
+1 -1
View File
@@ -183,7 +183,7 @@ func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
func (s *AuditSuite) Test_All_Logs() { func (s *AuditSuite) Test_All_Logs() {
request := domain.AuditPageRequest{ request := domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 3, Limit: 3,
Offset: 5, Offset: 5,
}, },
+1 -1
View File
@@ -241,7 +241,7 @@ func (s *AuthTestSuite) Test_Logout_NotFound() {
time.Sleep(time.Second) time.Sleep(time.Second)
audit := repository.NewAudit(s.db) audit := repository.NewAudit(s.db)
auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{ auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 10, Limit: 10,
Offset: 0, Offset: 0,
}, },
+1 -1
View File
@@ -49,7 +49,7 @@ func TestInactiveWorker(t *testing.T) {
require.True(user.Blocked) require.True(user.Blocked)
list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{ list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 10, Limit: 10,
Offset: 0, Offset: 0,
}, },
+2 -2
View File
@@ -117,7 +117,7 @@ func (s *SessionSuite) Test_All_Session() {
// Дефолт сортировка, лимит и оффсет // Дефолт сортировка, лимит и оффсет
request := domain.SessionPageRequest{ request := domain.SessionPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 5, Limit: 5,
Offset: 1, Offset: 1,
}, },
@@ -208,7 +208,7 @@ func (s *SessionSuite) Test_All_Session() {
} }
request = domain.SessionPageRequest{ request = domain.SessionPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 5, Limit: 5,
Offset: 0, Offset: 0,
}, },
+4 -4
View File
@@ -186,7 +186,7 @@ func (s *UserTestSuite) TestGetUsers() {
response := domain.UsersResponse{} response := domain.UsersResponse{}
err := s.grpcCli.Invoke("admin/user/get_users"). err := s.grpcCli.Invoke("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 5, Limit: 5,
Offset: 1, Offset: 1,
}, },
@@ -214,7 +214,7 @@ func (s *UserTestSuite) TestGetUsers() {
email = "test@mail.ru" email = "test@mail.ru"
err = s.grpcCli.Invoke("admin/user/get_users"). err = s.grpcCli.Invoke("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 10, Limit: 10,
Offset: 0, Offset: 0,
}, },
@@ -298,7 +298,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
response := domain.UsersResponse{} response := domain.UsersResponse{}
err = s.grpcCli.Invoke("admin/user/get_users"). err = s.grpcCli.Invoke("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 5, Limit: 5,
Offset: 0, Offset: 0,
}, },
@@ -334,7 +334,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
response := domain.UsersResponse{} response := domain.UsersResponse{}
err := s.grpcCli.Invoke("admin/user/get_users"). err := s.grpcCli.Invoke("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize LimitOffestParams: domain.LimitOffestParams{
Limit: 10, Limit: 10,
Offset: 0, Offset: 0,
}, },
+2 -3
View File
@@ -2,7 +2,6 @@ package handler
import ( import (
"context" "context"
"slices"
"github.com/txix-open/bgjob" "github.com/txix-open/bgjob"
) )
@@ -39,8 +38,8 @@ type Sync struct {
// will be the outermost wrapper. // will be the outermost wrapper.
func NewSync(adapter SyncHandlerAdapter, middlewares ...Middleware) Sync { func NewSync(adapter SyncHandlerAdapter, middlewares ...Middleware) Sync {
s := Sync{} s := Sync{}
for _, middleware := range slices.Backward(middlewares) { for i := len(middlewares) - 1; i >= 0; i-- {
adapter = middleware(adapter) adapter = middlewares[i](adapter)
} }
s.handler = adapter s.handler = adapter
return s return s
+2 -3
View File
@@ -7,7 +7,6 @@ package client
import ( import (
"context" "context"
"slices"
"strings" "strings"
"sync/atomic" "sync/atomic"
@@ -97,8 +96,8 @@ func New(initialHosts []string, opts ...Option) (*Client, error) {
cli.grpcCli = grpcCli cli.grpcCli = grpcCli
roundTripper := cli.do roundTripper := cli.do
for _, v := range slices.Backward(cli.middlewares) { for i := len(cli.middlewares) - 1; i >= 0; i-- {
roundTripper = v(roundTripper) roundTripper = cli.middlewares[i](roundTripper)
} }
cli.roundTripper = roundTripper cli.roundTripper = roundTripper
+2 -3
View File
@@ -8,7 +8,6 @@ import (
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"slices"
"strings" "strings"
"time" "time"
@@ -290,8 +289,8 @@ func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, strin
// nolint:ireturn // nolint:ireturn
func joinMiddlewares(root RoundTripper, mws ...Middleware) RoundTripper { func joinMiddlewares(root RoundTripper, mws ...Middleware) RoundTripper {
roundTripper := root roundTripper := root
for _, mw := range slices.Backward(mws) { for i := len(mws) - 1; i >= 0; i-- {
roundTripper = mw(roundTripper) roundTripper = mws[i](roundTripper)
} }
return roundTripper return roundTripper
} }
+1 -1
View File
@@ -27,7 +27,7 @@ func LogLevelForError(err error) log.Level {
// It uses LogLevelForError to determine the log level and returns the corresponding Logger method. // It uses LogLevelForError to determine the log level and returns the corresponding Logger method.
func LogLevelFuncForError(err error, logger log.Logger) func(ctx context.Context, message any, fields ...log.Field) { func LogLevelFuncForError(err error, logger log.Logger) func(ctx context.Context, message any, fields ...log.Field) {
logLevel := LogLevelForError(err) logLevel := LogLevelForError(err)
switch logLevel { //nolint:exhaustive switch logLevel {
case log.ErrorLevel: case log.ErrorLevel:
return logger.Error return logger.Error
case log.WarnLevel: case log.WarnLevel:
+5
View File
@@ -8,9 +8,14 @@
Проверяет, что удалённая конфигурация соответствует сгенерированной JSON-схеме и проходит валидацию. Проверяет, что удалённая конфигурация соответствует сгенерированной JSON-схеме и проходит валидацию.
* Проверяет отсутствие устаревшего тега `valid`
* Проверяет соответствие структуры JSON-схеме * Проверяет соответствие структуры JSON-схеме
* Выполняет валидацию значений с помощью `validator.Default` * Выполняет валидацию значений с помощью `validator.Default`
### `FindTag[T any](v T, tag string) bool`
Рекурсивно проверяет, содержит ли структура тег с указанным именем.
## Usage ## Usage
### Example usage in test ### Example usage in test
+36
View File
@@ -5,6 +5,7 @@ package rct
import ( import (
"os" "os"
"reflect"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@@ -20,6 +21,7 @@ import (
// validator tag validation. // validator tag validation.
// //
// The function checks: // The function checks:
// - No deprecated 'valid' tags are present
// - The default configuration file is valid against the generated schema // - The default configuration file is valid against the generated schema
// - The configuration can be unmarshaled from the file // - The configuration can be unmarshaled from the file
// - The configuration passes validation // - The configuration passes validation
@@ -28,6 +30,9 @@ import (
func Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T) { func Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T) {
require := require.New(t) require := require.New(t)
validatorTag := "valid"
require.Falsef(FindTag(remoteConfig, validatorTag), "'%s' tag is not longer supported, you must use https://github.com/go-playground/validator", validatorTag)
defaultRemoteConfig, err := os.ReadFile(defaultRemoteConfigPath) defaultRemoteConfig, err := os.ReadFile(defaultRemoteConfigPath)
require.NoError(err) require.NoError(err)
@@ -53,3 +58,34 @@ func Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T) {
err = validator.Default.ValidateToError(remoteConfig) err = validator.Default.ValidateToError(remoteConfig)
require.NoError(err) require.NoError(err)
} }
// FindTag recursively searches a type for the specified struct tag.
// It traverses structs, maps, arrays, and slices to find any field
// that has the given tag. Returns true if the tag is found.
func FindTag[T any](v T, tag string) bool {
t := reflect.TypeOf(v)
if t == nil {
return false
}
queue := []reflect.Type{t}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
if cur.Kind() == reflect.Ptr {
cur = cur.Elem()
}
// nolint:exhaustive
switch cur.Kind() {
case reflect.Struct:
for field := range cur.Fields() {
if field.Tag.Get(tag) != "" {
return true
}
queue = append(queue, field.Type)
}
case reflect.Map, reflect.Array, reflect.Slice:
queue = append(queue, cur.Elem())
}
}
return false
}
+2 -2
View File
@@ -213,8 +213,8 @@ github.com/txix-open/etp/v4/bpool
github.com/txix-open/etp/v4/internal github.com/txix-open/etp/v4/internal
github.com/txix-open/etp/v4/msg github.com/txix-open/etp/v4/msg
github.com/txix-open/etp/v4/store github.com/txix-open/etp/v4/store
# github.com/txix-open/isp-kit v1.75.0 # github.com/txix-open/isp-kit v1.74.1
## explicit; go 1.27 ## explicit; go 1.26.0
github.com/txix-open/isp-kit/app github.com/txix-open/isp-kit/app
github.com/txix-open/isp-kit/bgjobx github.com/txix-open/isp-kit/bgjobx
github.com/txix-open/isp-kit/bgjobx/handler github.com/txix-open/isp-kit/bgjobx/handler