MSP-2370 implement admin/secure/authorize
This commit is contained in:
1 parent
db7a668875
commit
3b3fc9dcfb
20 files changed
+509
-177
No files matched your search
+25
-2
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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]
|
||||
}
|
||||
Reference in new issue
Block a user