MSP-2370 implement admin/secure/authorize

This commit is contained in:
d1slike committed 2023-11-14 17:04:42 +03:00
1 parent db7a668875
commit 3b3fc9dcfb
20 files changed
+509 -177

No files matched your search

+1 -1
View File
@@ -1 +1 @@
6.0.0
6.1.0
+4
View File
@@ -1,3 +1,7 @@
### v6.1.0
* обогащена информация аудита дельтой изменений
* добавлен метод `admin/secure/authorize`
* добавлена защита методов через `cluster.RequireAdminPermission`
### v6.0.0
* добавлена интеграция с внешним LDAP
* механизм автоматических блокировок неактивных УЗ изымает роли
+4 -1
View File
@@ -18,6 +18,7 @@ import (
"msp-admin-service/service/delete_old_audit_worker"
"msp-admin-service/service/inactive_worker"
"msp-admin-service/service/ldap"
"msp-admin-service/service/secure"
"msp-admin-service/transaction"
)
@@ -62,6 +63,7 @@ func (l Locator) Config(ctx context.Context, ldapRepoSupplier ldap.RepoSupplier,
auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings)
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo)
secureService := secure.NewService(tokenRepo, userRoleRepo)
txManager := transaction.NewManager(l.db)
@@ -75,6 +77,7 @@ func (l Locator) Config(ctx context.Context, ldapRepoSupplier ldap.RepoSupplier,
auditService,
txManager,
ldapService,
cfg.IdleTimeoutMs,
l.logger,
)
authService := service.NewAuth(
@@ -89,7 +92,7 @@ func (l Locator) Config(ctx context.Context, ldapRepoSupplier ldap.RepoSupplier,
userController := controller.NewUser(userService)
customizationController := controller.NewCustomization(cfg.UiDesign)
authController := controller.NewAuth(authService, l.logger)
secureController := controller.NewSecure(tokenService)
secureController := controller.NewSecure(secureService)
sessionController := controller.NewSession(tokenService)
auditController := controller.NewAudit(auditService)
roleController := controller.NewRole(roleService)
+59
View File
@@ -27,6 +27,64 @@
"expireSyncPeriodInMin": 1440
}
},
"permissions": [
{
"key": "user_view",
"name": "Просмотр списка пользователей"
},
{
"key": "user_block",
"name": "Блокировка пользователя"
},
{
"key": "user_create",
"name": "Создать пользователя"
},
{
"key": "user_update",
"name": "Обновить пользователя"
},
{
"key": "user_delete",
"name": "Удаление пользователя"
},
{
"key": "session_view",
"name": "Просмотр списка пользовательских сессий"
},
{
"key": "session_revoke",
"name": "Отзыв сессии"
},
{
"key": "session_delete",
"name": "Удаление пользовательских сессий"
},
{
"key": "role_view",
"name": "Просмотр экрана ролей"
},
{
"key": "role_add",
"name": "Создание роли"
},
{
"key": "role_update",
"name": "Обновление роли"
},
{
"key": "role_delete",
"name": "Удаление роли"
},
{
"key": "security_log_view",
"name": "Просмотр журналов ИБ"
},
{
"key": "audit_management_view",
"name": "Упраление событиями аудита"
}
],
"database": {
"host": "{{ msp_pgsql_address }}",
"port": 5432,
@@ -41,6 +99,7 @@
"delayLoginRequestInSec": 3
},
"expireSec": 3600,
"idleTimeoutMs": 0,
"blockInactiveWorker": {
"daysThreshold": 90,
"runIntervalInMinutes": 60
+6 -4
View File
@@ -18,10 +18,12 @@ func init() { //
}
type Remote struct {
Audit Audit
Database dbx.Config
ExpireSec int `valid:"required" schema:"Время жизни токена в секундах,in seconds"`
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
Audit Audit
Database dbx.Config
ExpireSec int `valid:"required" schema:"Время жизни токена в секундах,in seconds"`
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
//nolint:lll
IdleTimeoutMs int `schema:"Время бездействия пользователя,в милисекундах, после указанного времени пользователь будет разлогирован из интерфейса в браузере, по умолчанию отключено"`
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
+24 -3
View File
@@ -3,12 +3,14 @@ package controller
import (
"context"
"github.com/integration-system/isp-kit/grpc/apierrors"
"github.com/pkg/errors"
"msp-admin-service/domain"
)
type SecureService interface {
GetUserId(ctx context.Context, token string) (int64, error)
Authenticate(ctx context.Context, token string) (int64, error)
Authorize(ctx context.Context, adminId int, permission string) (bool, error)
}
type Secure struct {
@@ -27,13 +29,12 @@ func NewSecure(service SecureService) Secure {
// @Description Проверяет токен и возвращает идентификатор администратора
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.SecureAuthRequest true "Тело запроса"
// @Success 200 {object} domain.SecureAuthResponse
// @Failure 500 {object} domain.GrpcError
// @Router /secure/authenticate [POST]
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
adminId, err := s.service.GetUserId(ctx, req.Token)
adminId, err := s.service.Authenticate(ctx, req.Token)
switch {
case errors.Is(err, domain.ErrTokenExpired):
return &domain.SecureAuthResponse{
@@ -57,3 +58,23 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
}, nil
}
}
// Authorize
// @Tags secure
// @Summary Метод авторизации для администратора
// @Description Проверяет наличие у администратора необходимого разрешения
// @Accept json
// @Produce json
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
// @Success 200 {object} domain.SecureAuthzResponse
// @Failure 500 {object} domain.GrpcError
// @Router /secure/authorize [POST]
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return &domain.SecureAuthzResponse{
Authorized: ok,
}, nil
}
+9
View File
@@ -9,3 +9,12 @@ type SecureAuthResponse struct {
ErrorReason string
AdminId int64
}
type SecureAuthzRequest struct {
AdminId int
Permission string
}
type SecureAuthzResponse struct {
Authorized bool
}
+7 -6
View File
@@ -29,12 +29,13 @@ type UsersRequest struct {
}
type AdminUserShort struct {
FirstName string
LastName string
Email string `valid:"required"`
Role string
Roles []int
Permissions []string
FirstName string
LastName string
Email string `valid:"required"`
Role string
Roles []int
Permissions []string
IdleTimeoutMs int
}
type CreateUserRequest struct {
+1 -1
View File
@@ -7,7 +7,7 @@ require (
github.com/go-ldap/ldap/v3 v3.4.6
github.com/google/uuid v1.3.1
github.com/integration-system/bgjob v1.3.0
github.com/integration-system/isp-kit v1.24.2
github.com/integration-system/isp-kit v1.24.3
github.com/integration-system/jsonschema v1.0.1
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.8.4
+2 -2
View File
@@ -70,8 +70,8 @@ github.com/integration-system/grmq v1.4.2 h1:BFO9ahqnb3SpMCt5zxaRAh1iiILkC8tqmNc
github.com/integration-system/grmq v1.4.2/go.mod h1:DeE6Ceo/A+MuvzdPkuZzqajy0VJhOyH7rRxksQqhEYk=
github.com/integration-system/isp-etp-go/v2 v2.1.3 h1:vcHP/PE7p1G3rxqoVKrKtXzoSxFA4ryxigd+zPkAb3w=
github.com/integration-system/isp-etp-go/v2 v2.1.3/go.mod h1:ZpB+FIH3hy7md+f8ylVSQx5zwZVjczhkc45f1B2z9nw=
github.com/integration-system/isp-kit v1.24.2 h1:ejjSv+CFlPUGV80lxAAleLSa6T/LRoto7evRjSSUF7c=
github.com/integration-system/isp-kit v1.24.2/go.mod h1:LvqQyw8PCuuo9O8jgvhKBlOP4UEIYRxb9cHWHuYddcQ=
github.com/integration-system/isp-kit v1.24.3 h1:kBy5jtzhQvtju5kAyjm+ABtt5usWwUkMe+4ewtsZufA=
github.com/integration-system/isp-kit v1.24.3/go.mod h1:LvqQyw8PCuuo9O8jgvhKBlOP4UEIYRxb9cHWHuYddcQ=
github.com/integration-system/jsonschema v1.0.1 h1:nR78BEDG9djX2uXQ1YP66a/9yQOMmp2HFmw8VPUdAa8=
github.com/integration-system/jsonschema v1.0.1/go.mod h1:EoqDH7RmC8Epg5EgjboIxDo7Udv3WX2exGqtIVB4hI0=
github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8=
@@ -0,0 +1,27 @@
-- +goose Up
update roles
set permissions = '[
"user_create",
"user_update",
"user_delete",
"user_block",
"role_view",
"role_add",
"role_update",
"role_delete",
"session_view",
"session_revoke",
"security_log_view",
"audit_management_view"
]'
where name = 'admin';
update roles
set permissions = '[
"role_view",
"session_view",
"security_log_view"
]'
where name = 'read_only_admin';
-- +goose Down
+24
View File
@@ -38,6 +38,30 @@ func (u UserRole) GetRolesByUserIds(ctx context.Context, identity []int) ([]enti
}
}
func (u UserRole) GetRoleEntitiesByUserId(ctx context.Context, userId int) ([]entity.Role, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.GetRoleEntitiesByUserId")
query, args, err := query.New().
Select("r.*").
From("user_roles ur").
Join("roles r on ur.role_id = r.id").
Where(squirrel.Eq{
"ur.user_id": userId,
}).OrderBy("r.id").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Role, 0)
err = u.db.Select(ctx, &result, query, args...)
if err != nil {
return nil, errors.WithMessagef(err, "db select: %s", query)
}
return result, nil
}
func (u UserRole) UpsertUserRoleLinks(ctx context.Context, id int, roleIds []int) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.UpsertUserRoleLinks")
+85 -88
View File
@@ -35,136 +35,133 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "admin/auth/login",
Inner: false,
UserAuthRequired: false,
Handler: c.Auth.Login,
Path: "admin/auth/login",
Inner: false,
Handler: c.Auth.Login,
},
{
Path: "admin/auth/login_with_sudir",
Inner: false,
UserAuthRequired: false,
Handler: c.Auth.LoginWithSudir,
Path: "admin/auth/login_with_sudir",
Inner: false,
Handler: c.Auth.LoginWithSudir,
},
{
Path: "admin/auth/logout",
Inner: true,
UserAuthRequired: false,
Handler: c.Auth.Logout,
Path: "admin/auth/logout",
Inner: true,
Handler: c.Auth.Logout,
},
{
Path: "admin/user/get_profile",
Inner: true,
UserAuthRequired: false,
Handler: c.User.GetProfile,
Path: "admin/user/get_profile",
Inner: true,
Handler: c.User.GetProfile,
},
{
Path: "admin/user/get_design",
Inner: true,
UserAuthRequired: false,
Handler: c.Customization.GetUIDesign,
Path: "admin/user/get_design",
Inner: true,
Handler: c.Customization.GetUIDesign,
},
{
Path: "admin/user/get_users",
Inner: true,
UserAuthRequired: false,
Handler: c.User.GetUsers,
Path: "admin/user/get_users",
Inner: true,
Handler: c.User.GetUsers,
},
{
Path: "admin/user/create_user",
Inner: true,
UserAuthRequired: false,
Handler: c.User.CreateUser,
Path: "admin/user/create_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_create"),
Handler: c.User.CreateUser,
},
{
Path: "admin/user/update_user",
Inner: true,
UserAuthRequired: false,
Handler: c.User.UpdateUser,
Path: "admin/user/update_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_update"),
Handler: c.User.UpdateUser,
},
{
Path: "admin/user/delete_user",
Inner: true,
UserAuthRequired: false,
Handler: c.User.DeleteUser,
Path: "admin/user/delete_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_delete"),
Handler: c.User.DeleteUser,
},
{
Path: "admin/user/block_user",
Inner: true,
UserAuthRequired: false,
Handler: c.User.Block,
Path: "admin/user/block_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_block"),
Handler: c.User.Block,
},
{
Path: "admin/user/get_by_id",
Inner: true,
UserAuthRequired: false,
Handler: c.User.GetById,
Path: "admin/user/get_by_id",
Inner: true,
Handler: c.User.GetById,
},
{
Path: "admin/role/all",
Inner: true,
UserAuthRequired: false,
Handler: c.Role.All,
Path: "admin/role/all",
Inner: true,
Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Role.All,
},
{
Path: "admin/user/get_permissions",
Inner: true,
UserAuthRequired: false,
Handler: c.Permissions.GetPermissions,
Path: "admin/user/get_permissions",
Inner: true,
Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Permissions.GetPermissions,
},
{
Path: "admin/role/create",
Inner: true,
UserAuthRequired: false,
Handler: c.Role.CreateRole,
Path: "admin/role/create",
Inner: true,
Extra: cluster.RequireAdminPermission("role_add"),
Handler: c.Role.CreateRole,
},
{
Path: "admin/role/update",
Inner: true,
UserAuthRequired: false,
Handler: c.Role.UpdateRole,
Path: "admin/role/update",
Inner: true,
Extra: cluster.RequireAdminPermission("role_update"),
Handler: c.Role.UpdateRole,
},
{
Path: "admin/role/delete",
Inner: true,
UserAuthRequired: false,
Handler: c.Role.DeleteRole,
Path: "admin/role/delete",
Inner: true,
Extra: cluster.RequireAdminPermission("role_delete"),
Handler: c.Role.DeleteRole,
},
{
Path: "admin/session/all",
Inner: true,
UserAuthRequired: false,
Handler: c.Session.All,
Path: "admin/session/all",
Inner: true,
Extra: cluster.RequireAdminPermission("session_view"),
Handler: c.Session.All,
},
{
Path: "admin/session/revoke",
Inner: true,
UserAuthRequired: false,
Handler: c.Session.Revoke,
Path: "admin/session/revoke",
Inner: true,
Extra: cluster.RequireAdminPermission("session_revoke"),
Handler: c.Session.Revoke,
},
{
Path: "admin/log/all",
Inner: true,
UserAuthRequired: false,
Handler: c.Audit.All,
Path: "admin/log/all",
Inner: true,
Extra: cluster.RequireAdminPermission("security_log_view"),
Handler: c.Audit.All,
},
{
Path: "admin/log/events",
Inner: true,
UserAuthRequired: false,
Handler: c.Audit.Events,
Path: "admin/log/events",
Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.Events,
},
{
Path: "admin/log/set_events",
Inner: true,
UserAuthRequired: false,
Handler: c.Audit.SetEvents,
Path: "admin/log/set_events",
Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.SetEvents,
},
{
Path: "admin/secure/authenticate",
Inner: true,
UserAuthRequired: false,
Handler: c.Secure.Authenticate,
Path: "admin/secure/authenticate",
Inner: true,
Handler: c.Secure.Authenticate,
},
{
Path: "admin/secure/authorize",
Inner: true,
Handler: c.Secure.Authorize,
},
}
}
+25 -2
View File
@@ -3,6 +3,7 @@ package service
import (
"context"
"fmt"
"slices"
"github.com/pkg/errors"
"msp-admin-service/domain"
@@ -65,8 +66,18 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
return nil, errors.WithMessage(err, "create role")
}
slices.Sort(role.Permissions)
diff := diffToString(map[string]any{
"Название": "",
"Группа ЕСК": "",
"Разрешения": []int{},
}, map[string]any{
"Название": role.Name,
"Группа ЕСК": role.ExternalGroup,
"Разрешения": role.Permissions,
})
u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s", req.Name, req.ChangeMessage),
fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
entity.EventRoleChanged,
)
@@ -92,6 +103,7 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
case roleByName != nil && roleByName.Id != roles[0].Id:
return nil, domain.ErrAlreadyExists
}
oldRole := roles[0]
role, err := u.roleRepo.Update(ctx, entity.Role{
Id: req.Id,
@@ -104,8 +116,19 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
return nil, errors.WithMessage(err, "update role")
}
slices.Sort(oldRole.Permissions)
slices.Sort(role.Permissions)
diff := diffToString(map[string]any{
"Название": oldRole.Name,
"Группа ЕСК": oldRole.ExternalGroup,
"Разрешения": oldRole.Permissions,
}, map[string]any{
"Название": role.Name,
"Группа ЕСК": role.ExternalGroup,
"Разрешения": role.Permissions,
})
u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Роль. Изменение роли %s. Причина: %s", req.Name, req.ChangeMessage),
fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
entity.EventRoleChanged,
)
result := u.toDomain(*role)
+61
View File
@@ -0,0 +1,61 @@
package secure
import (
"context"
"slices"
"time"
"github.com/pkg/errors"
"msp-admin-service/domain"
"msp-admin-service/entity"
)
type TokenRep interface {
Get(ctx context.Context, token string) (*entity.Token, error)
}
type UserRoleRepo interface {
GetRoleEntitiesByUserId(ctx context.Context, userId int) ([]entity.Role, error)
}
type Service struct {
tokenRep TokenRep
userRoleRepo UserRoleRepo
}
func NewService(tokenRep TokenRep, userRoleRepo UserRoleRepo) Service {
return Service{
tokenRep: tokenRep,
userRoleRepo: userRoleRepo,
}
}
func (s Service) Authenticate(ctx context.Context, token string) (int64, error) {
tokenInfo, err := s.tokenRep.Get(ctx, token)
if err != nil {
return 0, errors.WithMessage(err, "get token entity")
}
if time.Now().UTC().After(tokenInfo.ExpiredAt) ||
tokenInfo.Status != entity.TokenStatusAllowed {
return 0, domain.ErrTokenExpired
}
return tokenInfo.UserId, nil
}
func (s Service) Authorize(ctx context.Context, adminId int, permission string) (bool, error) {
roles, err := s.userRoleRepo.GetRoleEntitiesByUserId(ctx, adminId)
if err != nil {
return false, errors.WithMessage(err, "get role entities by user id")
}
for _, role := range roles {
exist := slices.Contains(role.Permissions, permission)
if exist {
return true, nil
}
}
return false, nil
}
-14
View File
@@ -63,20 +63,6 @@ func (s Token) GenerateToken(ctx context.Context, repo TokenSaver, id int64) (st
return random, expiredAt.String(), nil
}
func (s Token) GetUserId(ctx context.Context, token string) (int64, error) {
tokenInfo, err := s.tokenRep.Get(ctx, token)
if err != nil {
return 0, errors.WithMessage(err, "get token entity")
}
if time.Now().UTC().After(tokenInfo.ExpiredAt) ||
tokenInfo.Status != entity.TokenStatusAllowed {
return 0, domain.ErrTokenExpired
}
return tokenInfo.UserId, nil
}
func (s Token) RevokeAllByUserId(ctx context.Context, userId int64) error {
updatedAt := time.Now().UTC()
err := s.tokenRep.RevokeByUserId(ctx, userId, updatedAt)
+88 -28
View File
@@ -3,6 +3,9 @@ package service
import (
"context"
"fmt"
"reflect"
"slices"
"strings"
"time"
"github.com/integration-system/isp-kit/log"
@@ -51,14 +54,15 @@ type LdapService interface {
}
type User struct {
userRepo UserRepo
userRoleRepo UserRoleRepo
roleRepoUser roleRepoUser
tokenRepo TokenRepo
auditService auditService
txRunner UserTransactionRunner
ldapService LdapService
logger log.Logger
userRepo UserRepo
userRoleRepo UserRoleRepo
roleRepoUser roleRepoUser
tokenRepo TokenRepo
auditService auditService
txRunner UserTransactionRunner
ldapService LdapService
idleTimeoutMs int
logger log.Logger
}
func NewUser(
@@ -69,17 +73,19 @@ func NewUser(
service auditService,
txRunner UserTransactionRunner,
ldapService LdapService,
idleTimeoutMs int,
logger log.Logger,
) User {
return User{
userRepo: userRepo,
userRoleRepo: userRoleRepo,
roleRepoUser: roleRepoUser,
tokenRepo: tokenRepo,
auditService: service,
txRunner: txRunner,
ldapService: ldapService,
logger: logger,
userRepo: userRepo,
userRoleRepo: userRoleRepo,
roleRepoUser: roleRepoUser,
tokenRepo: tokenRepo,
auditService: service,
txRunner: txRunner,
ldapService: ldapService,
idleTimeoutMs: idleTimeoutMs,
logger: logger,
}
}
@@ -107,12 +113,13 @@ func (u User) GetProfileById(ctx context.Context, userId int64) (*domain.AdminUs
}
return &domain.AdminUserShort{
FirstName: user.FirstName,
LastName: user.LastName,
Email: user.Email,
Role: roleList[0].Name,
Roles: roleIds,
Permissions: mergePermissions(roleList),
FirstName: user.FirstName,
LastName: user.LastName,
Email: user.Email,
Role: roleList[0].Name,
Roles: roleIds,
IdleTimeoutMs: u.idleTimeoutMs,
Permissions: mergePermissions(roleList),
}, nil
}
@@ -202,8 +209,22 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
u.ldapService.SyncGroupsAsync(ctx, usr)
slices.Sort(req.Roles)
diff := diffToString(map[string]any{
"Имя": "",
"Фамилия": "",
"Описание": "",
"Email": "",
"Роли (ID)": []int{},
}, map[string]any{
"Имя": req.FirstName,
"Фамилия": req.LastName,
"Описание": req.Description,
"Email": req.Email,
"Роли (ID)": req.Roles,
})
u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Пользователь. Создание пользователя %s.", usr.Email),
fmt.Sprintf("Пользователь. Создание пользователя %d. \n %s", usr.Id, diff),
entity.EventUserChanged,
)
@@ -216,8 +237,11 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
user *entity.User
lastSessionCreatedAt *time.Time
)
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
oldRoles, err := u.userRoleRepo.GetRolesByUserIds(ctx, []int{int(req.Id)})
if err != nil {
return nil, errors.WithMessage(err, "get user roles")
}
err = u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
_, err := tx.GetUserById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrNotFound):
@@ -266,8 +290,22 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
u.ldapService.SyncGroupsAsync(ctx, *user)
slices.Sort(req.Roles)
diff := diffToString(map[string]any{
"Имя": user.FirstName,
"Фамилия": user.LastName,
"Описание": user.Description,
"Email": user.Email,
"Роли (ID)": RolesIds(oldRoles),
}, map[string]any{
"Имя": req.FirstName,
"Фамилия": req.LastName,
"Описание": req.Description,
"Email": req.Email,
"Роли (ID)": req.Roles,
})
u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Пользователь. Изменение пользователя %s.", user.Email),
fmt.Sprintf("Пользователь. Изменение пользователя %d.\n %s", user.Id, diff),
entity.EventUserChanged,
)
@@ -286,7 +324,7 @@ func (u User) DeleteUsers(ctx context.Context, ids []int64, adminId int64) (int,
}
u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Пользователь. Удаление пользователей %d.", ids),
fmt.Sprintf("Пользователь. Удаление пользователей %v.", ids),
entity.EventUserChanged,
)
@@ -378,7 +416,7 @@ func RolesIds(roles []entity.UserRole) []int {
for _, role := range roles {
roleList = append(roleList, role.RoleId)
}
slices.Sort(roleList)
return roleList
}
@@ -397,3 +435,25 @@ func mergePermissions(roles []entity.Role) []string {
return permList
}
func diffToString(a map[string]any, b map[string]any) string {
builder := strings.Builder{}
for key, aValue := range a {
bValue := b[key]
if reflect.DeepEqual(aValue, bValue) {
continue
}
if reflect.ValueOf(bValue).IsZero() {
builder.WriteString(fmt.Sprintf("%s: %v -> null\n", key, aValue))
continue
}
builder.WriteString(fmt.Sprintf("%s: %v -> %v\n", key, aValue, bValue))
}
if builder.Len() == 0 {
return "Нет изменений"
}
result := builder.String()
return result[:len(result)-1]
}
+14 -12
View File
@@ -21,7 +21,7 @@ func InsertUser(db *dbt.TestDb, user entity.User) int64 {
return id
}
func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) (int64, error) {
func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) int64 {
q, args, err := query.New().
Insert("users").
Columns("sudir_user_id", "first_name", "last_name", "email").
@@ -29,39 +29,41 @@ func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) (int64, error) {
Suffix("RETURNING id").
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "insert sudir user")
panic(errors.WithMessagef(err, "insert sudir user"))
}
var id int64
db.Must().SelectRow(&id, q, args...)
return id, nil
return id
}
func InsertRole(db *dbt.TestDb, role entity.Role) (int64, error) {
func InsertRole(db *dbt.TestDb, role entity.Role) int64 {
if role.Permissions == nil {
role.Permissions = []string{}
}
q, args, err := query.New().
Insert("roles").
Columns("name").
Values(role.Name).
Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name RETURNING id").
Columns("name", "permissions").
Values(role.Name, role.Permissions).
Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, permissions = EXCLUDED.permissions RETURNING id").
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "insert role")
panic(errors.WithMessagef(err, "insert role"))
}
var id int64
db.Must().SelectRow(&id, q, args...)
return id, nil
return id
}
func InsertUserRole(db *dbt.TestDb, role entity.UserRole) error {
func InsertUserRole(db *dbt.TestDb, role entity.UserRole) {
q, args, err := query.New().
Insert("user_roles").
Columns("user_id", "role_id").
Values(role.UserId, role.RoleId).
ToSql()
if err != nil {
return errors.WithMessage(err, "insert user role")
panic(errors.WithMessage(err, "insert user role"))
}
db.Must().Exec(q, args...)
return nil
}
func SelectTokenEntityByToken(db *dbt.TestDb, token string) entity.Token {
+59
View File
@@ -136,3 +136,62 @@ func (s *SecureSuite) Test_Authenticate_NotFound() {
AdminId: 0,
}, result)
}
func (s *SecureSuite) Test_Authorize_HappyPath() {
role1Id := InsertRole(s.db, entity.Role{
Name: "role1",
Permissions: []string{
"perm1",
},
})
role2Id := InsertRole(s.db, entity.Role{
Name: "role2",
Permissions: []string{
"perm2",
},
})
userId := InsertUser(s.db, entity.User{
Email: "test",
})
InsertUserRole(s.db, entity.UserRole{
UserId: int(userId),
RoleId: int(role1Id),
})
InsertUserRole(s.db, entity.UserRole{
UserId: int(userId),
RoleId: int(role2Id),
})
result := domain.SecureAuthzResponse{}
err := s.grpcCli.Invoke("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId),
Permission: "perm1",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.True(result.Authorized)
result = domain.SecureAuthzResponse{}
err = s.grpcCli.Invoke("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId),
Permission: "perm2",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.True(result.Authorized)
result = domain.SecureAuthzResponse{}
err = s.grpcCli.Invoke("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId),
Permission: "perm3",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.False(result.Authorized)
}
+9 -15
View File
@@ -73,19 +73,17 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
Password: "password",
})
roleId, err := InsertRole(s.db, entity.Role{
roleId := InsertRole(s.db, entity.Role{
Name: "admin",
})
s.Require().NoError(err)
err = InsertUserRole(s.db, entity.UserRole{
InsertUserRole(s.db, entity.UserRole{
UserId: int(id),
RoleId: int(roleId),
})
s.Require().NoError(err)
response := domain.AdminUserShort{}
err = s.grpcCli.Invoke("admin/user/get_profile").
err := s.grpcCli.Invoke("admin/user/get_profile").
JsonResponseBody(&response).
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
Do(context.Background())
@@ -119,27 +117,24 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
}
func (s *UserTestSuite) TestGetProfileSudir() {
id, err := InsertSudirUser(s.db, entity.SudirUser{
id := InsertSudirUser(s.db, entity.SudirUser{
SudirUserId: "sudirUser1",
FirstName: "name",
LastName: "surname",
Email: "a@b.ru",
})
s.Require().NoError(err)
roleId, err := InsertRole(s.db, entity.Role{
roleId := InsertRole(s.db, entity.Role{
Name: "admin",
})
s.Require().NoError(err)
err = InsertUserRole(s.db, entity.UserRole{
InsertUserRole(s.db, entity.UserRole{
UserId: int(id),
RoleId: int(roleId),
})
s.Require().NoError(err)
response := domain.AdminUserShort{}
err = s.grpcCli.
err := s.grpcCli.
Invoke("admin/user/get_profile").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonResponseBody(&response).
@@ -249,8 +244,7 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
}
func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
id, err := InsertSudirUser(s.db, entity.SudirUser{Email: "sudir@a.ru"})
s.Require().NoError(err)
id := InsertSudirUser(s.db, entity.SudirUser{Email: "sudir@a.ru"})
req := domain.UpdateUserRequest{
Id: id,
FirstName: "name",
@@ -258,7 +252,7 @@ func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
Email: "sudir@a.ru",
}
response := domain.User{}
err = s.grpcCli.
err := s.grpcCli.
Invoke("admin/user/update_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonRequestBody(req).