From 7bac2e403f94f2afe3380e5d63c4fd5b767d423c Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 15:41:28 +0300 Subject: [PATCH] MSP-8974 review fixes --- assembly/assembly.go | 15 ++- assembly/locator.go | 30 +++--- auth/auth.go | 80 ---------------- controller/audit.go | 1 - controller/download.go | 18 ++-- docs/swagger.json | 76 +-------------- domain/errors.go | 20 ++-- domain/session.go | 23 +++++ entity/download.go | 12 --- repository/admin.go | 103 -------------------- service/download.go | 76 +++++++-------- tests/audit_test.go | 4 +- tests/auth_test.go | 2 +- tests/customization_test.go | 2 +- tests/download_test.go | 183 ++++++++++++++---------------------- tests/inactive_test.go | 2 +- tests/secure_test.go | 2 +- tests/session_test.go | 2 +- tests/ui_settings_test.go | 2 +- tests/user_test.go | 2 +- 20 files changed, 189 insertions(+), 466 deletions(-) delete mode 100644 repository/admin.go diff --git a/assembly/assembly.go b/assembly/assembly.go index 66390f6..e249b8b 100644 --- a/assembly/assembly.go +++ b/assembly/assembly.go @@ -24,13 +24,12 @@ import ( ) type Assembly struct { - boot *bootstrap.Bootstrap - db *dbrx.Client - server *http.Server - downloadCli *httpcli.Client - oauthCli *httpcli.Client - logger *log.Adapter - bgjobCli *bgjobx.Client + boot *bootstrap.Bootstrap + db *dbrx.Client + server *http.Server + oauthCli *httpcli.Client + logger *log.Adapter + bgjobCli *bgjobx.Client } func New(boot *bootstrap.Bootstrap) (*Assembly, error) { @@ -74,7 +73,7 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error } a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl - locator := NewLocator(a.logger, a.oauthCli, a.downloadCli, a.db) + locator := NewLocator(a.logger, a.oauthCli, a.db) config, err := locator.Config(ctx, newCfg, time.Minute) if err != nil { a.logger.Fatal(ctx, errors.WithMessage(err, "locator config")) diff --git a/assembly/locator.go b/assembly/locator.go index 256dd7f..0e3cbae 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -18,7 +18,7 @@ import ( "github.com/txix-open/isp-kit/bgjobx" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/errors" - httpEndpoint "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint" "github.com/txix-open/isp-kit/http/endpoint/httplog" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/http/router" @@ -31,18 +31,16 @@ type DB interface { } type Locator struct { - logger log.Logger - downloadCli *httpcli.Client - oauthCli *httpcli.Client - db DB + logger log.Logger + oauthCli *httpcli.Client + db DB } -func NewLocator(logger log.Logger, oauthCli *httpcli.Client, downloadCli *httpcli.Client, db DB) Locator { +func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator { return Locator{ - logger: logger, - downloadCli: downloadCli, - oauthCli: oauthCli, - db: db, + logger: logger, + oauthCli: oauthCli, + db: db, } } @@ -64,11 +62,9 @@ func (l Locator) Config( auditRepo := repository.NewAudit(l.db) auditEventRepo := repository.NewAuditEvent(l.db) userRoleRepo := repository.NewUserRole(l.db) - adminRepo := repository.NewAdmin(l.downloadCli) auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings) tokenService := service.NewToken(tokenRepo, cfg.ExpireSec) - downloadService := service.NewDownload(adminRepo) oauthBaseUrl, oauthSettings := l.getOauthSettings(cfg.Oauth) oauthService, err := service.NewOauth(oauthSettings, oauthRepo) @@ -102,6 +98,14 @@ func (l Locator) Config( uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings) + downloadService := service.NewDownload( + auditService, + userService, + tokenService, + roleService, + *permissionsService, + ) + userController := controller.NewUser(userService) customizationController := controller.NewCustomization(cfg.UiDesign) authController := controller.NewAuth(authService, l.logger) @@ -113,7 +117,7 @@ func (l Locator) Config( uiSettingsController := controller.NewUiSettings(uiSettingsService) downloadController := controller.NewDownload(downloadService) - wrapper := httpEndpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true)) + wrapper := endpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true)) handler := routes.Handler( wrapper, routes.Controllers{ diff --git a/auth/auth.go b/auth/auth.go index 8213e91..498eecd 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -7,86 +7,6 @@ import ( "github.com/txix-open/isp-kit/errors" ) -const ( - // ApplicationIdHeader is the header key for application identity. - ApplicationIdHeader = "x-application-identity" - // ApplicationNameHeader is the header key for application name. - ApplicationNameHeader = "x-application-name" - // UserIdHeader is the header key for user identity. - UserIdHeader = "x-user-identity" - // DeviceIdHeader is the header key for device identity. - DeviceIdHeader = "x-device-identity" - // ServiceIdHeader is the header key for service identity. - ServiceIdHeader = "x-service-identity" - // DomainIdHeader is the header key for domain identity. - DomainIdHeader = "x-domain-identity" - // SystemIdHeader is the header key for system identity. - SystemIdHeader = "x-system-identity" - // UserTokenHeader is the header key for user token. - UserTokenHeader = "x-user-token" - // DeviceTokenHeader is the header key for device token. - DeviceTokenHeader = "x-device-token" -) - -// AuthData wraps http.Header to provide structured access to authentication -// and authorization information from http request header. -// All methods return an error if the key is not found or cannot be parsed. -type AuthData http.Header - -// SystemId extracts the system identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) SystemId() (int, error) { - return IntFromHeader(SystemIdHeader, http.Header(i)) -} - -// DomainId extracts the domain identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) DomainId() (int, error) { - return IntFromHeader(DomainIdHeader, http.Header(i)) -} - -// ServiceId extracts the service identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) ServiceId() (int, error) { - return IntFromHeader(ServiceIdHeader, http.Header(i)) -} - -// ApplicationId extracts the application identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) ApplicationId() (int, error) { - return IntFromHeader(ApplicationIdHeader, http.Header(i)) -} - -// ApplicationName extracts the application name from header as a string. -// Returns an error if the key is not found. -func (i AuthData) ApplicationName() (string, error) { - return StringFromHeader(ApplicationNameHeader, http.Header(i)) -} - -// UserId extracts the user identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) UserId() (int, error) { - return IntFromHeader(UserIdHeader, http.Header(i)) -} - -// DeviceId extracts the device identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) DeviceId() (int, error) { - return IntFromHeader(DeviceIdHeader, http.Header(i)) -} - -// UserToken extracts the user token from header as a string. -// Returns an error if the key is not found. -func (i AuthData) UserToken() (string, error) { - return StringFromHeader(UserTokenHeader, http.Header(i)) -} - -// DeviceToken extracts the device token from header as a string. -// Returns an error if the key is not found. -func (i AuthData) DeviceToken() (string, error) { - return StringFromHeader(DeviceTokenHeader, http.Header(i)) -} - // StringFromHeader extracts a string value from header by key. // Returns an error if header is nil or the key is not found. func StringFromHeader(key string, h http.Header) (string, error) { diff --git a/controller/audit.go b/controller/audit.go index c228e76..3650203 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -29,7 +29,6 @@ func NewAudit(service AuditService) Audit { // All // @Tags log // @Summary Получение списка логов -// @Description `errorCode: 400` - если тело запроса невалидно // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" diff --git a/controller/download.go b/controller/download.go index 7cabac1..6b10796 100644 --- a/controller/download.go +++ b/controller/download.go @@ -10,9 +10,9 @@ import ( ) type DownloadService interface { - DownloadUsers(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error - DownloadSessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error - DownloadAudit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error + DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error + DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error + DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error DownloadRoles(ctx context.Context, w http.ResponseWriter) error } @@ -31,11 +31,11 @@ func NewDownload(service DownloadService) Download { // @Summary Скачать список пользователей в csv // @Accept json // @Produce json -// @Param body body domain.UsersDownloadRequest true "Тело запроса" +// @Param body body domain.UsersPageRequest true "Тело запроса" // @Success 200 // @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /user/download [POST] -func (c Download) Users(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error { +func (c Download) Users(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error { err := c.service.DownloadUsers(ctx, req, w) if err != nil { return errors.WithMessage(err, "download users") @@ -49,11 +49,11 @@ func (c Download) Users(ctx context.Context, req domain.UsersDownloadRequest, w // @Summary Скачать список сессий в csv // @Accept json // @Produce json -// @Param body body domain.SessionDownloadRequest true "Тело запроса" +// @Param body body domain.SessionPageRequest true "Тело запроса" // @Success 200 // @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /session/download [POST] -func (c Download) Sessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error { +func (c Download) Sessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error { err := c.service.DownloadSessions(ctx, req, w) if err != nil { return errors.WithMessage(err, "download sessions") @@ -67,11 +67,11 @@ func (c Download) Sessions(ctx context.Context, req domain.SessionDownloadReques // @Summary Скачать журнал аудита в csv // @Accept json // @Produce json -// @Param body body domain.AuditDownloadRequest true "Тело запроса" +// @Param body body domain.AuditPageRequest true "Тело запроса" // @Success 200 // @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /log/download [POST] -func (c Download) Audit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error { +func (c Download) Audit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error { err := c.service.DownloadAudit(ctx, req, w) if err != nil { return errors.WithMessage(err, "download audit") diff --git a/docs/swagger.json b/docs/swagger.json index d6ed766..2c2b503 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -223,7 +223,6 @@ }, "/log/all": { "post": { - "description": "`errorCode: 400` - если тело запроса невалидно", "consumes": [ "application/json" ], @@ -293,7 +292,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/domain.AuditDownloadRequest" + "$ref": "#/definitions/domain.AuditPageRequest" } } ], @@ -808,7 +807,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/domain.SessionDownloadRequest" + "$ref": "#/definitions/domain.SessionPageRequest" } } ], @@ -1155,7 +1154,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/domain.UsersDownloadRequest" + "$ref": "#/definitions/domain.UsersPageRequest" } } ], @@ -1596,29 +1595,6 @@ } } }, - "domain.AuditDownloadRequest": { - "type": "object", - "required": [ - "limit" - ], - "properties": { - "limit": { - "description": "Максимальное количество записей", - "type": "integer" - }, - "offset": { - "description": "Отступ для выборки", - "type": "integer", - "format": "int64" - }, - "order": { - "$ref": "#/definitions/domain.OrderParams" - }, - "query": { - "$ref": "#/definitions/domain.AuditQuery" - } - } - }, "domain.AuditEvent": { "type": "object", "properties": { @@ -2098,29 +2074,6 @@ } } }, - "domain.SessionDownloadRequest": { - "type": "object", - "required": [ - "limit" - ], - "properties": { - "limit": { - "description": "Максимальное количество записей", - "type": "integer" - }, - "offset": { - "description": "Отступ для выборки", - "type": "integer", - "format": "int64" - }, - "order": { - "$ref": "#/definitions/domain.OrderParams" - }, - "query": { - "$ref": "#/definitions/domain.SessionQuery" - } - } - }, "domain.SessionPageRequest": { "type": "object", "required": [ @@ -2412,29 +2365,6 @@ } } }, - "domain.UsersDownloadRequest": { - "type": "object", - "required": [ - "limit" - ], - "properties": { - "limit": { - "description": "Максимальное количество записей", - "type": "integer" - }, - "offset": { - "description": "Отступ для выборки", - "type": "integer", - "format": "int64" - }, - "order": { - "$ref": "#/definitions/domain.OrderParams" - }, - "query": { - "$ref": "#/definitions/domain.UserQuery" - } - } - }, "domain.UsersPageRequest": { "type": "object", "required": [ diff --git a/domain/errors.go b/domain/errors.go index 8572df3..416c46d 100644 --- a/domain/errors.go +++ b/domain/errors.go @@ -28,16 +28,16 @@ var ( // nolint:gochecknoglobals var ( - UnknownAuditEventErrorCode = 1 - ErrOauthAuthorizationCode = 2 - ErrUnauthenticatedCode = 3 - ErrTooManyLoginRequestsCode = 4 - ErrOauthIsMissedCode = 5 - ErrAlreadyExistsCode = 6 - ErrNotFoundCode = 7 - ErrUnknownClientCode = 8 - ErrInvalidCode = 9 - ErrInvalidPasswordCode = 10 + UnknownAuditEventErrorCode = 601 + ErrOauthAuthorizationCode = 602 + ErrUnauthenticatedCode = 603 + ErrTooManyLoginRequestsCode = 604 + ErrOauthIsMissedCode = 605 + ErrAlreadyExistsCode = 606 + ErrNotFoundCode = 607 + ErrUnknownClientCode = 608 + ErrInvalidCode = 609 + ErrInvalidPasswordCode = 610 ) type UnknownAuditEventError struct { diff --git a/domain/session.go b/domain/session.go index 7a6061a..bc76be9 100644 --- a/domain/session.go +++ b/domain/session.go @@ -4,6 +4,17 @@ import ( "time" ) +const ( + SessionStatusAllowed = "ALLOWED" + SessionStatusAllowedRus = "Активная" + + SessionStatusExpired = "EXPIRED" + SessionStatusExpiredRus = "Истекшая" + + SessionStatusRevoked = "REVOKED" + SessionStatusRevokedRus = "Отмененная" +) + type Session struct { Id int // Идентификатор сессии UserId int // Идентификатор пользоватеккля @@ -35,3 +46,15 @@ type SessionResponse struct { type RevokeRequest struct { Id int `validate:"required"` // Идентификатор сессии } + +func (s Session) StatusRus() string { + switch s.Status { + case SessionStatusAllowed: + return SessionStatusAllowedRus + case SessionStatusExpired: + return SessionStatusExpiredRus + case SessionStatusRevoked: + return SessionStatusRevokedRus + } + return "" +} diff --git a/entity/download.go b/entity/download.go index 01e4679..0565765 100644 --- a/entity/download.go +++ b/entity/download.go @@ -31,18 +31,6 @@ type SessionResponse struct { Items []Session } -func (s Session) StatusRus() string { - switch s.Status { - case SessionStatusAllowed: - return SessionStatusAllowedRus - case SessionStatusExpired: - return SessionStatusExpiredRus - case SessionStatusRevoked: - return SessionStatusRevokedRus - } - return "" -} - type UsersResponse struct { Items []User } diff --git a/repository/admin.go b/repository/admin.go deleted file mode 100644 index 411ea8d..0000000 --- a/repository/admin.go +++ /dev/null @@ -1,103 +0,0 @@ -package repository - -import ( - "context" - "isp-admin-service/domain" - "isp-admin-service/entity" - - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/http/httpcli" -) - -const ( - getAllLogs = "/admin/log/all" - getAllSessions = "/admin/session/all" - getAllUsers = "/admin/user/get_users" - getAllRoles = "/admin/role/all" - getPermissions = "/admin/user/get_permissions" -) - -type ReqGetById struct { - UserId int `json:"userId"` -} - -type Admin struct { - cli *httpcli.Client -} - -func NewAdmin(cli *httpcli.Client) Admin { - return Admin{cli: cli} -} - -func (r Admin) GetAudit(ctx context.Context, req domain.AuditDownloadRequest) (*entity.AuditResponse, error) { - var response entity.AuditResponse - - err := r.cli.Post(getAllLogs). - JsonRequestBody(req). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllLogs) - } - - return &response, nil -} - -func (r Admin) GetSessions(ctx context.Context, req domain.SessionDownloadRequest) (*entity.SessionResponse, error) { - var response entity.SessionResponse - - err := r.cli.Post(getAllSessions). - JsonRequestBody(req). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllSessions) - } - - return &response, nil -} - -func (r Admin) GetUsers(ctx context.Context, req domain.UsersDownloadRequest) ([]entity.User, error) { - var response entity.UsersResponse - - err := r.cli.Post(getAllUsers). - JsonRequestBody(req). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllUsers) - } - - return response.Items, nil -} - -func (r Admin) GetRoles(ctx context.Context) ([]entity.Role, error) { - var response []entity.Role - - err := r.cli.Post(getAllRoles). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllRoles) - } - - return response, nil -} - -func (r Admin) GetPermissions(ctx context.Context) ([]entity.Permission, error) { - var response []entity.Permission - - err := r.cli.Post(getPermissions). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getPermissions) - } - - return response, nil -} diff --git a/service/download.go b/service/download.go index f65409a..d6a68ad 100644 --- a/service/download.go +++ b/service/download.go @@ -22,32 +22,38 @@ const ( notFoundSymbol = "-" ) -type AdminRepo interface { - GetAudit(ctx context.Context, req domain.AuditDownloadRequest) (*entity.AuditResponse, error) - GetSessions(ctx context.Context, req domain.SessionDownloadRequest) (*entity.SessionResponse, error) - GetUsers(ctx context.Context, req domain.UsersDownloadRequest) ([]entity.User, error) - GetRoles(ctx context.Context) ([]entity.Role, error) - GetPermissions(ctx context.Context) ([]entity.Permission, error) -} - type Download struct { - repo AdminRepo - loc *time.Location + auditService Audit + userService User + tokenService Token + roleService Role + permissionService Permission + loc *time.Location } -func NewDownload(repo AdminRepo) Download { +func NewDownload( + auditService Audit, + userService User, + tokenService Token, + roleService Role, + permissionService Permission, +) Download { loc, _ := time.LoadLocation("Europe/Moscow") return Download{ - repo: repo, - loc: loc, + auditService: auditService, + userService: userService, + tokenService: tokenService, + roleService: roleService, + permissionService: permissionService, + loc: loc, } } -func (s Download) DownloadAudit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error { +func (s Download) DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error { req.Limit = requestLimit req.Offset = 0 - response, err := s.repo.GetAudit(ctx, req) + response, err := s.auditService.All(ctx, req) if err != nil { return errors.WithMessage(err, "get audit") } @@ -90,7 +96,7 @@ func (s Download) DownloadAudit(ctx context.Context, req domain.AuditDownloadReq } req.Offset += requestLimit - response, err = s.repo.GetAudit(ctx, req) + response, err = s.auditService.All(ctx, req) if err != nil { return errors.WithMessage(err, "get audit") } @@ -101,11 +107,11 @@ func (s Download) DownloadAudit(ctx context.Context, req domain.AuditDownloadReq return nil } -func (s Download) DownloadSessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error { +func (s Download) DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error { req.Limit = requestLimit req.Offset = 0 - response, err := s.repo.GetSessions(ctx, req) + response, err := s.tokenService.All(ctx, req) if err != nil { return errors.WithMessage(err, "get sessions") } @@ -152,7 +158,7 @@ func (s Download) DownloadSessions(ctx context.Context, req domain.SessionDownlo } req.Offset += requestLimit - response, err = s.repo.GetSessions(ctx, req) + response, err = s.tokenService.All(ctx, req) if err != nil { return errors.WithMessage(err, "get sessions") } @@ -163,21 +169,21 @@ func (s Download) DownloadSessions(ctx context.Context, req domain.SessionDownlo return nil } -func (s Download) DownloadUsers(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error { +func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error { req.Limit = requestLimit req.Offset = 0 - users, err := s.repo.GetUsers(ctx, req) + users, err := s.userService.GetUsers(ctx, req) if err != nil { return errors.WithMessage(err, "get users") } - roles, err := s.repo.GetRoles(ctx) + roles, err := s.roleService.All(ctx) if err != nil { return errors.WithMessage(err, "get roles") } - if len(users) == 0 { + if len(users.Items) == 0 { return nil } @@ -193,7 +199,7 @@ func (s Download) DownloadUsers(ctx context.Context, req domain.UsersDownloadReq return errors.WithMessage(err, "write userColumns to csv") } - for _, user := range users { + for _, user := range users.Items { row := []string{strconv.Itoa(int(user.Id)), user.FullName, user.Description, @@ -211,15 +217,12 @@ func (s Download) DownloadUsers(ctx context.Context, req domain.UsersDownloadReq } func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) error { - roles, err := s.repo.GetRoles(ctx) + roles, err := s.roleService.All(ctx) if err != nil { return errors.WithMessage(err, "get roles") } - perms, err := s.repo.GetPermissions(ctx) - if err != nil { - return errors.WithMessage(err, "get permissions") - } + perms := s.permissionService.All(ctx) if len(perms) == 0 { return nil @@ -262,24 +265,21 @@ func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) erro return nil } -func (s Download) getUsersList(ctx context.Context) (map[int]entity.User, error) { - users, err := s.repo.GetUsers(ctx, domain.UsersDownloadRequest{ - Limit: requestLimit, - Offset: 0, - }) +func (s Download) getUsersList(ctx context.Context) (map[int]domain.User, error) { + users, err := s.userService.GetAllUsers(ctx) if err != nil { return nil, errors.WithMessage(err, "get users") } - userById := make(map[int]entity.User) - for _, user := range users { + userById := make(map[int]domain.User) + for _, user := range users.Items { userById[int(user.Id)] = user } return userById, nil } -func getUsername(userById map[int]entity.User, userId int) string { +func getUsername(userById map[int]domain.User, userId int) string { user, ok := userById[userId] if !ok { return "" @@ -288,7 +288,7 @@ func getUsername(userById map[int]entity.User, userId int) string { return user.FullName } -func getRoleNamesByIds(roles []entity.Role, roleIds []int) string { +func getRoleNamesByIds(roles []domain.Role, roleIds []int) string { names := make([]string, 0) for _, role := range roles { if slices.Contains(roleIds, role.Id) { diff --git a/tests/audit_test.go b/tests/audit_test.go index 9681942..883a75a 100644 --- a/tests/audit_test.go +++ b/tests/audit_test.go @@ -68,7 +68,7 @@ func (s *AuditSuite) SetupTest() { AuditTTl: conf.AuditTTlSetting{}, }, } - cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), httpcli.New(), s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) s.insertAuditLogs() @@ -178,7 +178,7 @@ func (s *AuditSuite) Test_SetEvents_InvalidEvent() { var httpErr httpcli.ErrorResponse s.Require().ErrorAs(err, &httpErr) - s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode) // не уверен тут какой код проверять? Статус или внутренний? Коммент чтобы не забыть + s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode) } func (s *AuditSuite) Test_All_Logs() { diff --git a/tests/auth_test.go b/tests/auth_test.go index 61b23bb..9549cd7 100644 --- a/tests/auth_test.go +++ b/tests/auth_test.go @@ -74,7 +74,7 @@ func (s *AuthTestSuite) SetupTest() { }, } - cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, httpcli.New(), s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) diff --git a/tests/customization_test.go b/tests/customization_test.go index 56c6729..734fa7a 100644 --- a/tests/customization_test.go +++ b/tests/customization_test.go @@ -40,7 +40,7 @@ func (s *CustomizationTestSuite) SetupTest() { }, ExpireSec: 0, } - cfg, err := assembly.NewLocator(testInstance.Logger(), nil, nil, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) diff --git a/tests/download_test.go b/tests/download_test.go index e6beb36..29ea6e9 100644 --- a/tests/download_test.go +++ b/tests/download_test.go @@ -3,7 +3,6 @@ package tests_test import ( "encoding/csv" - "encoding/json" "net/http" "testing" "time" @@ -12,6 +11,7 @@ import ( "isp-admin-service/conf" "isp-admin-service/domain" "isp-admin-service/entity" + "isp-admin-service/repository" "github.com/stretchr/testify/suite" @@ -33,7 +33,6 @@ type DownloadSuite struct { test *test.Test db *dbt.TestDb httpCli *httpcli.Client - downloadCli *httpcli.Client permissions entity.PermList } @@ -50,8 +49,7 @@ func (s *DownloadSuite) SetupTest() { }, }, } - s.initMockDownload() - cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.downloadCli, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) @@ -79,8 +77,13 @@ func (s *DownloadSuite) TestUsersHappyPath() { InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) resp, err := s.httpCli.Post("user/download"). - JsonRequestBody(domain.UsersDownloadRequest{ - Limit: 1000, Offset: 0, + JsonRequestBody(domain.UsersPageRequest{ + Limit: 1000, + Offset: 0, + Order: &domain.OrderParams{ + Field: "id", + Type: "desc", + }, }). Do(s.T().Context()) s.Require().NoError(err) @@ -104,22 +107,53 @@ func (s *DownloadSuite) TestUsersHappyPath() { fullNameIdx, ok := col["Пользователь"] s.Require().True(ok) - s.Require().Len(records, 2) + s.Require().Len(records, 4) row := records[1] - s.Require().EqualValues("1", row[idIdx]) + s.Require().EqualValues("3", row[idIdx]) s.Require().EqualValues("alice@a.ru", row[emailIdx]) s.Require().EqualValues("Bob Alice", row[fullNameIdx]) } func (s *DownloadSuite) TestSessionsHappyPath() { - id1 := InsertUser(s.db, entity.User{Email: "sess1@a.ru"}) + timeNow := time.Now().UTC() + userId := InsertUser(s.db, entity.User{Email: "sess1@a.ru", FullName: "Bob Alice"}) roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions}) - InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) + InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)}) + + InsertTokenEntity(s.db, entity.Token{ + Token: "test_token_1", + UserId: userId, + Status: entity.TokenStatusAllowed, + ExpiredAt: timeNow.Add(1 * time.Hour), + CreatedAt: timeNow.Add(-1 * time.Hour), + UpdatedAt: timeNow, + }) + InsertTokenEntity(s.db, entity.Token{ + Token: "test_token_2", + UserId: userId, + Status: entity.TokenStatusRevoked, + ExpiredAt: timeNow.Add(1 * time.Hour), + CreatedAt: timeNow.Add(-2 * time.Hour), + UpdatedAt: timeNow, + }) + InsertTokenEntity(s.db, entity.Token{ + Token: "test_token_3", + UserId: userId, + Status: entity.TokenStatusExpired, + ExpiredAt: timeNow.Add(-1 * time.Hour), + CreatedAt: timeNow.Add(-3 * time.Hour), + UpdatedAt: timeNow, + }) resp, err := s.httpCli.Post("/session/download"). - JsonRequestBody(domain.SessionDownloadRequest{ - Limit: 1000, Offset: 0, + JsonRequestBody(domain.SessionPageRequest{ + Limit: 1000, + Offset: 0, + Order: &domain.OrderParams{ + Field: "user_id", + Type: "desc", + }, }). Do(s.T().Context()) s.Require().NoError(err) @@ -141,20 +175,36 @@ func (s *DownloadSuite) TestSessionsHappyPath() { idIdx, ok := col["Идентификатор"] s.Require().True(ok) - s.Require().Len(records, 2) + s.Require().Len(records, 4) row := records[1] s.Require().EqualValues("Bob Alice", row[userIdx]) s.Require().EqualValues("1", row[idIdx]) } func (s *DownloadSuite) TestAuditHappyPath() { - id1 := InsertUser(s.db, entity.User{Email: "audit1@a.ru"}) + timeNow := time.Now().UTC() + userId := InsertUser(s.db, entity.User{Email: "audit1@a.ru", FullName: "Bob Alice"}) roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions}) - InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) + InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)}) + + auditRepo := repository.NewAudit(s.db) + _, err := auditRepo.Insert(s.T().Context(), entity.Audit{ + Id: 1, + UserId: int(userId), + Message: "audit1@a.ru", + Event: "123456", + CreatedAt: timeNow, + }) + s.Require().NoError(err) resp, err := s.httpCli.Post("log/download"). - JsonRequestBody(domain.AuditDownloadRequest{ - Limit: 1000, Offset: 0, + JsonRequestBody(domain.AuditPageRequest{ + Limit: 1000, + Offset: 0, + Order: &domain.OrderParams{ + Field: "user_id", + Type: "desc", + }, }). StatusCodeToError(). Do(s.T().Context()) @@ -172,7 +222,7 @@ func (s *DownloadSuite) TestAuditHappyPath() { idIdx, ok := col["Пользователь"] s.Require().True(ok) - moveIdx, ok := col["Действие"] // уточнить + moveIdx, ok := col["Действие"] s.Require().True(ok) s.Require().Len(records, 2) @@ -182,99 +232,12 @@ func (s *DownloadSuite) TestAuditHappyPath() { } func (s *DownloadSuite) TestRolesHappyPath() { - err := s.httpCli.Post("role/download"). + resp, err := s.httpCli.Post("role/download"). StatusCodeToError(). - DoWithoutResponse(s.T().Context()) + Do(s.T().Context()) s.Require().NoError(err) -} -func (s *DownloadSuite) initMockDownload() { - mocksrv := httpt.NewMock(s.test) - mocksrv.POST("/user/download", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.User{{Id: 0, FullName: "Bob Alice", Email: "alice@a.ru"}}, - }) - }) - mocksrv.POST("/session/download", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.User{{Id: 0, FullName: "Sess1", Email: "sess1@a.ru"}}, - }) - }) - mocksrv.POST("/log/download", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "TotalCount": 1, - "Items": []domain.Audit{{Id: 0, UserId: 0, Message: "audit1@a.ru"}}, - }) - }) - mocksrv.POST("/role/download", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.User{{Id: 0, Roles: []int{0}, Email: "admin@a.ru"}}, - }) - }) - - mocksrv.POST("/admin/user/get_users", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.User{{ - Id: 1, - FullName: "Bob Alice", - Email: "alice@a.ru", - }}, - "TotalCount": 1, - }) - }) - - mocksrv.POST("/admin/user/get_permissions", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode([]domain.Permission{{ - Key: "data_download", - Name: "123", - }}) - }) - - mocksrv.POST("/admin/session/all", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.Session{{ - Id: 1, - UserId: 1, - }}, - "TotalCount": 1, - }) - }) - - mocksrv.POST("/admin/log/all", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.Audit{{ - Id: 1, - UserId: 1, - Message: "audit1@a.ru", - }}, - "TotalCount": 1, - }) - }) - - mocksrv.POST("/admin/role/all", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode([]domain.Role{{ - Id: 1, - Name: "admin", - }}) - }) - - s.downloadCli = mocksrv.Client() + records, err := csv.NewReader(resp.Raw.Body).ReadAll() + s.Require().NoError(err) + s.Require().NotEmpty(records) } diff --git a/tests/inactive_test.go b/tests/inactive_test.go index a0f01be..e96e04a 100644 --- a/tests/inactive_test.go +++ b/tests/inactive_test.go @@ -27,7 +27,7 @@ func TestInactiveWorker(t *testing.T) { userId := InsertUser(db, entity.User{Email: "a@test", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)}) InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()}) - config, err := assembly.NewLocator(test.Logger(), nil, nil, db). + config, err := assembly.NewLocator(test.Logger(), nil, db). Config(t.Context(), conf.Remote{ BlockInactiveWorker: conf.BlockInactiveWorker{ DaysThreshold: 1, diff --git a/tests/secure_test.go b/tests/secure_test.go index 2255a9a..7327d31 100644 --- a/tests/secure_test.go +++ b/tests/secure_test.go @@ -39,7 +39,7 @@ func (s *SecureSuite) SetupTest() { remote := conf.Remote{ ExpireSec: 3600, } - cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, nil, s.db). + cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) diff --git a/tests/session_test.go b/tests/session_test.go index 474bba3..f8a23b7 100644 --- a/tests/session_test.go +++ b/tests/session_test.go @@ -70,7 +70,7 @@ func (s *SessionSuite) SetupTest() { AuditTTl: conf.AuditTTlSetting{}, }, } - config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), nil, s.db). + config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). Config(s.T().Context(), remote, 500*time.Millisecond) s.Require().NoError(err) diff --git a/tests/ui_settings_test.go b/tests/ui_settings_test.go index a507093..740007b 100644 --- a/tests/ui_settings_test.go +++ b/tests/ui_settings_test.go @@ -49,7 +49,7 @@ func (s *UiSettingsSuite) SetupTest() { Clients: []conf.OauthClientConfig{s.oauthClientSetting}, }, } - cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil, nil). + cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil). Config(s.T().Context(), remote, 0) s.Require().NoError(err) diff --git a/tests/user_test.go b/tests/user_test.go index 77e22d2..ed0d529 100644 --- a/tests/user_test.go +++ b/tests/user_test.go @@ -54,7 +54,7 @@ func (s *UserTestSuite) SetupTest() { remote := conf.Remote{ ExpireSec: 0, } - cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, nil, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err)