Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b167919b1 | ||
|
|
f10153a53b | ||
|
|
83b10f368c | ||
|
|
8789f8a5ec | ||
|
|
3bbe1c3952 | ||
|
|
e1de1c31d8 | ||
|
|
0166d4a050 | ||
|
|
5d7c8f48c3 | ||
|
|
8ec71761d3 | ||
|
|
f8074400a1 | ||
|
|
daf35df301 | ||
|
|
1efb8fa354 | ||
|
|
17747f5b74 | ||
|
|
ed8a4eef5d |
No files matched your search
@@ -69,6 +69,8 @@ fabric.properties
|
|||||||
*.out
|
*.out
|
||||||
|
|
||||||
/node_modules/
|
/node_modules/
|
||||||
|
/vendor/
|
||||||
|
google/
|
||||||
package.json
|
package.json
|
||||||
yarn.lock
|
yarn.lock
|
||||||
/bin/golangci-lint
|
/bin/golangci-lint
|
||||||
@@ -17,15 +17,7 @@ linters:
|
|||||||
- tagalign # не всегда имеет смысл
|
- tagalign # не всегда имеет смысл
|
||||||
- varnamelen # очень индивидуально (db)
|
- varnamelen # очень индивидуально (db)
|
||||||
- wsl # расставление пробелов очень индивидуально
|
- wsl # расставление пробелов очень индивидуально
|
||||||
- wsl_v5 # расставление пробелов очень индивидуально
|
|
||||||
- godoclint # ругается на // nolint, не удобно
|
|
||||||
- prealloc # слишком аггресивный, в большинстве случаев не требуется
|
|
||||||
- gomodguard # deprecated
|
|
||||||
- goconst # слишком агрессивный
|
|
||||||
settings:
|
settings:
|
||||||
exhaustruct_v5:
|
|
||||||
allow-empty: true
|
|
||||||
explicit-mode: true
|
|
||||||
cyclop:
|
cyclop:
|
||||||
max-complexity: 15 # по умолчанию 10 мало
|
max-complexity: 15 # по умолчанию 10 мало
|
||||||
funlen:
|
funlen:
|
||||||
@@ -61,13 +53,6 @@ linters:
|
|||||||
- linters:
|
- linters:
|
||||||
- wrapcheck
|
- wrapcheck
|
||||||
path: transaction # транзакции прозрачны
|
path: transaction # транзакции прозрачны
|
||||||
- linters:
|
|
||||||
- unqueryvet
|
|
||||||
- prealloc
|
|
||||||
path: ".*_test\\.go$"
|
|
||||||
- linters:
|
|
||||||
- goconst
|
|
||||||
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
|
|
||||||
paths:
|
paths:
|
||||||
- third_party$
|
- third_party$
|
||||||
- builtin$
|
- builtin$
|
||||||
@@ -81,4 +66,3 @@ formatters:
|
|||||||
- third_party$
|
- third_party$
|
||||||
- builtin$
|
- builtin$
|
||||||
- examples$
|
- examples$
|
||||||
|
|
||||||
@@ -1,53 +1,3 @@
|
|||||||
### v7.2.0
|
|
||||||
* Добавлено поле `application_group` в таблицу `roles`
|
|
||||||
* Добавлен для запросов `admin/role/create` и `admin/role/update`, необязателен
|
|
||||||
* Изменен эндпоинт `admin/role/all`, теперь результаты фильтруются по группе из тела запроса, при пустом теле без фильтрации
|
|
||||||
* Добавлена возможность скачивания и формирования CSV
|
|
||||||
### v7.1.0
|
|
||||||
* переименование авторизации через SUDIR в OAuth:
|
|
||||||
* Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth`
|
|
||||||
* Колонка `users.sudir_user_id` → `users.oauth_user_id`
|
|
||||||
* Переименованы ошибки: `ErrOauthAuthorization`, `ErrOauthIsMissed`
|
|
||||||
* Метод `LoginWithSudir` → `LoginWithOauth`, поле `OauthUser.SudirUserId` → `OauthUser.OauthUserId`
|
|
||||||
* Обновлены сообщения ошибок, логи, аудит и swagger-документация
|
|
||||||
* в конфиге ключ OAuth-раздела `sudirAuth` → `oauth`
|
|
||||||
### v7.0.0
|
|
||||||
* Изменена логика авторизации через СУДИР:
|
|
||||||
* Изменена схема конфигурации для авторизации через СУДИР
|
|
||||||
* Изменён контракт взаимодействия по `admin/auth/login_with_sudir`
|
|
||||||
* Добавлен endpoint для получения ссылок для login и logout через sudir - `admin/ui_settings/sudir`
|
|
||||||
### v6.8.2
|
|
||||||
* обновлены зависимости
|
|
||||||
### v6.8.1
|
|
||||||
* Обновлен isp-kit
|
|
||||||
### v6.8.0
|
|
||||||
* Изменен контракт методов. В запросах теперь массив идентификаторов пользователей и массив статусов сессий
|
|
||||||
* Обновлена версия go
|
|
||||||
### v6.7.0
|
|
||||||
* Обновлены методы `admin/log/all`, `admin/session/all` и `admin/user/get_users`: добавлена сортировка и поиск
|
|
||||||
* Добавлен воркер выставления статуса 'EXPIRED' для токенов сессий
|
|
||||||
* Добавлено поле `fullName` пользователя, содержащее полное ФИО, получаемое от sudir
|
|
||||||
* Обновлены зависимости
|
|
||||||
### v6.6.1
|
|
||||||
* Добавлено поле `roleNames` в метод `admin/user/get_profile`
|
|
||||||
### v6.6.0
|
|
||||||
* Добавлено отдельное событие 'user_blocked' для блокировки/разблокировки пользователей
|
|
||||||
* Обновлены зависимости
|
|
||||||
### v6.5.0
|
|
||||||
* Изменена уникальность учетных записей с "email" на связку "email + sudir_id"
|
|
||||||
* Добавлен метод `admin/auth/logout_with_reason` для вывода логов `Выхода по бездействию` в журнал ИБ
|
|
||||||
### v6.4.0
|
|
||||||
* Обновлены зависимости
|
|
||||||
### v6.3.1
|
|
||||||
* Корневой путь до методов СУДИР перенесён в конфигурацию
|
|
||||||
* Ранее: В конфигурации `https://sudir-domain/` + фиксированно в коде `/blitz/oauth/*`
|
|
||||||
* Сейчас: В конфигурации `https://sudir-domain/<указать, что необходимо>` + фиксированно в коде `/oauth/*`
|
|
||||||
### v6.3.0
|
|
||||||
* убрана интеграция с LDAP
|
|
||||||
* исправлен сброс разблокировки и назначения ролей на пользователя
|
|
||||||
### v6.2.6
|
|
||||||
* добавлен `Dockerfile` и скрипт для сборки и публикации образа в `GitHub Contaier Registry`
|
|
||||||
* обновлены зависимости
|
|
||||||
### v6.2.5
|
### v6.2.5
|
||||||
* исправлена паника при отсутствии ролей у пользователя
|
* исправлена паника при отсутствии ролей у пользователя
|
||||||
* обновлены зависимости
|
* обновлены зависимости
|
||||||
|
|||||||
-47
@@ -1,47 +0,0 @@
|
|||||||
FROM golang:1.26-alpine as builder
|
|
||||||
WORKDIR /build
|
|
||||||
ARG version
|
|
||||||
ENV version_env=$version
|
|
||||||
ARG app_name
|
|
||||||
ENV app_name_env=$app_name
|
|
||||||
COPY . .
|
|
||||||
RUN --mount=type=cache,target=/go/pkg/mod/ \
|
|
||||||
--mount=type=bind,source=go.sum,target=go.sum \
|
|
||||||
--mount=type=bind,source=go.mod,target=go.mod \
|
|
||||||
go mod download -x
|
|
||||||
RUN --mount=type=cache,target=/go/pkg/mod/ \
|
|
||||||
--mount=type=bind,target=. \
|
|
||||||
go build -ldflags="-X 'main.version=$version_env'" -o /main .
|
|
||||||
|
|
||||||
FROM alpine:3.23
|
|
||||||
|
|
||||||
RUN apk add --no-cache tzdata
|
|
||||||
RUN cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime
|
|
||||||
RUN echo "Europe/Moscow" > /etc/timezone
|
|
||||||
|
|
||||||
ARG UID=10001
|
|
||||||
RUN adduser \
|
|
||||||
--disabled-password \
|
|
||||||
--gecos "" \
|
|
||||||
--home "/nonexistent" \
|
|
||||||
--shell "/sbin/nologin" \
|
|
||||||
--no-create-home \
|
|
||||||
--uid "${UID}" \
|
|
||||||
appuser
|
|
||||||
|
|
||||||
RUN mkdir -p /app/data
|
|
||||||
RUN chown appuser:appuser /app/data
|
|
||||||
VOLUME /app/data
|
|
||||||
|
|
||||||
USER appuser
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
ARG app_name
|
|
||||||
ENV app_name_env=$app_name
|
|
||||||
COPY --from=builder main /app/$app_name_env
|
|
||||||
COPY /conf/config.yml /app/config.yml
|
|
||||||
COPY /conf/default_remote_config.json* /app/default_remote_config.json
|
|
||||||
COPY /migrations /app/migrations
|
|
||||||
|
|
||||||
ENTRYPOINT /app/$app_name_env
|
|
||||||
+25
-35
@@ -4,48 +4,45 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/conf"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/service/delete_old_audit_worker"
|
|
||||||
"isp-admin-service/service/inactive_worker"
|
|
||||||
"isp-admin-service/service/session_worker"
|
|
||||||
|
|
||||||
"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/bootstrap"
|
"github.com/txix-open/isp-kit/bootstrap"
|
||||||
"github.com/txix-open/isp-kit/cluster"
|
"github.com/txix-open/isp-kit/cluster"
|
||||||
"github.com/txix-open/isp-kit/dbrx"
|
"github.com/txix-open/isp-kit/dbrx"
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/txix-open/isp-kit/grpc"
|
||||||
"github.com/txix-open/isp-kit/http"
|
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
"github.com/txix-open/isp-kit/http/httpcli"
|
||||||
"github.com/txix-open/isp-kit/http/httpclix"
|
"github.com/txix-open/isp-kit/http/httpclix"
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
"github.com/txix-open/isp-kit/observability/sentry"
|
"msp-admin-service/conf"
|
||||||
|
ldapRepo "msp-admin-service/repository/ldap"
|
||||||
|
"msp-admin-service/service/delete_old_audit_worker"
|
||||||
|
"msp-admin-service/service/inactive_worker"
|
||||||
|
"msp-admin-service/service/ldap"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Assembly struct {
|
type Assembly struct {
|
||||||
boot *bootstrap.Bootstrap
|
boot *bootstrap.Bootstrap
|
||||||
db *dbrx.Client
|
db *dbrx.Client
|
||||||
server *http.Server
|
server *grpc.Server
|
||||||
oauthCli *httpcli.Client
|
httpCli *httpcli.Client
|
||||||
logger *log.Adapter
|
logger *log.Adapter
|
||||||
bgjobCli *bgjobx.Client
|
bgjobCli *bgjobx.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||||
logger := boot.App.Logger()
|
logger := boot.App.Logger()
|
||||||
wrappedLogger := sentry.WrapErrorLogger(logger, boot.SentryHub)
|
server := grpc.NewServer()
|
||||||
|
httpCli := httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(logger)))
|
||||||
db := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, wrappedLogger))
|
db := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, logger))
|
||||||
boot.HealthcheckRegistry.Register("db", db)
|
bgjobCli := bgjobx.NewClient(db, logger)
|
||||||
|
|
||||||
bgjobCli := bgjobx.NewClient(db, wrappedLogger)
|
|
||||||
return &Assembly{
|
return &Assembly{
|
||||||
boot: boot,
|
boot: boot,
|
||||||
db: db,
|
db: db,
|
||||||
server: http.NewServer(logger),
|
server: server,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
|
httpCli: httpCli,
|
||||||
bgjobCli: bgjobCli,
|
bgjobCli: bgjobCli,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -67,17 +64,14 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
|||||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"))
|
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"))
|
||||||
}
|
}
|
||||||
|
|
||||||
oauthBaseUrl := ""
|
locator := NewLocator(a.logger, a.httpCli, a.db)
|
||||||
if newCfg.Oauth != nil {
|
config := locator.Config(ctx, func(config *conf.Ldap) (ldap.Repo, error) {
|
||||||
oauthBaseUrl = newCfg.Oauth.Host
|
repo, err := ldapRepo.NewRepository(config)
|
||||||
}
|
if err != nil {
|
||||||
a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl
|
return nil, errors.WithMessage(err, "new repository")
|
||||||
|
}
|
||||||
locator := NewLocator(a.logger, a.oauthCli, a.db)
|
return repo, nil
|
||||||
config, err := locator.Config(ctx, newCfg, time.Minute)
|
}, newCfg, time.Minute)
|
||||||
if err != nil {
|
|
||||||
a.logger.Fatal(ctx, errors.WithMessage(err, "locator config"))
|
|
||||||
}
|
|
||||||
|
|
||||||
a.server.Upgrade(config.Handler)
|
a.server.Upgrade(config.Handler)
|
||||||
|
|
||||||
@@ -94,10 +88,6 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
a.logger.Fatal(ctx, errors.WithMessage(err, "seed inactive user worker"))
|
a.logger.Fatal(ctx, errors.WithMessage(err, "seed inactive user worker"))
|
||||||
}
|
}
|
||||||
err = session_worker.EnqueueSeedJob(ctx, a.bgjobCli)
|
|
||||||
if err != nil {
|
|
||||||
a.logger.Fatal(ctx, errors.WithMessage(err, "seed expire session worker"))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -109,7 +99,7 @@ func (a *Assembly) Runners() []app.Runner {
|
|||||||
app.RunnerFunc(func(ctx context.Context) error {
|
app.RunnerFunc(func(ctx context.Context) error {
|
||||||
err := a.server.ListenAndServe(a.boot.BindingAddress)
|
err := a.server.ListenAndServe(a.boot.BindingAddress)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "listen and serve http server")
|
return errors.WithMessage(err, "listen ans serve grpc server")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}),
|
}),
|
||||||
@@ -127,7 +117,7 @@ func (a *Assembly) Closers() []app.Closer {
|
|||||||
return []app.Closer{
|
return []app.Closer{
|
||||||
a.boot.ClusterCli,
|
a.boot.ClusterCli,
|
||||||
app.CloserFunc(func() error {
|
app.CloserFunc(func() error {
|
||||||
_ = a.server.Shutdown(context.Background())
|
a.server.Shutdown()
|
||||||
return nil
|
return nil
|
||||||
}),
|
}),
|
||||||
app.CloserFunc(func() error {
|
app.CloserFunc(func() error {
|
||||||
|
|||||||
+31
-63
@@ -4,25 +4,22 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/controller"
|
|
||||||
"isp-admin-service/repository"
|
|
||||||
"isp-admin-service/routes"
|
|
||||||
"isp-admin-service/service"
|
|
||||||
"isp-admin-service/service/delete_old_audit_worker"
|
|
||||||
"isp-admin-service/service/inactive_worker"
|
|
||||||
"isp-admin-service/service/secure"
|
|
||||||
"isp-admin-service/service/session_worker"
|
|
||||||
"isp-admin-service/transaction"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/bgjobx"
|
"github.com/txix-open/isp-kit/bgjobx"
|
||||||
"github.com/txix-open/isp-kit/db"
|
"github.com/txix-open/isp-kit/db"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||||
"github.com/txix-open/isp-kit/http/endpoint"
|
"github.com/txix-open/isp-kit/grpc/isp"
|
||||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
"github.com/txix-open/isp-kit/http/httpcli"
|
||||||
"github.com/txix-open/isp-kit/http/router"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/controller"
|
||||||
|
"msp-admin-service/repository"
|
||||||
|
"msp-admin-service/routes"
|
||||||
|
"msp-admin-service/service"
|
||||||
|
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
type DB interface {
|
type DB interface {
|
||||||
@@ -31,31 +28,32 @@ type DB interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Locator struct {
|
type Locator struct {
|
||||||
logger log.Logger
|
logger log.Logger
|
||||||
oauthCli *httpcli.Client
|
httpCli *httpcli.Client
|
||||||
db DB
|
db DB
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator {
|
func NewLocator(logger log.Logger, httpCli *httpcli.Client, db DB) Locator {
|
||||||
return Locator{
|
return Locator{
|
||||||
logger: logger,
|
logger: logger,
|
||||||
oauthCli: oauthCli,
|
httpCli: httpCli,
|
||||||
db: db,
|
db: db,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Handler *router.Router
|
Handler isp.BackendServiceServer
|
||||||
BgJobCfg []bgjobx.WorkerConfig
|
BgJobCfg []bgjobx.WorkerConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
//nolint:funlen
|
//nolint:funlen
|
||||||
func (l Locator) Config(
|
func (l Locator) Config(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
|
ldapRepoSupplier ldap.RepoSupplier,
|
||||||
cfg conf.Remote,
|
cfg conf.Remote,
|
||||||
jobPollInterval time.Duration,
|
jobPollInterval time.Duration,
|
||||||
) (Config, error) {
|
) Config {
|
||||||
oauthRepo := repository.NewOauth(l.oauthCli)
|
sudirRepo := repository.NewSudir(l.httpCli, cfg.SudirAuth)
|
||||||
roleRepo := repository.NewRole(l.db)
|
roleRepo := repository.NewRole(l.db)
|
||||||
userRepo := repository.NewUser(l.db)
|
userRepo := repository.NewUser(l.db)
|
||||||
tokenRepo := repository.NewToken(l.db)
|
tokenRepo := repository.NewToken(l.db)
|
||||||
@@ -65,17 +63,13 @@ func (l Locator) Config(
|
|||||||
|
|
||||||
auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings)
|
auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings)
|
||||||
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
|
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
|
||||||
|
sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo)
|
||||||
oauthBaseUrl, oauthSettings := l.getOauthSettings(cfg.Oauth)
|
|
||||||
oauthService, err := service.NewOauth(oauthSettings, oauthRepo)
|
|
||||||
if err != nil {
|
|
||||||
return Config{}, errors.WithMessage(err, "new oauth")
|
|
||||||
}
|
|
||||||
|
|
||||||
secureService := secure.NewService(tokenRepo, userRoleRepo)
|
secureService := secure.NewService(tokenRepo, userRoleRepo)
|
||||||
|
|
||||||
txManager := transaction.NewManager(l.db)
|
txManager := transaction.NewManager(l.db)
|
||||||
|
|
||||||
|
ldapService := ldap.NewService(cfg.Ldap, ldapRepoSupplier, userRoleRepo, roleRepo, l.logger)
|
||||||
|
|
||||||
userService := service.NewUser(
|
userService := service.NewUser(
|
||||||
userRepo,
|
userRepo,
|
||||||
userRoleRepo,
|
userRoleRepo,
|
||||||
@@ -83,12 +77,13 @@ func (l Locator) Config(
|
|||||||
tokenRepo,
|
tokenRepo,
|
||||||
auditService,
|
auditService,
|
||||||
txManager,
|
txManager,
|
||||||
|
ldapService,
|
||||||
tokenService,
|
tokenService,
|
||||||
cfg.IdleTimeoutMs,
|
cfg.IdleTimeoutMs,
|
||||||
l.logger,
|
l.logger,
|
||||||
)
|
)
|
||||||
authService := service.NewAuth(
|
authService := service.NewAuth(
|
||||||
userRepo, txManager, tokenService, oauthService, auditService, l.logger,
|
userRepo, txManager, tokenService, sudirService, auditService, l.logger,
|
||||||
cfg.AntiBruteforce.DelayLoginRequestInSec,
|
cfg.AntiBruteforce.DelayLoginRequestInSec,
|
||||||
cfg.AntiBruteforce.MaxInFlightLoginRequests,
|
cfg.AntiBruteforce.MaxInFlightLoginRequests,
|
||||||
)
|
)
|
||||||
@@ -96,16 +91,6 @@ func (l Locator) Config(
|
|||||||
|
|
||||||
permissionsService := service.NewPermission(cfg.Permissions)
|
permissionsService := service.NewPermission(cfg.Permissions)
|
||||||
|
|
||||||
uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings)
|
|
||||||
|
|
||||||
downloadService := service.NewDownload(
|
|
||||||
auditService,
|
|
||||||
userService,
|
|
||||||
tokenService,
|
|
||||||
roleService,
|
|
||||||
permissionsService,
|
|
||||||
)
|
|
||||||
|
|
||||||
userController := controller.NewUser(userService)
|
userController := controller.NewUser(userService)
|
||||||
customizationController := controller.NewCustomization(cfg.UiDesign)
|
customizationController := controller.NewCustomization(cfg.UiDesign)
|
||||||
authController := controller.NewAuth(authService, l.logger)
|
authController := controller.NewAuth(authService, l.logger)
|
||||||
@@ -114,12 +99,9 @@ func (l Locator) Config(
|
|||||||
auditController := controller.NewAudit(auditService)
|
auditController := controller.NewAudit(auditService)
|
||||||
roleController := controller.NewRole(roleService)
|
roleController := controller.NewRole(roleService)
|
||||||
permissionController := controller.NewPermissions(permissionsService)
|
permissionController := controller.NewPermissions(permissionsService)
|
||||||
uiSettingsController := controller.NewUiSettings(uiSettingsService)
|
|
||||||
downloadController := controller.NewDownload(downloadService)
|
|
||||||
|
|
||||||
wrapper := endpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true))
|
|
||||||
handler := routes.Handler(
|
handler := routes.Handler(
|
||||||
wrapper,
|
endpoint.DefaultWrapper(l.logger),
|
||||||
routes.Controllers{
|
routes.Controllers{
|
||||||
User: userController,
|
User: userController,
|
||||||
Customization: customizationController,
|
Customization: customizationController,
|
||||||
@@ -129,20 +111,19 @@ func (l Locator) Config(
|
|||||||
Audit: auditController,
|
Audit: auditController,
|
||||||
Role: roleController,
|
Role: roleController,
|
||||||
Permissions: permissionController,
|
Permissions: permissionController,
|
||||||
UiSettings: uiSettingsController,
|
|
||||||
Download: downloadController,
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
inactiveBlocker := inactive_worker.NewInactiveBlocker(
|
inactiveBlocker := inactive_worker.NewInactiveBlocker(
|
||||||
|
tokenRepo,
|
||||||
userRepo,
|
userRepo,
|
||||||
auditService,
|
auditService,
|
||||||
userRoleRepo,
|
userRoleRepo,
|
||||||
|
ldapService,
|
||||||
cfg.BlockInactiveWorker,
|
cfg.BlockInactiveWorker,
|
||||||
l.logger,
|
l.logger,
|
||||||
)
|
)
|
||||||
deleteOldAuditWorker := delete_old_audit_worker.NewService(l.logger, auditRepo, cfg.Audit.AuditTTl)
|
deleteOldAuditWorker := delete_old_audit_worker.NewService(l.logger, auditRepo, cfg.Audit.AuditTTl)
|
||||||
expireSessionWorker := session_worker.NewExpireSessionWorker(l.logger, txManager)
|
|
||||||
|
|
||||||
return Config{
|
return Config{
|
||||||
Handler: handler,
|
Handler: handler,
|
||||||
@@ -156,19 +137,6 @@ func (l Locator) Config(
|
|||||||
Concurrency: 1,
|
Concurrency: 1,
|
||||||
PollInterval: jobPollInterval,
|
PollInterval: jobPollInterval,
|
||||||
Handle: inactiveBlocker,
|
Handle: inactiveBlocker,
|
||||||
}, {
|
|
||||||
Queue: session_worker.QueueName,
|
|
||||||
Concurrency: 1,
|
|
||||||
PollInterval: jobPollInterval,
|
|
||||||
Handle: expireSessionWorker,
|
|
||||||
}},
|
}},
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l Locator) getOauthSettings(oauthAuth *conf.Oauth) (string, []conf.OauthClientConfig) {
|
|
||||||
if oauthAuth == nil {
|
|
||||||
return "", []conf.OauthClientConfig{}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return oauthAuth.Host, oauthAuth.Clients
|
|
||||||
}
|
}
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 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) {
|
|
||||||
if h == nil {
|
|
||||||
return "", errors.New("header is nil")
|
|
||||||
}
|
|
||||||
values := h.Values(key)
|
|
||||||
if len(values) == 0 {
|
|
||||||
return "", errors.Errorf("'%s' is expected in header", key)
|
|
||||||
}
|
|
||||||
return values[0], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// IntFromHeader extracts an integer value from header by key.
|
|
||||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
|
||||||
func IntFromHeader(key string, h http.Header) (int, error) {
|
|
||||||
value, err := StringFromHeader(key, h)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
intValue, err := strconv.Atoi(value)
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessagef(err, "parse '%s' to int", key)
|
|
||||||
}
|
|
||||||
return intValue, nil
|
|
||||||
}
|
|
||||||
+2
-2
@@ -7,11 +7,11 @@ grpcOuterAddress:
|
|||||||
grpcInnerAddress:
|
grpcInnerAddress:
|
||||||
ip: 0.0.0.0
|
ip: 0.0.0.0
|
||||||
port: 9007
|
port: 9007
|
||||||
moduleName: isp-admin-service
|
moduleName: msp-admin-service
|
||||||
infraServerPort: 9557
|
infraServerPort: 9557
|
||||||
|
|
||||||
logfile:
|
logfile:
|
||||||
path: /var/log/isp-admin-service/runtime.log
|
path: /var/log/msp-admin-service/runtime.log
|
||||||
maxSizeMb: 512
|
maxSizeMb: 512
|
||||||
maxBackups: 4
|
maxBackups: 4
|
||||||
compress: true
|
compress: true
|
||||||
@@ -20,10 +20,6 @@
|
|||||||
{
|
{
|
||||||
"event": "user_changed",
|
"event": "user_changed",
|
||||||
"name": "Изменение пользователя"
|
"name": "Изменение пользователя"
|
||||||
},
|
|
||||||
{
|
|
||||||
"event": "user_blocked",
|
|
||||||
"name": "Изменение статуса блокировки пользователя"
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"auditTTl": {
|
"auditTTl": {
|
||||||
|
|||||||
+30
-33
@@ -1,4 +1,3 @@
|
|||||||
//nolint:lll
|
|
||||||
package conf
|
package conf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -11,62 +10,53 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// nolint: gochecknoinits
|
// nolint: gochecknoinits
|
||||||
func init() {
|
func init() { //
|
||||||
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
|
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
|
||||||
t.Type = "string"
|
t.Type = "string"
|
||||||
t.Enum = []any{"debug", "info", "error", "fatal"}
|
t.Enum = []interface{}{"debug", "info", "error", "fatal"}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
type Remote struct {
|
type Remote struct {
|
||||||
Audit Audit `schema:"Настройки audit"`
|
Audit Audit
|
||||||
Database dbx.Config `schema:"Настройка подключения к БД"`
|
Database dbx.Config
|
||||||
ExpireSec int `validate:"required" schema:"Время жизни токена в секундах,in seconds"`
|
ExpireSec int `validate:"required" schema:"Время жизни токена в секундах,in seconds"`
|
||||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||||
|
//nolint:lll
|
||||||
IdleTimeoutMs int `schema:"Время бездействия пользователя,в милисекундах, после указанного времени пользователь будет разлогирован из интерфейса в браузере, по умолчанию отключено"`
|
IdleTimeoutMs int `schema:"Время бездействия пользователя,в милисекундах, после указанного времени пользователь будет разлогирован из интерфейса в браузере, по умолчанию отключено"`
|
||||||
Oauth *Oauth `schema:"OAuth авторизация"`
|
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||||
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
||||||
BlockInactiveWorker BlockInactiveWorker `validate:"required" schema:"Блокировка неактивных УЗ"`
|
BlockInactiveWorker BlockInactiveWorker `validate:"required" schema:"Блокировка неактивных УЗ"`
|
||||||
Permissions []Permission `schema:"Список разрешений"`
|
Permissions []Permission `schema:"Список разрешений"`
|
||||||
|
Ldap *Ldap `schema:"Настройки LDAP"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Audit struct {
|
type Audit struct {
|
||||||
EventSettings []AuditEventSetting `schema:"Маппинг событий"`
|
EventSettings []AuditEventSetting
|
||||||
AuditTTl AuditTTlSetting `schema:"Настройки TTL для audit"`
|
AuditTTl AuditTTlSetting
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuditTTlSetting struct {
|
type AuditTTlSetting struct {
|
||||||
TimeToLiveInMin int `validate:"required" schema:"TTL события в минутах"`
|
TimeToLiveInMin int `validate:"required"`
|
||||||
ExpireSyncPeriodInMin int `validate:"required" schema:"Интервал запуска воркера"`
|
ExpireSyncPeriodInMin int `validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuditEventSetting struct {
|
type AuditEventSetting struct {
|
||||||
Event string `schema:"Ключ события"`
|
Event string
|
||||||
Name string `schema:"Пользовательское название события"`
|
Name string
|
||||||
}
|
}
|
||||||
|
|
||||||
type UIDesign struct {
|
type UIDesign struct {
|
||||||
Name string `schema:"Название стенда"`
|
Name string `schema:"Название стенда"`
|
||||||
PrimaryColor string `schema:"Цвет в HEX,примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
PrimaryColor string `schema:"Цвет в HEX, примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Oauth struct {
|
type SudirAuth struct {
|
||||||
Host string `validate:"required" schema:"Базовый путь до методов, пример https://oauth.example.com"`
|
ClientId string `validate:"required"`
|
||||||
Clients []OauthClientConfig `validate:"omitempty,min=1" schema:"Настройка взаимодействия для логина по authCode"`
|
ClientSecret string `validate:"required"`
|
||||||
}
|
Host string `validate:"required" schema:"Хост, пример https://sudir.mos.ru"`
|
||||||
|
RedirectURI string `validate:"required"`
|
||||||
type OauthClientConfig struct {
|
|
||||||
ClientName string `validate:"required" schema:"Уникальное имя конфигурации клиента"`
|
|
||||||
ClientId string `validate:"required" schema:"Идентификатор клиента,выданный для basicAuth"`
|
|
||||||
ClientSecret string `validate:"required" schema:"Пароль клиента,выданный для basicAuth"`
|
|
||||||
RedirectURI string `validate:"required" schema:"URI для редиректа,передаётся в запросе токена в query"`
|
|
||||||
UiSetting *UiOauthSetting `schema:"Настройки OAuth для админки"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UiOauthSetting struct {
|
|
||||||
LoginEndpoint string `validate:"required" schema:"Эндпоинт для входа через OAuth в адмиинке,может содержать query параметры,client_id и redirect_uri добавляются автоматически"`
|
|
||||||
LogoutEndpoint string `validate:"required" schema:"Эндпоинт для выхода через OAuth в адмиинке"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type AntiBruteforce struct {
|
type AntiBruteforce struct {
|
||||||
@@ -80,6 +70,13 @@ type BlockInactiveWorker struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Permission struct {
|
type Permission struct {
|
||||||
Key string `schema:"Ключ прав"`
|
Key string
|
||||||
Name string `schema:"Пользовательское название"`
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Ldap struct {
|
||||||
|
Address string `validate:"required" schema:"Адрес LDAP"`
|
||||||
|
Username string `validate:"required" schema:"Пользователь сервисной УЗ"`
|
||||||
|
Password string `validate:"required" schema:"Пароль сервисной УЗ"`
|
||||||
|
BaseDn string `validate:"required"`
|
||||||
}
|
}
|
||||||
+1
-2
@@ -3,9 +3,8 @@ package conf_test
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/test/rct"
|
"github.com/txix-open/isp-kit/test/rct"
|
||||||
|
"msp-admin-service/conf"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestDefaultRemoteConfig(t *testing.T) {
|
func TestDefaultRemoteConfig(t *testing.T) {
|
||||||
|
|||||||
+40
-49
@@ -2,16 +2,15 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"google.golang.org/grpc/status"
|
||||||
"github.com/txix-open/isp-kit/http/apierrors"
|
"msp-admin-service/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuditService interface {
|
type AuditService interface {
|
||||||
All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error)
|
All(ctx context.Context, limit int, offset int) (*domain.AuditResponse, error)
|
||||||
Events(ctx context.Context) ([]domain.AuditEvent, error)
|
Events(ctx context.Context) ([]domain.AuditEvent, error)
|
||||||
SetEvents(ctx context.Context, req []domain.SetAuditEvent) error
|
SetEvents(ctx context.Context, req []domain.SetAuditEvent) error
|
||||||
}
|
}
|
||||||
@@ -27,61 +26,53 @@ func NewAudit(service AuditService) Audit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// All
|
// All
|
||||||
//
|
// @Tags log
|
||||||
// @Tags log
|
// @Summary Получение списка логов
|
||||||
// @Summary Получение списка логов
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.PageRequest true "Тело запроса"
|
||||||
// @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)"
|
// @Success 200 {object} domain.AuditResponse
|
||||||
// @Success 200 {object} domain.AuditResponse
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /log/all [POST]
|
||||||
// @Router /log/all [POST]
|
func (c Audit) All(ctx context.Context, req domain.PageRequest) (*domain.AuditResponse, error) {
|
||||||
func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) {
|
return c.service.All(ctx, req.Limit, req.Offset)
|
||||||
if req.Order == nil {
|
|
||||||
req.Order = &domain.OrderParams{
|
|
||||||
Field: domain.DefaultOrderField,
|
|
||||||
Type: domain.DefaultOrderType,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.service.All(ctx, req)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Events
|
// Events
|
||||||
//
|
// @Tags log
|
||||||
// @Tags log
|
// @Summary Получение списка логов
|
||||||
// @Summary Получение списка событий аудита
|
// @Description Возвращает полный список доступных событий аудита
|
||||||
// @Description Возвращает полный список доступных событий аудита
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.AuditResponse true "Тело запроса"
|
||||||
// @Success 200 {array} domain.AuditEvent
|
// @Success 200 {array} domain.AuditEvent
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Router /log/events [POST]
|
// @Failure 500 {object} domain.GrpcError
|
||||||
|
// @Router /log/events [POST]
|
||||||
func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) {
|
func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) {
|
||||||
return c.service.Events(ctx)
|
return c.service.Events(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetEvents
|
// SetEvents
|
||||||
//
|
// @Tags log
|
||||||
// @Tags log
|
// @Summary Получение списка логов
|
||||||
// @Summary Установить события аудита
|
// @Description Всегда возвращает полный список доступных событий аудита
|
||||||
// @Description Устанавливает (обновляет) набор активных событий аудита.
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.SetAuditEvent true "Тело запроса"
|
||||||
// @Param body body []domain.SetAuditEvent true "Список событий аудита для установки"
|
// @Success 200
|
||||||
// @Success 200 {object} map[string]interface{} "События успешно установлены"
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /log/set_events [POST]
|
||||||
// @Router /log/set_events [POST]
|
|
||||||
func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error {
|
func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error {
|
||||||
err := c.service.SetEvents(ctx, req)
|
err := c.service.SetEvents(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.As(err, &domain.UnknownAuditEventError{}):
|
case errors.As(err, &domain.UnknownAuditEventError{}):
|
||||||
return apierrors.New(http.StatusBadRequest, domain.UnknownAuditEventErrorCode, err.Error(), err)
|
return status.Error(codes.InvalidArgument, err.Error())
|
||||||
default:
|
default:
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
+58
-89
@@ -2,21 +2,21 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"isp-admin-service/auth"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/domain"
|
"github.com/txix-open/isp-kit/grpc"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/http/apierrors"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/metadata"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
"msp-admin-service/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
type authService interface {
|
type authService interface {
|
||||||
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
|
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
|
||||||
LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error)
|
LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error)
|
||||||
Logout(ctx context.Context, adminId int64, request *domain.LogoutRequest) error
|
Logout(ctx context.Context, adminId int64) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type Auth struct {
|
type Auth struct {
|
||||||
@@ -32,51 +32,23 @@ func NewAuth(authService authService, logger log.Logger) Auth {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Logout
|
// Logout
|
||||||
//
|
// @Tags auth
|
||||||
// @Tags auth
|
// @Summary Выход из авторизованной сессии
|
||||||
// @Summary Выход из авторизованной сессии
|
// @Description Выход из авторизованной сессии администрирования
|
||||||
// @Description Выход из авторизованной сессии администрирования
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Success 200
|
||||||
// @Success 200 {object} map[string]interface{} "Успешный выход"
|
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /auth/logout [POST]
|
||||||
// @Router /auth/logout [POST]
|
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
||||||
func (a Auth) Logout(ctx context.Context, r *http.Request) error {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.authService.Logout(ctx, adminId, nil)
|
err = a.authService.Logout(ctx, adminId)
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "logout")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LogoutWithReason
|
|
||||||
//
|
|
||||||
// @Tags auth
|
|
||||||
// @Summary Выход по бездействию из авторизованной сессии
|
|
||||||
// @Description Выход по бездействию из авторизованной сессии администрирования
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
|
||||||
// @Param body body domain.LogoutRequest true "Тело запроса"
|
|
||||||
// @Success 200 {object} map[string]interface{} "Успешный выход"
|
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
|
||||||
// @Failure 500 {object} apierrors.Error
|
|
||||||
// @Router /auth/logout_with_reason [POST]
|
|
||||||
func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error {
|
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = a.authService.Logout(ctx, adminId, &logoutRequest)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "logout")
|
return errors.WithMessage(err, "logout")
|
||||||
}
|
}
|
||||||
@@ -85,30 +57,28 @@ func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutR
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Login
|
// Login
|
||||||
//
|
// @Tags auth
|
||||||
// @Tags auth
|
// @Summary Авторизация по логину и паролю
|
||||||
// @Summary Авторизация по логину и паролю
|
// @Description Авторизация с получением токена администратора
|
||||||
// @Description Авторизация с получением токена администратора
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param body body domain.LoginRequest true "Тело запроса"
|
||||||
// @Param body body domain.LoginRequest true "Тело запроса"
|
// @Success 200 {object} domain.LoginResponse
|
||||||
// @Success 200 {object} domain.LoginResponse
|
// @Failure 400 {object} domain.GrpcError
|
||||||
// @Failure 400 {object} apierrors.Error
|
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
|
||||||
// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию"
|
// @Router /auth/login [POST]
|
||||||
// @Failure 500 {object} apierrors.Error
|
|
||||||
// @Router /auth/login [POST]
|
|
||||||
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
|
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
|
||||||
auth, err := a.authService.Login(ctx, authRequest)
|
auth, err := a.authService.Login(ctx, authRequest)
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrOauthAuthorization):
|
case errors.Is(err, domain.ErrSudirAuthorization):
|
||||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthAuthorizationCode, err.Error(), err)
|
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
||||||
case errors.Is(err, domain.ErrUnauthenticated):
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
a.logger.Error(ctx, err.Error())
|
a.logger.Error(ctx, err.Error())
|
||||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
return nil, status.Error(codes.Unauthenticated, "invalid credential")
|
||||||
case errors.Is(err, domain.ErrTooManyLoginRequests):
|
case errors.Is(err, domain.ErrTooManyLoginRequests):
|
||||||
return nil, apierrors.New(http.StatusTooManyRequests, domain.ErrTooManyLoginRequestsCode, err.Error(), err)
|
return nil, status.Error(codes.ResourceExhausted, "too many requests")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "login")
|
return nil, errors.WithMessage(err, "login")
|
||||||
default:
|
default:
|
||||||
@@ -116,43 +86,42 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoginWithOauth
|
// LoginWithSudir
|
||||||
//
|
// @Tags auth
|
||||||
// @Tags auth
|
// @Summary Авторизация по авторизационному коду от СУДИР
|
||||||
// @Summary Авторизация по авторизационному коду от OAuth
|
// @Description Авторизация с получением токена администратора
|
||||||
// @Description Авторизация с получением токена администратора.
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param body body domain.LoginSudirRequest true "Тело запроса"
|
||||||
// @Param body body domain.LoginOauthRequest true "Тело запроса"
|
// @Success 200 {object} domain.LoginResponse
|
||||||
// @Success 200 {object} domain.LoginResponse
|
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации"
|
||||||
// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере"
|
// @Failure 412 {object} domain.GrpcError "Авторизация СУДИР не настроена на сервере"
|
||||||
// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /auth/login_with_sudir [POST]
|
||||||
// @Router /auth/login_with_oauth [POST]
|
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
||||||
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
auth, err := a.authService.LoginWithSudir(ctx, request)
|
||||||
auth, err := a.authService.LoginWithOauth(ctx, request)
|
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrOauthIsMissed):
|
case errors.Is(err, domain.ErrSudirAuthIsMissed):
|
||||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthIsMissedCode, err.Error(), err)
|
return nil, status.Error(codes.FailedPrecondition, "sudir auth is not configured")
|
||||||
case errors.Is(err, domain.ErrUnauthenticated):
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "login with oauth")
|
return nil, errors.WithMessage(err, "login with sudir")
|
||||||
default:
|
default:
|
||||||
return auth, nil
|
return auth, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getAdminId(r *http.Request) (int64, error) {
|
func getAdminId(authData grpc.AuthData) (int64, error) {
|
||||||
token, err := auth.StringFromHeader(domain.AdminAuthIdHeader, r.Header)
|
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
return 0, status.Error(codes.InvalidArgument, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
adminId, err := strconv.Atoi(token)
|
adminId, err := strconv.Atoi(token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
return 0, status.Error(codes.InvalidArgument, "admin id is not a number")
|
||||||
}
|
}
|
||||||
|
|
||||||
return int64(adminId), nil
|
return int64(adminId), nil
|
||||||
|
|||||||
+14
-19
@@ -1,35 +1,30 @@
|
|||||||
package controller
|
package controller
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"isp-admin-service/conf"
|
"msp-admin-service/conf"
|
||||||
"isp-admin-service/domain"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Customization struct {
|
type Customization struct {
|
||||||
uiCfg domain.UIDesign
|
uiCfg conf.UIDesign
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCustomization(uiCfg conf.UIDesign) Customization {
|
func NewCustomization(uiCfg conf.UIDesign) Customization {
|
||||||
return Customization{
|
return Customization{
|
||||||
uiCfg: domain.UIDesign{
|
uiCfg: uiCfg,
|
||||||
Name: uiCfg.Name,
|
|
||||||
PrimaryColor: uiCfg.PrimaryColor,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUIDesign
|
// GetUIDesign
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Получение внешнего вида
|
||||||
// @Summary Получение внешнего вида
|
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Success 200 {object} conf.UIDesign
|
||||||
// @Success 200 {object} domain.UIDesign
|
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /user/get_design [POST]
|
||||||
// @Router /user/get_design [POST]
|
func (c Customization) GetUIDesign() (conf.UIDesign, error) {
|
||||||
func (c Customization) GetUIDesign() (domain.UIDesign, error) {
|
|
||||||
return c.uiCfg, nil
|
return c.uiCfg, nil
|
||||||
}
|
}
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DownloadService interface {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
type Download struct {
|
|
||||||
service DownloadService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDownload(service DownloadService) Download {
|
|
||||||
return Download{
|
|
||||||
service: service,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Users
|
|
||||||
//
|
|
||||||
// @Tags Download
|
|
||||||
// @Summary Скачать список пользователей в csv
|
|
||||||
// @Accept json
|
|
||||||
// @Produce text/csv
|
|
||||||
// @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.UsersPageRequest, w http.ResponseWriter) error {
|
|
||||||
err := c.service.DownloadUsers(ctx, req, w)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "download users")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sessions
|
|
||||||
//
|
|
||||||
// @Tags Download
|
|
||||||
// @Summary Скачать список сессий в csv
|
|
||||||
// @Accept json
|
|
||||||
// @Produce text/csv
|
|
||||||
// @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.SessionPageRequest, w http.ResponseWriter) error {
|
|
||||||
err := c.service.DownloadSessions(ctx, req, w)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "download sessions")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Audit
|
|
||||||
//
|
|
||||||
// @Tags Download
|
|
||||||
// @Summary Скачать журнал аудита в csv
|
|
||||||
// @Accept json
|
|
||||||
// @Produce text/csv
|
|
||||||
// @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.AuditPageRequest, w http.ResponseWriter) error {
|
|
||||||
err := c.service.DownloadAudit(ctx, req, w)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "download audit")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Roles
|
|
||||||
//
|
|
||||||
// @Tags Download
|
|
||||||
// @Summary Скачать матрицу ролей в csv
|
|
||||||
// @Accept json
|
|
||||||
// @Produce text/csv
|
|
||||||
// @Success 200
|
|
||||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
|
||||||
// @Router /role/download [POST]
|
|
||||||
func (c Download) Roles(ctx context.Context, w http.ResponseWriter) error {
|
|
||||||
err := c.service.DownloadRoles(ctx, w)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "download roles")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,7 @@ package controller
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"msp-admin-service/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
type permissionsService interface {
|
type permissionsService interface {
|
||||||
@@ -21,15 +21,13 @@ func NewPermissions(permissionsService permissionsService) Permissions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetPermissions
|
// GetPermissions
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Получить все разрашения
|
||||||
// @Summary Получить все разрешения
|
// @Description Получить все разрашения
|
||||||
// @Description Получить все разрешения
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Success 200 {array} domain.Permission
|
||||||
// @Success 200 {array} domain.Permission
|
// @Router /user/get_profile [POST]
|
||||||
// @Failure 500 {object} apierrors.Error
|
|
||||||
// @Router /user/get_permissions [POST]
|
|
||||||
func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission {
|
func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission {
|
||||||
return u.permissionsService.All(ctx)
|
return u.permissionsService.All(ctx)
|
||||||
}
|
}
|
||||||
+62
-66
@@ -2,16 +2,16 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"google.golang.org/grpc/codes"
|
||||||
"github.com/txix-open/isp-kit/http/apierrors"
|
"google.golang.org/grpc/status"
|
||||||
|
"msp-admin-service/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
type roleService interface {
|
type roleService interface {
|
||||||
All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error)
|
All(ctx context.Context) ([]domain.Role, error)
|
||||||
Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error)
|
Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error)
|
||||||
Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error)
|
Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error)
|
||||||
Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error
|
Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error
|
||||||
@@ -28,19 +28,18 @@ func NewRole(roleService roleService) Role {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// All
|
// All
|
||||||
//
|
// @Tags role
|
||||||
// @Tags role
|
// @Summary Список ролей
|
||||||
// @Summary Список ролей
|
// @Description Получить список ролей
|
||||||
// @Description Получить список ролей
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Success 200 {array} domain.Role
|
||||||
// @Success 200 {array} domain.Role
|
// @Failure 400 {object} domain.GrpcError
|
||||||
// @Failure 400 {object} apierrors.Error
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /role/all [POST]
|
||||||
// @Router /role/all [POST]
|
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
users, err := u.roleService.All(ctx)
|
||||||
users, err := u.roleService.All(ctx, req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get roles")
|
return nil, errors.WithMessage(err, "get roles")
|
||||||
}
|
}
|
||||||
@@ -49,21 +48,20 @@ func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CreateRole
|
// CreateRole
|
||||||
//
|
// @Tags user
|
||||||
// @Tags role
|
// @Summary Создать роль
|
||||||
// @Summary Создать роль
|
// @Description Создать роль
|
||||||
// @Description Создать роль
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
||||||
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
// @Success 200 {object} domain.User
|
||||||
// @Success 200 {object} domain.Role
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||||
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /role/create [POST]
|
||||||
// @Router /role/create [POST]
|
func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) {
|
||||||
func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -71,7 +69,7 @@ func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *h
|
|||||||
role, err := u.roleService.Create(ctx, req, adminId)
|
role, err := u.roleService.Create(ctx, req, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrAlreadyExists):
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "create role")
|
return nil, errors.WithMessage(err, "create role")
|
||||||
default:
|
default:
|
||||||
@@ -80,21 +78,20 @@ func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *h
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UpdateRole
|
// UpdateRole
|
||||||
//
|
// @Tags role
|
||||||
// @Tags role
|
// @Summary Обновить роль
|
||||||
// @Summary Обновить роль
|
// @Description Обновить данные существующую роль
|
||||||
// @Description Обновить данные существующую роль
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
||||||
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
// @Success 200 {object} domain.Role
|
||||||
// @Success 200 {object} domain.Role
|
// @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует"
|
||||||
// @Failure 404 {object} apierrors.Error "Роль с указанным id не существует"
|
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||||
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /role/update [POST]
|
||||||
// @Router /role/update [POST]
|
func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) {
|
||||||
func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -102,9 +99,9 @@ func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *h
|
|||||||
result, err := u.roleService.Update(ctx, req, adminId)
|
result, err := u.roleService.Update(ctx, req, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
return nil, status.Error(codes.NotFound, "role not found")
|
||||||
case errors.Is(err, domain.ErrAlreadyExists):
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "update role")
|
return nil, errors.WithMessage(err, "update role")
|
||||||
default:
|
default:
|
||||||
@@ -113,20 +110,19 @@ func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *h
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteRole
|
// DeleteRole
|
||||||
//
|
// @Tags role
|
||||||
// @Tags role
|
// @Summary Удалить роль
|
||||||
// @Summary Удалить роль
|
// @Description Удалить существующую роль
|
||||||
// @Description Удалить существующую роль
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
||||||
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
// @Success 200
|
||||||
// @Success 200
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /role/delete [POST]
|
||||||
// @Router /role/delete [POST]
|
func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error {
|
||||||
func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-24
@@ -3,10 +3,9 @@ package controller
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"msp-admin-service/domain"
|
||||||
"github.com/txix-open/isp-kit/http/apierrors"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type SecureService interface {
|
type SecureService interface {
|
||||||
@@ -25,16 +24,15 @@ func NewSecure(service SecureService) Secure {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Authenticate
|
// Authenticate
|
||||||
//
|
// @Tags secure
|
||||||
// @Tags secure
|
// @Summary Метод аутентификации токена
|
||||||
// @Summary Метод аутентификации токена
|
// @Description Проверяет токен и возвращает идентификатор администратора
|
||||||
// @Description Проверяет токен и возвращает идентификатор администратора
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
||||||
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
// @Success 200 {object} domain.SecureAuthResponse
|
||||||
// @Success 200 {object} domain.SecureAuthResponse
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /secure/authenticate [POST]
|
||||||
// @Router /secure/authenticate [POST]
|
|
||||||
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
|
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
|
||||||
adminId, err := s.service.Authenticate(ctx, req.Token)
|
adminId, err := s.service.Authenticate(ctx, req.Token)
|
||||||
switch {
|
switch {
|
||||||
@@ -62,16 +60,15 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Authorize
|
// Authorize
|
||||||
//
|
// @Tags secure
|
||||||
// @Tags secure
|
// @Summary Метод авторизации для администратора
|
||||||
// @Summary Метод авторизации для администратора
|
// @Description Проверяет наличие у администратора необходимого разрешения
|
||||||
// @Description Проверяет наличие у администратора необходимого разрешения
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
||||||
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
// @Success 200 {object} domain.SecureAuthzResponse
|
||||||
// @Success 200 {object} domain.SecureAuthzResponse
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /secure/authorize [POST]
|
||||||
// @Router /secure/authorize [POST]
|
|
||||||
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
|
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
|
||||||
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
|
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+24
-33
@@ -3,11 +3,11 @@ package controller
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"msp-admin-service/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
type SessionService interface {
|
type SessionService interface {
|
||||||
All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error)
|
All(ctx context.Context, limit int, offset int) (*domain.SessionResponse, error)
|
||||||
Revoke(ctx context.Context, id int) error
|
Revoke(ctx context.Context, id int) error
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,40 +22,31 @@ func NewSession(service SessionService) Session {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// All
|
// All
|
||||||
//
|
// @Tags session
|
||||||
// @Tags session
|
// @Summary Получение списка сессий
|
||||||
// @Summary Получение списка сессий
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.SessionRequest true "Тело запроса"
|
||||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
// @Success 200 {object} domain.PageRequest
|
||||||
// @Success 200 {object} domain.SessionResponse
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /session/all [POST]
|
||||||
// @Router /session/all [POST]
|
func (c Session) All(ctx context.Context, req domain.PageRequest) (*domain.SessionResponse, error) {
|
||||||
func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) {
|
return c.service.All(ctx, req.Limit, req.Offset)
|
||||||
if req.Order == nil {
|
|
||||||
req.Order = &domain.OrderParams{
|
|
||||||
Field: domain.DefaultOrderField,
|
|
||||||
Type: domain.DefaultOrderType,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.service.All(ctx, req)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Revoke
|
// Revoke
|
||||||
//
|
// @Tags session
|
||||||
// @Tags session
|
// @Summary Отзыв сессии
|
||||||
// @Summary Отзыв сессии
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
// @Success 200
|
||||||
// @Success 200
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /session/revoke [POST]
|
||||||
// @Router /session/revoke [POST]
|
|
||||||
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
|
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
|
||||||
return c.service.Revoke(ctx, req.Id)
|
return c.service.Revoke(ctx, req.Id)
|
||||||
}
|
}
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/http/apierrors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UiSettingsService interface {
|
|
||||||
OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type UiSettings struct {
|
|
||||||
service UiSettingsService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUiSettings(service UiSettingsService) UiSettings {
|
|
||||||
return UiSettings{
|
|
||||||
service: service,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// UiOauthSettings
|
|
||||||
//
|
|
||||||
// @Tags ui_settings
|
|
||||||
// @Summary Получение настроек для ui для авторизации через OAuth
|
|
||||||
// @Description Получение настроек для ui для авторизации через OAuth
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
|
||||||
// @Success 200 {object} domain.UiOauthSetting
|
|
||||||
// @Failure 400 {object} apierrors.Error
|
|
||||||
// @Failure 401 {object} apierrors.Error "Неизвестное название клиента"
|
|
||||||
// @Failure 500 {object} apierrors.Error
|
|
||||||
// @Router /ui_settings/oauth [POST]
|
|
||||||
func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
|
||||||
resp, err := c.service.OauthSettings(ctx, req)
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrUnknownClient):
|
|
||||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnknownClientCode, err.Error(), err)
|
|
||||||
case err != nil:
|
|
||||||
return nil, err
|
|
||||||
default:
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+115
-152
@@ -2,19 +2,18 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/http/apierrors"
|
"github.com/pkg/errors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc"
|
||||||
"isp-admin-service/domain"
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"msp-admin-service/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
type userService interface {
|
type userService interface {
|
||||||
GetProfileById(ctx context.Context, userId int64) (*domain.AdminUserShort, error)
|
GetProfileById(ctx context.Context, userId int64) (*domain.AdminUserShort, error)
|
||||||
GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error)
|
GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error)
|
||||||
GetAllUsers(ctx context.Context) (*domain.UsersResponse, error)
|
|
||||||
CreateUser(ctx context.Context, req domain.CreateUserRequest, adminId int64) (*domain.User, error)
|
CreateUser(ctx context.Context, req domain.CreateUserRequest, adminId int64) (*domain.User, error)
|
||||||
UpdateUser(ctx context.Context, req domain.UpdateUserRequest, adminId int64) (*domain.User, error)
|
UpdateUser(ctx context.Context, req domain.UpdateUserRequest, adminId int64) (*domain.User, error)
|
||||||
DeleteUsers(ctx context.Context, ids []int64, adminId int64) (int, error)
|
DeleteUsers(ctx context.Context, ids []int64, adminId int64) (int, error)
|
||||||
@@ -34,20 +33,19 @@ func NewUser(userService userService) User {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetProfile
|
// GetProfile
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Получить профиль
|
||||||
// @Summary Получить профиль
|
// @Description Получить данные профиля
|
||||||
// @Description Получить данные профиля
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Success 200 {object} domain.AdminUserShort
|
||||||
// @Success 200 {object} domain.AdminUserShort
|
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||||
// @Failure 401 {object} apierrors.Error "Невалидный токен"
|
// @Failure 404 {object} domain.GrpcError "Пользователя не существует"
|
||||||
// @Failure 404 {object} apierrors.Error "Пользователя не существует"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /user/get_profile [POST]
|
||||||
// @Router /user/get_profile [POST]
|
func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) {
|
||||||
func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -55,9 +53,9 @@ func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUse
|
|||||||
profile, err := u.userService.GetProfileById(ctx, adminId)
|
profile, err := u.userService.GetProfileById(ctx, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrUnauthenticated):
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
return nil, status.Error(codes.Unauthenticated, "user is blocked")
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
return nil, status.Error(codes.NotFound, "user not found")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "get profile")
|
return nil, errors.WithMessage(err, "get profile")
|
||||||
default:
|
default:
|
||||||
@@ -66,27 +64,19 @@ func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUse
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetUsers
|
// GetUsers
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Список пользователей
|
||||||
// @Summary Список пользователей
|
// @Description Получить список пользователей
|
||||||
// @Description Получить список пользователей
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.UsersRequest true "Тело запроса"
|
||||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
// @Success 200 {object} domain.UsersResponse
|
||||||
// @Success 200 {object} domain.UsersResponse
|
// @Failure 400 {object} domain.GrpcError
|
||||||
// @Failure 400 {object} apierrors.Error
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /user/get_users [POST]
|
||||||
// @Router /user/get_users [POST]
|
func (u User) GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error) {
|
||||||
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) {
|
users, err := u.userService.GetUsers(ctx, identities)
|
||||||
if req.Order == nil {
|
|
||||||
req.Order = &domain.OrderParams{
|
|
||||||
Field: domain.DefaultOrderField,
|
|
||||||
Type: domain.DefaultOrderType,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
users, err := u.userService.GetUsers(ctx, req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get users")
|
return nil, errors.WithMessage(err, "get users")
|
||||||
}
|
}
|
||||||
@@ -94,43 +84,21 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
|
|||||||
return users, nil
|
return users, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAllUsers
|
|
||||||
//
|
|
||||||
// @Tags user
|
|
||||||
// @Summary Список пользователей
|
|
||||||
// @Description Получить список пользователей
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
|
||||||
// @Success 200 {object} domain.UsersResponse
|
|
||||||
// @Failure 400 {object} apierrors.Error
|
|
||||||
// @Failure 500 {object} apierrors.Error
|
|
||||||
// @Router /user/get_all_users [POST]
|
|
||||||
func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
|
||||||
users, err := u.userService.GetAllUsers(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get all users")
|
|
||||||
}
|
|
||||||
|
|
||||||
return users, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateUser
|
// CreateUser
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Создать пользователя
|
||||||
// @Summary Создать пользователя
|
// @Description Создать пользователя
|
||||||
// @Description Создать пользователя
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
// @Success 200 {object} domain.User
|
||||||
// @Success 200 {object} domain.User
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||||
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /user/create_user [POST]
|
||||||
// @Router /user/create_user [POST]
|
func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) {
|
||||||
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -138,7 +106,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *h
|
|||||||
user, err := u.userService.CreateUser(ctx, req, adminId)
|
user, err := u.userService.CreateUser(ctx, req, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrAlreadyExists):
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "create user")
|
return nil, errors.WithMessage(err, "create user")
|
||||||
default:
|
default:
|
||||||
@@ -147,22 +115,21 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *h
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UpdateUser
|
// UpdateUser
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Обновить пользователя
|
||||||
// @Summary Обновить пользователя
|
// @Description Обновить данные существующего пользователя
|
||||||
// @Description Обновить данные существующего пользователя
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||||
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
// @Success 200 {object} domain.User
|
||||||
// @Success 200 {object} domain.User
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует"
|
||||||
// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует"
|
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||||
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /user/update_user [POST]
|
||||||
// @Router /user/update_user [POST]
|
func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) {
|
||||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -170,11 +137,11 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *h
|
|||||||
result, err := u.userService.UpdateUser(ctx, req, adminId)
|
result, err := u.userService.UpdateUser(ctx, req, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
return nil, status.Error(codes.NotFound, "user not found")
|
||||||
case errors.Is(err, domain.ErrInvalid):
|
case errors.Is(err, domain.ErrInvalid):
|
||||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrInvalidCode, err.Error(), err)
|
return nil, status.Error(codes.InvalidArgument, "user modification is not available")
|
||||||
case errors.Is(err, domain.ErrAlreadyExists):
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "update user")
|
return nil, errors.WithMessage(err, "update user")
|
||||||
default:
|
default:
|
||||||
@@ -183,20 +150,19 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *h
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteUser
|
// DeleteUser
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Удалить пользователя
|
||||||
// @Summary Удалить пользователя
|
// @Description Удалить существующего пользователя
|
||||||
// @Description Удалить существующего пользователя
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
// @Success 200 {object} domain.DeleteResponse
|
||||||
// @Success 200 {object} domain.DeleteResponse
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /user/delete_user [POST]
|
||||||
// @Router /user/delete_user [POST]
|
func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
|
||||||
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -210,19 +176,18 @@ func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesReques
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Block
|
// Block
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Метод блокировки/разблокировки пользователя
|
||||||
// @Summary Метод блокировки/разблокировки пользователя
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.IdRequest true "Тело запроса"
|
||||||
// @Param body body domain.IdRequest true "Тело запроса"
|
// @Success 200
|
||||||
// @Success 200
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /user/block_user [POST]
|
||||||
// @Router /user/block_user [POST]
|
func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error {
|
||||||
func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -235,34 +200,32 @@ func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Re
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetById
|
// GetById
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Метод получения данных по пользователю
|
||||||
// @Summary Метод получения данных по пользователю
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param body body domain.IdRequest true "Тело запроса"
|
||||||
// @Param body body domain.IdRequest true "Тело запроса"
|
// @Success 200 {object} domain.User
|
||||||
// @Success 200 {object} domain.User
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} apierrors.Error
|
// @Router /user/get_by_id [POST]
|
||||||
// @Router /user/get_by_id [POST]
|
|
||||||
func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) {
|
func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) {
|
||||||
return u.userService.GetById(ctx, identities.UserId)
|
return u.userService.GetById(ctx, identities.UserId)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ChangePassword
|
// ChangePassword
|
||||||
//
|
// @Tags user
|
||||||
// @Tags user
|
// @Summary Метод изменения пароля пользователя
|
||||||
// @Summary Метод изменения пароля пользователя
|
// @Accept json
|
||||||
// @Accept json
|
// @Produce json
|
||||||
// @Produce json
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
|
||||||
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
|
// @Success 200
|
||||||
// @Success 200
|
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль"
|
// @Failure 500 {object} apierrors.Error "внутренняя ошибка"
|
||||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка"
|
// @Router /user/change_password [POST]
|
||||||
// @Router /user/change_password [POST]
|
func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error {
|
||||||
func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error {
|
adminId, err := getAdminId(authData)
|
||||||
adminId, err := getAdminId(r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -270,7 +233,7 @@ func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordReque
|
|||||||
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
|
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrInvalidPassword):
|
case errors.Is(err, domain.ErrInvalidPassword):
|
||||||
return apierrors.New(http.StatusBadRequest, domain.ErrCodeInvalidPassword, err.Error(), err)
|
return apierrors.NewBusinessError(domain.ErrCodeInvalidPassword, "invalid password", err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return apierrors.NewInternalServiceError(err)
|
return apierrors.NewInternalServiceError(err)
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
package docs
|
|
||||||
|
|
||||||
import _ "embed"
|
|
||||||
|
|
||||||
// Embedded swagger files.
|
|
||||||
var (
|
|
||||||
//go:embed swagger.json
|
|
||||||
SwaggerJson []byte
|
|
||||||
)
|
|
||||||
-2396
File diff suppressed because it is too large.
Load diff
+1122
File diff suppressed because it is too large.
Load diff
+13
-22
@@ -5,38 +5,29 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Audit struct {
|
type Audit struct {
|
||||||
Id int // Идентификатор audit'а
|
Id int
|
||||||
UserId int // Идентификатор пользователя
|
UserId int
|
||||||
Message string // Сообщение
|
Message string
|
||||||
CreatedAt time.Time // Дата события
|
CreatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuditResponse struct {
|
type AuditResponse struct {
|
||||||
TotalCount int // Количество audit'ов
|
TotalCount int
|
||||||
Items []Audit // Список audit'ов
|
Items []Audit
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuditPageRequest struct {
|
type PageRequest struct {
|
||||||
LimitOffsetParams
|
Limit int `validate:"required"`
|
||||||
|
Offset int
|
||||||
Order *OrderParams // Параметры сортировки
|
|
||||||
Query *AuditQuery // Параметры выборки
|
|
||||||
}
|
|
||||||
|
|
||||||
type AuditQuery struct {
|
|
||||||
Id *int // Фильтр по идентификатору audit
|
|
||||||
UserId []int // Фильтр по идентификатору пользователей
|
|
||||||
Message *string // Фильтр по сообщению
|
|
||||||
CreatedAt *DateFromToParams // Фильтр по дате
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type SetAuditEvent struct {
|
type SetAuditEvent struct {
|
||||||
Event string // Название события
|
Event string
|
||||||
Enabled bool // Включено/выключено
|
Enabled bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuditEvent struct {
|
type AuditEvent struct {
|
||||||
Event string // Название события
|
Event string
|
||||||
Name string //
|
Name string
|
||||||
Enabled bool
|
Enabled bool
|
||||||
}
|
}
|
||||||
+3
-17
@@ -3,7 +3,7 @@ package domain
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -13,8 +13,8 @@ const (
|
|||||||
var (
|
var (
|
||||||
ErrNotFound = errors.New("not found")
|
ErrNotFound = errors.New("not found")
|
||||||
ErrUnauthenticated = errors.New("authentication failure")
|
ErrUnauthenticated = errors.New("authentication failure")
|
||||||
ErrOauthAuthorization = errors.New("user is authorized only with oauth")
|
ErrSudirAuthorization = errors.New("User is authorized only with SUDIR")
|
||||||
ErrOauthIsMissed = errors.New("oauth is not configured on the server")
|
ErrSudirAuthIsMissed = errors.New("SUDIR authorization is not configured on the server")
|
||||||
ErrInvalid = errors.New("entity is invalid")
|
ErrInvalid = errors.New("entity is invalid")
|
||||||
ErrAlreadyExists = errors.New("already exists")
|
ErrAlreadyExists = errors.New("already exists")
|
||||||
ErrTokenExpired = errors.New("token expired")
|
ErrTokenExpired = errors.New("token expired")
|
||||||
@@ -23,20 +23,6 @@ var (
|
|||||||
ErrUserIsBlocked = errors.New("user is blocked")
|
ErrUserIsBlocked = errors.New("user is blocked")
|
||||||
ErrNoActionRequired = errors.New("no action required")
|
ErrNoActionRequired = errors.New("no action required")
|
||||||
ErrInvalidPassword = errors.New("invalid password")
|
ErrInvalidPassword = errors.New("invalid password")
|
||||||
ErrUnknownClient = errors.New("unknown client")
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
UnknownAuditEventErrorCode = 601
|
|
||||||
ErrOauthAuthorizationCode = 602
|
|
||||||
ErrUnauthenticatedCode = 603
|
|
||||||
ErrTooManyLoginRequestsCode = 604
|
|
||||||
ErrOauthIsMissedCode = 605
|
|
||||||
ErrAlreadyExistsCode = 606
|
|
||||||
ErrNotFoundCode = 607
|
|
||||||
ErrUnknownClientCode = 608
|
|
||||||
ErrInvalidCode = 609
|
|
||||||
ErrInvalidPasswordCode = 610
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type UnknownAuditEventError struct {
|
type UnknownAuditEventError struct {
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
type GrpcError struct {
|
||||||
|
ErrorMessage string `json:"errorMessage"`
|
||||||
|
ErrorCode string `json:"errorCode"`
|
||||||
|
Details []interface{} `json:"details"`
|
||||||
|
}
|
||||||
+8
-13
@@ -1,3 +1,4 @@
|
|||||||
|
// nolint:tagliatelle
|
||||||
package domain
|
package domain
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -5,23 +6,17 @@ const (
|
|||||||
AdminAuthIdHeader = "x-admin-id"
|
AdminAuthIdHeader = "x-admin-id"
|
||||||
)
|
)
|
||||||
|
|
||||||
type LogoutRequest struct {
|
|
||||||
Reason string // Причина выхода
|
|
||||||
}
|
|
||||||
|
|
||||||
type LoginRequest struct {
|
type LoginRequest struct {
|
||||||
Email string `validate:"required"` // Электронная почта
|
Email string `validate:"required"`
|
||||||
Password string ` validate:"required"` // Пароль
|
Password string ` validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoginOauthRequest struct {
|
type LoginSudirRequest struct {
|
||||||
AuthCode string `validate:"required"` // Код для авторизации у OAuth-провайдера
|
AuthCode string `validate:"required"`
|
||||||
ClientName string `validate:"required"` // Уникальное имя конфигурации клиента
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint:tagliatelle,godoclint
|
|
||||||
type LoginResponse struct {
|
type LoginResponse struct {
|
||||||
Token string // Токен
|
Token string
|
||||||
Expired string `json:",omitempty"` // Дата истечения токена
|
Expired string `json:",omitempty"`
|
||||||
HeaderName string // Названия заголовка для передачи токена
|
HeaderName string
|
||||||
}
|
}
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
const (
|
|
||||||
DefaultOrderField = "created_at"
|
|
||||||
DefaultOrderType = "desc"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LimitOffsetParams struct {
|
|
||||||
Limit uint64 `validate:"required"` // Максимальное количество записей
|
|
||||||
Offset uint64 // Отступ для выборки
|
|
||||||
}
|
|
||||||
|
|
||||||
type OrderParams struct {
|
|
||||||
Field string // Поле сортировки
|
|
||||||
Type string `validate:"oneof=asc desc ASC DESC"` // Порядок сортировки
|
|
||||||
}
|
|
||||||
|
|
||||||
type DateFromToParams struct {
|
|
||||||
From time.Time `validate:"required"` // Дата с
|
|
||||||
To time.Time `validate:"required"` // Дата до
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package domain
|
package domain
|
||||||
|
|
||||||
type Permission struct {
|
type Permission struct {
|
||||||
Key string // Ключ прав
|
Key string
|
||||||
Name string // Пользовательское название
|
Name string
|
||||||
}
|
}
|
||||||
+19
-26
@@ -5,39 +5,32 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Role struct {
|
type Role struct {
|
||||||
Id int // Идентификатор роли
|
Id int
|
||||||
Name string // Название роли
|
Name string
|
||||||
ExternalGroup string // Внешнее название группы
|
ExternalGroup string
|
||||||
ApplicationGroup string // Группа приложений
|
ChangeMessage string
|
||||||
ChangeMessage string // Причина изменений
|
Permissions []string
|
||||||
Permissions []string // Набор прав
|
Immutable bool
|
||||||
Immutable bool
|
Exclusive bool
|
||||||
Exclusive bool
|
CreatedAt time.Time
|
||||||
CreatedAt time.Time // Дата создания
|
UpdatedAt time.Time
|
||||||
UpdatedAt time.Time // Дата обновления
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateRoleRequest struct {
|
type CreateRoleRequest struct {
|
||||||
Name string // Название роли
|
Name string
|
||||||
ExternalGroup string // Внешнее название группы
|
ExternalGroup string
|
||||||
ApplicationGroup string // Группа приложений
|
ChangeMessage string
|
||||||
ChangeMessage string // Причина изменений
|
Permissions []string
|
||||||
Permissions []string // Набор прав
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateRoleRequest struct {
|
type UpdateRoleRequest struct {
|
||||||
Id int // Идентификатор роли
|
Id int
|
||||||
Name string // Название роли
|
Name string
|
||||||
ExternalGroup string // Внешнее название группы
|
ExternalGroup string
|
||||||
ApplicationGroup string // Группа приложений
|
ChangeMessage string
|
||||||
ChangeMessage string // Причина изменений
|
Permissions []string
|
||||||
Permissions []string // Набор прав
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type DeleteRoleRequest struct {
|
type DeleteRoleRequest struct {
|
||||||
Id int // Идентификатор роли
|
Id int
|
||||||
}
|
|
||||||
|
|
||||||
type RoleAllRequest struct {
|
|
||||||
ApplicationGroup *string `validate:"omitnil,min=1"` // Фильтр по группе приложений
|
|
||||||
}
|
}
|
||||||
+7
-7
@@ -1,20 +1,20 @@
|
|||||||
package domain
|
package domain
|
||||||
|
|
||||||
type SecureAuthRequest struct {
|
type SecureAuthRequest struct {
|
||||||
Token string // Токен
|
Token string
|
||||||
}
|
}
|
||||||
|
|
||||||
type SecureAuthResponse struct {
|
type SecureAuthResponse struct {
|
||||||
Authenticated bool // Флаг успешной аутентикации
|
Authenticated bool
|
||||||
ErrorReason string // Причина ошибки
|
ErrorReason string
|
||||||
AdminId int64 // Идентификатор администратора
|
AdminId int64
|
||||||
}
|
}
|
||||||
|
|
||||||
type SecureAuthzRequest struct {
|
type SecureAuthzRequest struct {
|
||||||
AdminId int // Идентификатор администратора
|
AdminId int
|
||||||
Permission string // Роль
|
Permission string
|
||||||
}
|
}
|
||||||
|
|
||||||
type SecureAuthzResponse struct {
|
type SecureAuthzResponse struct {
|
||||||
Authorized bool // Флаг успешноЙ авторизации
|
Authorized bool
|
||||||
}
|
}
|
||||||
+13
-46
@@ -4,57 +4,24 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
SessionStatusAllowed = "ALLOWED"
|
|
||||||
SessionStatusAllowedRus = "Активная"
|
|
||||||
|
|
||||||
SessionStatusExpired = "EXPIRED"
|
|
||||||
SessionStatusExpiredRus = "Истекшая"
|
|
||||||
|
|
||||||
SessionStatusRevoked = "REVOKED"
|
|
||||||
SessionStatusRevokedRus = "Отмененная"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Session struct {
|
type Session struct {
|
||||||
Id int // Идентификатор сессии
|
Id int
|
||||||
UserId int // Идентификатор пользоватеккля
|
UserId int
|
||||||
Status string // Статус сессии
|
Status string
|
||||||
ExpiredAt time.Time // Дата протухания сессии
|
ExpiredAt time.Time
|
||||||
CreatedAt time.Time // Дата создания сессии
|
CreatedAt time.Time
|
||||||
}
|
|
||||||
|
|
||||||
type SessionPageRequest struct {
|
|
||||||
LimitOffsetParams
|
|
||||||
|
|
||||||
Order *OrderParams // Параметры сортировки
|
|
||||||
Query *SessionQuery // Параметры выборки
|
|
||||||
}
|
|
||||||
|
|
||||||
type SessionQuery struct {
|
|
||||||
Id *int // Фильтр по идентификатору сессии
|
|
||||||
UserId []int // Фильтр по идентификаторам пользователей
|
|
||||||
Status []string // Фильтр по статусам
|
|
||||||
CreatedAt *DateFromToParams // Фильтр по дате создания
|
|
||||||
ExpiredAt *DateFromToParams // Фильтр по дате протухания
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type SessionResponse struct {
|
type SessionResponse struct {
|
||||||
TotalCount int // Количество сессий
|
TotalCount int
|
||||||
Items []Session // Список сессий
|
Items []Session
|
||||||
|
}
|
||||||
|
|
||||||
|
type SessionRequest struct {
|
||||||
|
Limit int
|
||||||
|
Offset int
|
||||||
}
|
}
|
||||||
|
|
||||||
type RevokeRequest struct {
|
type RevokeRequest struct {
|
||||||
Id int `validate:"required"` // Идентификатор сессии
|
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 ""
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
type UIDesign struct {
|
|
||||||
Name string // Название ui
|
|
||||||
PrimaryColor string `example:"#ff4d4f"` // Цвет в HEX
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
type ClientNameRequest struct {
|
|
||||||
ClientName string `validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UiOauthSetting struct {
|
|
||||||
LoginUrl string // URL для получения authCode для авторизации через OAuth
|
|
||||||
LogoutUrl string // URL для завершения сессии
|
|
||||||
}
|
|
||||||
+41
-53
@@ -5,83 +5,71 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
Id int64 // Идентификатор пользователя
|
Id int64
|
||||||
Roles []int // Список идентификаторов ролей
|
Roles []int
|
||||||
FirstName string // Имя
|
FirstName string
|
||||||
LastName string // Фамилия
|
LastName string
|
||||||
FullName string // ФИО
|
Email string
|
||||||
Email string // Электронная почта
|
Description string
|
||||||
Description string // Описание
|
Blocked bool
|
||||||
Blocked bool // Флаг блокировки
|
LastSessionCreatedAt *time.Time
|
||||||
LastSessionCreatedAt *time.Time // Дата создания последней сессии
|
UpdatedAt time.Time
|
||||||
UpdatedAt time.Time // Дата обновлёния
|
CreatedAt time.Time
|
||||||
CreatedAt time.Time // Дата создания
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UsersResponse struct {
|
type UsersResponse struct {
|
||||||
Items []User // Список пользователей
|
Items []User
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserQuery struct {
|
type UsersRequest struct {
|
||||||
Id *int // Фильтр по идентификатору пользователя
|
Ids []int64
|
||||||
UserId []int // Фильтр по идентификаторам пользователя
|
Offset int
|
||||||
Description *string // Фильтр по описанию
|
Limit int
|
||||||
Email *string // Фильтр по электроннйо почты
|
Email string
|
||||||
Roles []int // Фильтр по ролям
|
|
||||||
LastSessionCreatedAt *DateFromToParams // Фильтр по дате создания последней сессии
|
|
||||||
}
|
|
||||||
|
|
||||||
type UsersPageRequest struct {
|
|
||||||
LimitOffsetParams
|
|
||||||
|
|
||||||
Order *OrderParams // Параметры сортировки
|
|
||||||
Query *UserQuery // Параметры выборки
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type AdminUserShort struct {
|
type AdminUserShort struct {
|
||||||
FirstName string // Имя
|
FirstName string
|
||||||
LastName string // Фамилия
|
LastName string
|
||||||
FullName string // ФИО
|
Email string `validate:"required"`
|
||||||
Email string `validate:"required"` // Электронный адрес
|
Role string
|
||||||
Role string // Название роли
|
Roles []int
|
||||||
Roles []int // Список идентификаторов ролей
|
Permissions []string
|
||||||
RoleNames []string // Список названия ролей
|
IdleTimeoutMs int
|
||||||
Permissions []string // Список прав
|
|
||||||
IdleTimeoutMs int // Время бездействия пользователя в мс
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateUserRequest struct {
|
type CreateUserRequest struct {
|
||||||
Roles []int // Список идентификаторов ролей
|
Roles []int
|
||||||
FirstName string // Имя
|
FirstName string
|
||||||
LastName string // Фамилия
|
LastName string
|
||||||
Email string `validate:"required"` // Электронный адрес
|
Email string `validate:"required"`
|
||||||
Password string `validate:"required"` // Пароль
|
Password string `validate:"required"`
|
||||||
Description string // Описание
|
Description string
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateUserRequest struct {
|
type UpdateUserRequest struct {
|
||||||
Id int64 `validate:"required"` // Идентификатор пользователя
|
Id int64 `validate:"required"`
|
||||||
Roles []int // Список идентификаторов ролей
|
Roles []int
|
||||||
FirstName string // Имя
|
FirstName string
|
||||||
LastName string // Фамилия
|
LastName string
|
||||||
Email string // Электронный адрес
|
Email string
|
||||||
Description string // Описание
|
Description string
|
||||||
Blocked bool // Флаг блокировки
|
Blocked bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type DeleteResponse struct {
|
type DeleteResponse struct {
|
||||||
Deleted int // Количество удалённых УЗ
|
Deleted int
|
||||||
}
|
}
|
||||||
|
|
||||||
type IdentitiesRequest struct {
|
type IdentitiesRequest struct {
|
||||||
Ids []int64 `validate:"required"` // Список идентификаторов
|
Ids []int64 `validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type IdRequest struct {
|
type IdRequest struct {
|
||||||
UserId int `validate:"required"` // Идентификато пользователя
|
UserId int `validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ChangePasswordRequest struct {
|
type ChangePasswordRequest struct {
|
||||||
OldPassword string `validate:"required"` // Старый пароль
|
OldPassword string `validate:"required"`
|
||||||
NewPassword string `validate:"required"` // Новый пароль
|
NewPassword string `validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,6 @@ const (
|
|||||||
EventUserChanged = "user_changed"
|
EventUserChanged = "user_changed"
|
||||||
EventUserPasswordChanged = "success_change_password"
|
EventUserPasswordChanged = "success_change_password"
|
||||||
EventErrorPasswordChange = "error_change_password"
|
EventErrorPasswordChange = "error_change_password"
|
||||||
EventUserBlocked = "user_blocked"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuditEvent struct {
|
type AuditEvent struct {
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
package entity
|
|
||||||
|
|
||||||
const (
|
|
||||||
SessionStatusAllowed = "ALLOWED"
|
|
||||||
SessionStatusAllowedRus = "Активная"
|
|
||||||
|
|
||||||
SessionStatusExpired = "EXPIRED"
|
|
||||||
SessionStatusExpiredRus = "Истекшая"
|
|
||||||
|
|
||||||
SessionStatusRevoked = "REVOKED"
|
|
||||||
SessionStatusRevokedRus = "Отмененная"
|
|
||||||
)
|
|
||||||
|
|
||||||
func AuditColumnNames() []string {
|
|
||||||
return []string{"Пользователь", "Время события", "Действие"}
|
|
||||||
}
|
|
||||||
|
|
||||||
func SessionColumnNames() []string {
|
|
||||||
return []string{"Пользователь", "Идентификатор", "Дата начала сессии", "Дата окончания сессии", "Статус"}
|
|
||||||
}
|
|
||||||
|
|
||||||
func UserColumnNames() []string {
|
|
||||||
return []string{"id", "Пользователь", "Описание", "Email", "Роль", "Последняя сессия"}
|
|
||||||
}
|
|
||||||
|
|
||||||
func RoleColumnNames() []string {
|
|
||||||
return []string{"Действие", "Ключ в системе"}
|
|
||||||
}
|
|
||||||
+8
-9
@@ -13,15 +13,14 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Role struct {
|
type Role struct {
|
||||||
Id int
|
Id int
|
||||||
Name string
|
Name string
|
||||||
ExternalGroup string
|
ExternalGroup string
|
||||||
ApplicationGroup string
|
Permissions PermList
|
||||||
Permissions PermList
|
Immutable bool
|
||||||
Immutable bool
|
Exclusive bool
|
||||||
Exclusive bool
|
CreatedAt time.Time
|
||||||
CreatedAt time.Time
|
UpdatedAt time.Time
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type PermList []string
|
type PermList []string
|
||||||
|
|||||||
@@ -1,41 +1,31 @@
|
|||||||
|
// nolint:tagliatelle,errname
|
||||||
package entity
|
package entity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ClientSetting struct {
|
type SudirAuthError struct {
|
||||||
AuthCode string
|
|
||||||
ClientId string
|
|
||||||
ClientSecret string
|
|
||||||
RedirectURI string
|
|
||||||
}
|
|
||||||
|
|
||||||
// nolint:tagliatelle,godoclint
|
|
||||||
type OauthAuthError struct {
|
|
||||||
ErrorName string `json:"error"`
|
ErrorName string `json:"error"`
|
||||||
ErrorDescription string `json:"error_description"`
|
ErrorDescription string `json:"error_description"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *OauthAuthError) Error() string {
|
func (s *SudirAuthError) Error() string {
|
||||||
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint:tagliatelle,errname,godoclint
|
type SudirUserResponse struct {
|
||||||
type OauthUserResponse struct {
|
*SudirAuthError
|
||||||
*OauthAuthError
|
|
||||||
|
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Groups []string `json:"groups"`
|
Groups []string `json:"groups"`
|
||||||
Sub string `json:"sub"`
|
Sub string `json:"sub"`
|
||||||
GivenName string `json:"given_name"`
|
GivenName string `json:"given_name"`
|
||||||
FamilyName string `json:"family_name"`
|
FamilyName string `json:"family_name"`
|
||||||
Name string `json:"name"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint:tagliatelle,errname,godoclint
|
type SudirTokenResponse struct {
|
||||||
type OauthTokenResponse struct {
|
*SudirAuthError
|
||||||
*OauthAuthError
|
|
||||||
|
|
||||||
IdToken string `json:"id_token"`
|
IdToken string `json:"id_token"`
|
||||||
AccessToken string `json:"access_token"`
|
AccessToken string `json:"access_token"`
|
||||||
+12
-18
@@ -3,36 +3,30 @@ package entity
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
OauthUserId *string
|
SudirUserId *string
|
||||||
Id int64
|
Id int64
|
||||||
Roles []int
|
FirstName string
|
||||||
FirstName string
|
LastName string
|
||||||
LastName string
|
Description string
|
||||||
FullName string
|
Email string
|
||||||
Description string
|
Password string
|
||||||
Email string
|
Blocked bool
|
||||||
Password string
|
UpdatedAt time.Time
|
||||||
Blocked bool
|
CreatedAt time.Time
|
||||||
LastActiveAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
CreatedAt time.Time
|
|
||||||
LastSessionCreatedAt *time.Time
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type OauthUser struct {
|
type SudirUser struct {
|
||||||
RoleIds []int
|
RoleIds []int
|
||||||
OauthUserId string
|
SudirUserId string
|
||||||
FirstName string
|
FirstName string
|
||||||
LastName string
|
LastName string
|
||||||
Email string
|
Email string
|
||||||
Description string
|
Description string
|
||||||
FullName string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateUser struct {
|
type UpdateUser struct {
|
||||||
FirstName string
|
FirstName string
|
||||||
LastName string
|
LastName string
|
||||||
FullName string
|
|
||||||
Email string
|
Email string
|
||||||
Description string
|
Description string
|
||||||
}
|
}
|
||||||
@@ -1,86 +1,85 @@
|
|||||||
module isp-admin-service
|
module msp-admin-service
|
||||||
|
|
||||||
go 1.27
|
go 1.24
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Masterminds/squirrel v1.5.4
|
github.com/Masterminds/squirrel v1.5.4
|
||||||
|
github.com/go-ldap/ldap/v3 v3.4.8
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/iancoleman/strcase v0.3.0
|
github.com/pkg/errors v0.9.1
|
||||||
github.com/stretchr/testify v1.12.1
|
github.com/stretchr/testify v1.10.0
|
||||||
github.com/txix-open/bgjob v1.6.0
|
github.com/txix-open/bgjob v1.5.0
|
||||||
github.com/txix-open/isp-kit v1.76.0
|
github.com/txix-open/isp-kit v1.48.1
|
||||||
github.com/txix-open/jsonschema v1.3.0
|
github.com/txix-open/jsonschema v1.3.0
|
||||||
golang.org/x/crypto v0.59.0
|
golang.org/x/crypto v0.38.0
|
||||||
golang.org/x/sync v0.25.0
|
golang.org/x/sync v0.14.0
|
||||||
|
google.golang.org/grpc v1.72.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
||||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||||
github.com/beorn7/perks v1.0.1 // indirect
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
github.com/buger/jsonparser v1.6.1 // indirect
|
github.com/buger/jsonparser v1.1.1 // indirect
|
||||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
github.com/coder/websocket v1.8.15 // indirect
|
github.com/coder/websocket v1.8.13 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/getsentry/sentry-go v0.50.0 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
|
||||||
github.com/go-faker/faker/v4 v4.12.0 // indirect
|
github.com/getsentry/sentry-go v0.32.0 // indirect
|
||||||
github.com/go-logr/logr v1.4.4 // indirect
|
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
|
||||||
|
github.com/go-logr/logr v1.4.2 // indirect
|
||||||
github.com/go-logr/stdr v1.2.2 // indirect
|
github.com/go-logr/stdr v1.2.2 // indirect
|
||||||
github.com/go-playground/locales v0.14.2 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.2 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect
|
||||||
|
github.com/iancoleman/strcase v0.3.0 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/pgx/v5 v5.13.0 // indirect
|
github.com/jackc/pgx/v5 v5.7.4 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.4 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/julienschmidt/httprouter v1.3.0 // indirect
|
|
||||||
github.com/klauspost/compress v1.20.4 // indirect
|
|
||||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||||
github.com/leodido/go-urn v1.5.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/mailru/easyjson v0.9.2 // indirect
|
github.com/mailru/easyjson v0.9.0 // indirect
|
||||||
github.com/mfridman/interpolate v0.2.0 // indirect
|
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
github.com/pandatix/go-abnf v0.5.5 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/pressly/goose/v3 v3.30.1 // indirect
|
github.com/pressly/goose/v3 v3.24.2 // indirect
|
||||||
github.com/prometheus/client_golang v1.25.0 // indirect
|
github.com/prometheus/client_golang v1.22.0 // indirect
|
||||||
github.com/prometheus/client_model v0.6.3 // indirect
|
github.com/prometheus/client_model v0.6.2 // indirect
|
||||||
github.com/prometheus/common v0.74.0 // indirect
|
github.com/prometheus/common v0.63.0 // indirect
|
||||||
github.com/prometheus/procfs v0.23.0 // indirect
|
github.com/prometheus/procfs v0.16.1 // indirect
|
||||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
github.com/sethvargo/go-retry v0.3.0 // indirect
|
||||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
|
||||||
github.com/txix-open/bellows v1.2.0 // indirect
|
github.com/txix-open/bellows v1.2.0 // indirect
|
||||||
github.com/txix-open/etp/v4 v4.1.3 // indirect
|
github.com/txix-open/etp/v4 v4.0.1 // indirect
|
||||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect
|
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
|
||||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
|
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.60.0 // indirect
|
||||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
go.opentelemetry.io/otel v1.35.0 // indirect
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 // indirect
|
||||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
go.opentelemetry.io/otel/metric v1.35.0 // indirect
|
||||||
go.opentelemetry.io/otel/metric v1.47.0 // indirect
|
go.opentelemetry.io/otel/sdk v1.35.0 // indirect
|
||||||
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
|
go.opentelemetry.io/otel/trace v1.35.0 // indirect
|
||||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
go.opentelemetry.io/proto/otlp v1.6.0 // indirect
|
||||||
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
|
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
go.uber.org/zap v1.28.0 // indirect
|
go.uber.org/zap v1.27.0 // indirect
|
||||||
go.yaml.in/yaml/v3 v3.0.6 // indirect
|
golang.org/x/net v0.40.0 // indirect
|
||||||
golang.org/x/net v0.63.0 // indirect
|
golang.org/x/sys v0.33.0 // indirect
|
||||||
golang.org/x/sys v0.50.0 // indirect
|
golang.org/x/text v0.25.0 // indirect
|
||||||
golang.org/x/text v0.44.0 // indirect
|
google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2 // indirect
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20250505200425-f936aa4a68b2 // indirect
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
|
google.golang.org/protobuf v1.36.6 // indirect
|
||||||
google.golang.org/grpc v1.85.0 // indirect
|
|
||||||
google.golang.org/protobuf v1.36.12 // indirect
|
|
||||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
@@ -1,50 +1,58 @@
|
|||||||
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
|
||||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||||
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
|
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
|
||||||
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
|
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
|
||||||
|
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
|
||||||
|
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
|
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
||||||
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
|
||||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
|
github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
|
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
|
||||||
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
|
github.com/getsentry/sentry-go v0.32.0 h1:YKs+//QmwE3DcYtfKRH8/KyOOF/I6Qnx7qYGNHCGmCY=
|
||||||
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
|
github.com/getsentry/sentry-go v0.32.0/go.mod h1:CYNcMMz73YigoHljQRG+qPF+eMq8gG72XcGN/p71BAY=
|
||||||
|
github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=
|
||||||
|
github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||||
github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
|
github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ=
|
||||||
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk=
|
||||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
|
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
|
||||||
|
github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA=
|
||||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||||
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
|
github.com/go-sql-driver/mysql v1.9.1 h1:FrjNGn/BsJQjVRuSa8CBrM5BWA9BWoXXat3KrtSb/iI=
|
||||||
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
github.com/go-sql-driver/mysql v1.9.1/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
@@ -52,26 +60,43 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
|
|||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
|
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
|
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo=
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI=
|
||||||
|
github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||||
|
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
|
||||||
|
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||||
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
|
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
|
||||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
|
||||||
github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
|
||||||
|
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
|
||||||
|
github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=
|
||||||
|
github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM=
|
||||||
|
github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg=
|
||||||
|
github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo=
|
||||||
|
github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o=
|
||||||
|
github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg=
|
||||||
|
github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8=
|
||||||
|
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
|
||||||
|
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
|
||||||
|
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
||||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||||
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
|
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||||
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
@@ -82,18 +107,18 @@ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq
|
|||||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
|
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
|
||||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
|
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
|
||||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
|
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
|
||||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
|
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
|
||||||
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
|
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||||
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
|
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
|
||||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
@@ -103,62 +128,61 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
|||||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||||
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
|
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||||
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
|
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||||
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
|
|
||||||
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
|
|
||||||
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
||||||
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
||||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
|
github.com/pressly/goose/v3 v3.24.2 h1:c/ie0Gm8rnIVKvnDQ/scHErv46jrDv9b4I0WRcFJzYU=
|
||||||
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
|
github.com/pressly/goose/v3 v3.24.2/go.mod h1:kjefwFB0eR4w30Td2Gj2Mznyw94vSP+2jJYkOVNbD1k=
|
||||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
|
||||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
|
||||||
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
|
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||||
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
|
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||||
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
|
github.com/prometheus/common v0.63.0 h1:YR/EIY1o3mEFP/kZCD7iDMnLPlGyuU2Gb3HIcXnA98k=
|
||||||
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
|
github.com/prometheus/common v0.63.0/go.mod h1:VVFF/fBIoToEnWRVkYoXEkq3R3paCoxG9PXP74SnV18=
|
||||||
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
|
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||||
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
|
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||||
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
|
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||||
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
|
||||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
|
||||||
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
|
|
||||||
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
|
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
|
||||||
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
|
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
|
||||||
github.com/txix-open/bgjob v1.6.0 h1:Vwj9cAsIhMrHPKRZVxfg6mHqE9LI/atDCq1aeihH3+I=
|
github.com/txix-open/bgjob v1.5.0 h1:/ZbHzb3EZDZSzaUxA7xfuYt9CS/hmXC33mJ4Z4Lvkhc=
|
||||||
github.com/txix-open/bgjob v1.6.0/go.mod h1:aKbwpVclWmq82s7fchazp099yWjEpVKFkxT85i4hARM=
|
github.com/txix-open/bgjob v1.5.0/go.mod h1:aKbwpVclWmq82s7fchazp099yWjEpVKFkxT85i4hARM=
|
||||||
github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo=
|
github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA=
|
||||||
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
|
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
||||||
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
|
github.com/txix-open/grmq v1.8.0 h1:YXTruBap7EQZ6WNOhjoFqx/XBYMBhgeYM4mzNkX+bzU=
|
||||||
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
|
github.com/txix-open/grmq v1.8.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po=
|
||||||
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
|
github.com/txix-open/isp-kit v1.48.1 h1:LZGZSpjUIaUfUQOGOHgRm9Q977su/C/rv3bI4w+x9iw=
|
||||||
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
|
github.com/txix-open/isp-kit v1.48.1/go.mod h1:qp0pbpsUqaAKhYGKGArYnBd0u7UBYuh561Q4MFkEqgs=
|
||||||
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-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
|
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
|
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
|
||||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||||
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
||||||
@@ -168,73 +192,114 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo
|
|||||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
|
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
|
||||||
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
|
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
|
||||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
|
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
|
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.60.0 h1:0tY123n7CdWMem7MOVdKOt0YfshufLCwfE5Bob+hQuM=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.60.0/go.mod h1:CosX/aS4eHnG9D7nESYpV753l4j9q5j3SL/PUYd2lR8=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 h1:sbiXRNDSWJOTobXh5HyQKjq6wUC5tNybqjIqDpAY4CU=
|
||||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0/go.mod h1:69uWxva0WgAA/4bu2Yy70SLDBwZXuQ6PbBpbsa5iZrQ=
|
||||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
|
go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 h1:1fTNlAIJZGWLP5FVu0fikVry1IsiUnXjf7QFvoNN3Xw=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 h1:xJ2qHD0C1BeYVTLLR9sX12+Qb95kfeD/byKj6Ky1pXg=
|
||||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0/go.mod h1:u5BF1xyjstDowA1R5QAO9JHzqK+ublenEW/dyqTjBVk=
|
||||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=
|
||||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=
|
||||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=
|
||||||
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg=
|
||||||
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
|
||||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
|
||||||
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
|
go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=
|
||||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=
|
||||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
go.opentelemetry.io/proto/otlp v1.6.0 h1:jQjP+AQyTf+Fe7OKj/MfkDrmK4MNVtw2NpXsf9fefDI=
|
||||||
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
|
go.opentelemetry.io/proto/otlp v1.6.0/go.mod h1:cicgGehlFuNdgZkcALOCh3VE6K/u2tAjzlRhDwmVpZc=
|
||||||
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
|
|
||||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||||
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||||
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
|
||||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
|
||||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
|
||||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
|
||||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
|
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M=
|
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
|
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||||
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
|
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
|
||||||
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
|
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
|
||||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
|
||||||
|
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||||
|
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
|
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||||
|
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||||
|
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||||
|
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
|
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
|
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
|
||||||
|
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2 h1:vPV0tzlsK6EzEDHNNH5sa7Hs9bd7iXR7B1tSiPepkV0=
|
||||||
|
google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:pKLAc5OolXC3ViWGI62vvC0n10CpwAtRcTNCFwTKBEw=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20250505200425-f936aa4a68b2 h1:IqsN8hx+lWLqlN+Sc3DoMy/watjofWiU8sRFgQ8fhKM=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
|
||||||
|
google.golang.org/grpc v1.72.0 h1:S7UkcVa60b5AAQTaO6ZKamFp1zMZSU0fGDK2WZLbBnM=
|
||||||
|
google.golang.org/grpc v1.72.0/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM=
|
||||||
|
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||||
|
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
|
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
|
||||||
modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
|
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
|
||||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
modernc.org/memory v1.9.1 h1:V/Z1solwAVmMW1yttq3nDdZPJqV1rM05Ccq6KMSZ34g=
|
||||||
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
modernc.org/memory v1.9.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||||
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
|
modernc.org/sqlite v1.36.2 h1:vjcSazuoFve9Wm0IVNHgmJECoOXLZM1KfMXbcX2axHA=
|
||||||
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
|
modernc.org/sqlite v1.36.2/go.mod h1:ADySlx7K4FdY5MaJcEv86hTJ0PjedAloTUuif0YS3ws=
|
||||||
@@ -1,29 +1,28 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/routes"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/bootstrap"
|
"github.com/txix-open/isp-kit/bootstrap"
|
||||||
"github.com/txix-open/isp-kit/cluster"
|
|
||||||
"github.com/txix-open/isp-kit/shutdown"
|
"github.com/txix-open/isp-kit/shutdown"
|
||||||
|
"msp-admin-service/assembly"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/routes"
|
||||||
)
|
)
|
||||||
|
|
||||||
var version = "1.0.0"
|
var version = "1.0.0"
|
||||||
|
|
||||||
// @title isp-admin-service
|
// @title msp-admin-service
|
||||||
// @version 1.0.0
|
// @version 1.0.0
|
||||||
// @description сервис управления администраторами
|
// @description сервис управления администраторами
|
||||||
|
|
||||||
// @license.name GNU GPL v3.0
|
// @license.name GNU GPL v3.0
|
||||||
|
|
||||||
// @host localhost:9000
|
// @host localhost:9000
|
||||||
// @BasePath /api/admin
|
// @BasePath /api/admin
|
||||||
|
|
||||||
//go:generate swag init -pd -ot json -eot json
|
//go:generate swag init --parseDependency
|
||||||
|
//go:generate rm -f docs/swagger.json docs/docs.go
|
||||||
func main() {
|
func main() {
|
||||||
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.HttpTransport)
|
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors())
|
||||||
app := boot.App
|
app := boot.App
|
||||||
logger := app.Logger()
|
logger := app.Logger()
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
-- +goose Up
|
|
||||||
ALTER TABLE users
|
|
||||||
ADD COLUMN last_active_at TIMESTAMP DEFAULT (now() at time zone 'utc') NOT NULL;
|
|
||||||
|
|
||||||
-- +goose Down
|
|
||||||
ALTER TABLE users
|
|
||||||
DROP COLUMN last_active_at;
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
-- +goose Up
|
|
||||||
ALTER TABLE users DROP CONSTRAINT users_email_key;
|
|
||||||
ALTER TABLE users ADD CONSTRAINT users_email_sudir_user_id_key UNIQUE (email, sudir_user_id);
|
|
||||||
|
|
||||||
-- +goose Down
|
|
||||||
ALTER TABLE users DROP CONSTRAINT users_email_sudir_user_id_key;
|
|
||||||
ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email);
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
-- +goose Up
|
|
||||||
INSERT INTO audit_event (event, enable)
|
|
||||||
VALUES
|
|
||||||
('user_blocked', true);
|
|
||||||
|
|
||||||
-- +goose Down
|
|
||||||
DELETE FROM audit_event WHERE event = 'user_blocked';
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
-- +goose Up
|
|
||||||
alter table bgjob_job
|
|
||||||
add column request_id text;
|
|
||||||
|
|
||||||
alter table bgjob_dead_job
|
|
||||||
add column request_id text;
|
|
||||||
|
|
||||||
update bgjob_job
|
|
||||||
set request_id = ''
|
|
||||||
where request_id is null;
|
|
||||||
|
|
||||||
update bgjob_dead_job
|
|
||||||
set request_id = ''
|
|
||||||
where request_id is null;
|
|
||||||
|
|
||||||
alter table bgjob_job
|
|
||||||
alter column request_id set default '',
|
|
||||||
alter column request_id set not null;
|
|
||||||
|
|
||||||
alter table bgjob_dead_job
|
|
||||||
alter column request_id set default '',
|
|
||||||
alter column request_id set not null;
|
|
||||||
|
|
||||||
-- +goose Down
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
-- +goose Up
|
|
||||||
ALTER TABLE users ADD COLUMN full_name VARCHAR(255) DEFAULT '' NOT NULL;
|
|
||||||
|
|
||||||
UPDATE users u SET full_name=u.first_name
|
|
||||||
WHERE (u.last_name = '') AND (u.first_name <> '');
|
|
||||||
|
|
||||||
UPDATE users u SET full_name=u.last_name || ' ' || u.first_name
|
|
||||||
WHERE (u.last_name <> '') AND (u.first_name <> '');
|
|
||||||
|
|
||||||
-- +goose Down
|
|
||||||
ALTER TABLE users DROP COLUMN full_name;
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
-- +goose Up
|
|
||||||
ALTER TABLE users RENAME COLUMN sudir_user_id TO oauth_user_id;
|
|
||||||
|
|
||||||
-- +goose Down
|
|
||||||
ALTER TABLE users RENAME COLUMN oauth_user_id TO sudir_user_id;
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
-- +goose Up
|
|
||||||
ALTER TABLE roles ADD COLUMN application_group TEXT NOT NULL DEFAULT '';
|
|
||||||
|
|
||||||
-- +goose Down
|
|
||||||
ALTER TABLE roles DROP COLUMN application_group;
|
|
||||||
+15
-67
@@ -4,23 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
|
||||||
"github.com/iancoleman/strcase"
|
|
||||||
"github.com/txix-open/isp-kit/db"
|
"github.com/txix-open/isp-kit/db"
|
||||||
"github.com/txix-open/isp-kit/db/query"
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
)
|
"msp-admin-service/entity"
|
||||||
|
|
||||||
const (
|
|
||||||
idAuditColumn = "id"
|
|
||||||
userIdAuditColumn = "user_id"
|
|
||||||
messageAuditColumn = "message"
|
|
||||||
createdAtAuditColumn = "created_at"
|
|
||||||
eventAuditColumn = "event"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Audit struct {
|
type Audit struct {
|
||||||
@@ -55,50 +43,35 @@ func (r Audit) Insert(ctx context.Context, log entity.Audit) (int, error) {
|
|||||||
return id, nil
|
return id, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Audit) AllByRequest(ctx context.Context, req domain.AuditPageRequest) ([]entity.Audit, error) {
|
//nolint:gosec
|
||||||
|
func (r Audit) All(ctx context.Context, limit int, offset int) ([]entity.Audit, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Audit.All")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Audit.All")
|
||||||
|
|
||||||
q := query.New().
|
query, args, err := query.New().
|
||||||
Select(
|
Select("*").
|
||||||
idAuditColumn,
|
|
||||||
userIdAuditColumn,
|
|
||||||
messageAuditColumn,
|
|
||||||
createdAtAuditColumn,
|
|
||||||
eventAuditColumn,
|
|
||||||
).
|
|
||||||
From("audit").
|
From("audit").
|
||||||
OrderBy(strcase.ToSnake(req.Order.Field) + " " + req.Order.Type).
|
OrderBy("created_at DESC").
|
||||||
Offset(req.Offset).
|
Offset(uint64(offset)).
|
||||||
Limit(req.Limit)
|
Limit(uint64(limit)).
|
||||||
|
ToSql()
|
||||||
query, args, err := reqAuditQuery(q, req.Query).ToSql()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "build query")
|
return nil, errors.WithMessage(err, "build query")
|
||||||
}
|
}
|
||||||
|
|
||||||
logs := make([]entity.Audit, 0)
|
tokens := make([]entity.Audit, 0)
|
||||||
err = r.db.Select(ctx, &logs, query, args...)
|
err = r.db.Select(ctx, &tokens, query, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select query: %s", query)
|
return nil, errors.WithMessagef(err, "select query: %s", query)
|
||||||
}
|
}
|
||||||
|
|
||||||
return logs, nil
|
return tokens, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Audit) Count(ctx context.Context, reqQuery *domain.AuditQuery) (int64, error) {
|
func (r Audit) Count(ctx context.Context) (int64, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Audit.Count")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Audit.Count")
|
||||||
|
|
||||||
q := query.New().
|
|
||||||
Select("count(*)").
|
|
||||||
From("audit")
|
|
||||||
|
|
||||||
query, args, err := reqAuditQuery(q, reqQuery).ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
count := int64(0)
|
count := int64(0)
|
||||||
err = r.db.SelectRow(ctx, &count, query, args...)
|
err := r.db.SelectRow(ctx, &count, "select count(*) from audit")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, errors.WithMessage(err, "select count")
|
return 0, errors.WithMessage(err, "select count")
|
||||||
}
|
}
|
||||||
@@ -123,28 +96,3 @@ func (r Audit) DeleteUpToCreatedAt(ctx context.Context, createdAt time.Time) err
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func reqAuditQuery(q squirrel.SelectBuilder, reqQuery *domain.AuditQuery) squirrel.SelectBuilder {
|
|
||||||
if reqQuery == nil {
|
|
||||||
return q
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.Id != nil {
|
|
||||||
q = q.Where("id = ?", *reqQuery.Id)
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.UserId != nil {
|
|
||||||
q = q.Where(squirrel.Eq{"user_id": reqQuery.UserId})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.Message != nil {
|
|
||||||
q = q.Where(squirrel.ILike{"message": "%" + *reqQuery.Message + "%"})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.CreatedAt != nil {
|
|
||||||
q = q.Where(squirrel.GtOrEq{"created_at": reqQuery.CreatedAt.From}).
|
|
||||||
Where(squirrel.Lt{"created_at": reqQuery.CreatedAt.To})
|
|
||||||
}
|
|
||||||
|
|
||||||
return q
|
|
||||||
}
|
|
||||||
@@ -4,18 +4,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
"github.com/Masterminds/squirrel"
|
||||||
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/isp-kit/db"
|
"github.com/txix-open/isp-kit/db"
|
||||||
"github.com/txix-open/isp-kit/db/query"
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
)
|
"msp-admin-service/entity"
|
||||||
|
|
||||||
const (
|
|
||||||
eventAuditEventColumn = "event"
|
|
||||||
enableAuditEventColumn = "enable"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuditEvent struct {
|
type AuditEvent struct {
|
||||||
@@ -32,7 +26,7 @@ func (r AuditEvent) All(ctx context.Context) ([]entity.AuditEvent, error) {
|
|||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Audit_Event.All")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Audit_Event.All")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(eventAuditEventColumn, enableAuditEventColumn).
|
Select("*").
|
||||||
From("audit_event").
|
From("audit_event").
|
||||||
OrderBy("enable DESC").
|
OrderBy("enable DESC").
|
||||||
ToSql()
|
ToSql()
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package ldap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-ldap/ldap/v3"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
dialTimeout = 5 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
type Repository struct {
|
||||||
|
baseDn string
|
||||||
|
conn *ldap.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRepository(config *conf.Ldap) (*Repository, error) {
|
||||||
|
if config == nil {
|
||||||
|
return nil, errors.New("ldap config is not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := net.DialTimeout("tcp", config.Address, dialTimeout)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessagef(err, "net dial to %s", config.Address)
|
||||||
|
}
|
||||||
|
|
||||||
|
conn := ldap.NewConn(c, false)
|
||||||
|
conn.Start()
|
||||||
|
|
||||||
|
err = conn.Bind(config.Username, config.Password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessagef(err, "ldap auth, username: %s", config.Username)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Repository{
|
||||||
|
conn: conn,
|
||||||
|
baseDn: config.BaseDn,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Repository) IsExist(ctx context.Context, dn string) (bool, error) {
|
||||||
|
request := ldap.NewSearchRequest(
|
||||||
|
dn,
|
||||||
|
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||||
|
"(objectClass=*)",
|
||||||
|
[]string{"name"},
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
result, err := r.conn.Search(request)
|
||||||
|
if err != nil {
|
||||||
|
return false, errors.WithMessage(err, "search by full dn")
|
||||||
|
}
|
||||||
|
return len(result.Entries) > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Repository) DnByUserPrincipalName(ctx context.Context, principalName string) (string, error) {
|
||||||
|
filter := fmt.Sprintf("(&(userPrincipalName=%s))", principalName)
|
||||||
|
request := ldap.NewSearchRequest(
|
||||||
|
r.baseDn, // The base dn to search
|
||||||
|
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||||
|
filter,
|
||||||
|
[]string{"name"},
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
result, err := r.conn.Search(request)
|
||||||
|
if err != nil {
|
||||||
|
return "", errors.WithMessagef(err, "search by '%s'", filter)
|
||||||
|
}
|
||||||
|
if len(result.Entries) == 0 {
|
||||||
|
return "", errors.Errorf("not found entities by principalName: %s", principalName)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.Entries[0].DN, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Repository) ModifyMemberAttr(ctx context.Context, userDn string, groupDn string, operation string) error {
|
||||||
|
modifyReq := ldap.NewModifyRequest(groupDn, nil)
|
||||||
|
switch operation {
|
||||||
|
case entity.GroupOperationAdd:
|
||||||
|
modifyReq.Add("member", []string{userDn})
|
||||||
|
case entity.GroupOperationDelete:
|
||||||
|
modifyReq.Delete("member", []string{userDn})
|
||||||
|
}
|
||||||
|
|
||||||
|
err := r.conn.Modify(modifyReq)
|
||||||
|
if ldap.IsErrorAnyOf(err, ldap.LDAPResultUnwillingToPerform, ldap.LDAPResultEntryAlreadyExists) {
|
||||||
|
return errors.WithMessage(domain.ErrNoActionRequired, err.Error())
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessagef(err, "modify entity by dn %s, operation: %s member from group", groupDn, operation)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Repository) Close() error {
|
||||||
|
return errors.WithMessage(r.conn.Close(), "close ldap connection")
|
||||||
|
}
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
|
||||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
|
||||||
)
|
|
||||||
|
|
||||||
//nolint:gosec
|
|
||||||
const (
|
|
||||||
getTokenEndpoint = "/oauth/te"
|
|
||||||
getUserEndpoint = "/oauth/me"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Oauth struct {
|
|
||||||
cli *httpcli.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewOauth(cli *httpcli.Client) Oauth {
|
|
||||||
return Oauth{
|
|
||||||
cli: cli,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Oauth) GetToken(ctx context.Context, clientSetting entity.ClientSetting) (*entity.OauthTokenResponse, error) {
|
|
||||||
ctx = http_metrics.ClientEndpointToContext(ctx, getTokenEndpoint)
|
|
||||||
|
|
||||||
response := entity.OauthTokenResponse{}
|
|
||||||
err := s.cli.Post(getTokenEndpoint).
|
|
||||||
BasicAuth(httpcli.BasicAuth{
|
|
||||||
Username: clientSetting.ClientId,
|
|
||||||
Password: clientSetting.ClientSecret,
|
|
||||||
}).
|
|
||||||
Header("Content-Type", "application/x-www-form-urlencoded").
|
|
||||||
QueryParams(map[string]any{
|
|
||||||
"grant_type": "authorization_code",
|
|
||||||
"code": clientSetting.AuthCode,
|
|
||||||
"redirect_uri": clientSetting.RedirectURI,
|
|
||||||
}).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "call POST: '%s'", getTokenEndpoint)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &response, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Oauth) GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error) {
|
|
||||||
ctx = http_metrics.ClientEndpointToContext(ctx, getUserEndpoint)
|
|
||||||
|
|
||||||
response := entity.OauthUserResponse{}
|
|
||||||
err := s.cli.Get(getUserEndpoint).
|
|
||||||
Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "call GET: '%s'", getUserEndpoint)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &response, nil
|
|
||||||
}
|
|
||||||
+9
-55
@@ -4,32 +4,19 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
"github.com/Masterminds/squirrel"
|
||||||
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/isp-kit/db"
|
"github.com/txix-open/isp-kit/db"
|
||||||
"github.com/txix-open/isp-kit/db/query"
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Role struct {
|
type Role struct {
|
||||||
db db.DB
|
db db.DB
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
|
||||||
idRolesColumn = "id"
|
|
||||||
nameRolesColumn = "name"
|
|
||||||
createdAtRolesColumn = "created_at"
|
|
||||||
updatedAtRolesColumn = "updated_at"
|
|
||||||
permissionsRolesColumn = "permissions"
|
|
||||||
externalGroupRolesColumn = "external_group"
|
|
||||||
applicationGroupColumn = "application_group"
|
|
||||||
immutableRolesColumn = "immutable"
|
|
||||||
exclusiveRolesColumn = "exclusive"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewRole(db db.DB) Role {
|
func NewRole(db db.DB) Role {
|
||||||
return Role{db: db}
|
return Role{db: db}
|
||||||
}
|
}
|
||||||
@@ -38,7 +25,7 @@ func (r Role) GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error)
|
|||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select("id, name, external_group, application_group, permissions, created_at, updated_at").
|
Select("id, name, external_group, permissions, created_at, updated_at").
|
||||||
From("roles").
|
From("roles").
|
||||||
Where(squirrel.Eq{"id": id}).
|
Where(squirrel.Eq{"id": id}).
|
||||||
ToSql()
|
ToSql()
|
||||||
@@ -61,17 +48,7 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err
|
|||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByName")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByName")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(
|
Select("*").
|
||||||
idRolesColumn,
|
|
||||||
nameRolesColumn,
|
|
||||||
createdAtRolesColumn,
|
|
||||||
updatedAtRolesColumn,
|
|
||||||
permissionsRolesColumn,
|
|
||||||
externalGroupRolesColumn,
|
|
||||||
applicationGroupColumn,
|
|
||||||
immutableRolesColumn,
|
|
||||||
exclusiveRolesColumn,
|
|
||||||
).
|
|
||||||
From("roles").
|
From("roles").
|
||||||
Where(squirrel.Eq{"name": name}).
|
Where(squirrel.Eq{"name": name}).
|
||||||
ToSql()
|
ToSql()
|
||||||
@@ -96,17 +73,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
|
|||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRolesByExternalGroup")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRolesByExternalGroup")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(
|
Select("*").
|
||||||
idRolesColumn,
|
|
||||||
nameRolesColumn,
|
|
||||||
createdAtRolesColumn,
|
|
||||||
updatedAtRolesColumn,
|
|
||||||
permissionsRolesColumn,
|
|
||||||
externalGroupRolesColumn,
|
|
||||||
applicationGroupColumn,
|
|
||||||
immutableRolesColumn,
|
|
||||||
exclusiveRolesColumn,
|
|
||||||
).
|
|
||||||
From("roles").
|
From("roles").
|
||||||
Where(squirrel.Eq{"external_group": groups}).
|
Where(squirrel.Eq{"external_group": groups}).
|
||||||
ToSql()
|
ToSql()
|
||||||
@@ -125,7 +92,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
|
|||||||
|
|
||||||
func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All")
|
||||||
q := "select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
|
q := "select id, name, external_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
|
||||||
roles := make([]entity.Role, 0)
|
roles := make([]entity.Role, 0)
|
||||||
err := r.db.Select(ctx, &roles, q)
|
err := r.db.Select(ctx, &roles, q)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -134,24 +101,12 @@ func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
|||||||
return roles, nil
|
return roles, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Role) AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error) {
|
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.AllWithFilter")
|
|
||||||
roles := make([]entity.Role, 0)
|
|
||||||
err := r.db.Select(ctx, &roles, `
|
|
||||||
select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at
|
|
||||||
from roles where application_group=$1 order by created_at`, applicationGroup)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "select all roles")
|
|
||||||
}
|
|
||||||
return roles, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) {
|
func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole")
|
||||||
|
|
||||||
q, args, err := query.New().Insert("roles").
|
q, args, err := query.New().Insert("roles").
|
||||||
Columns("name", "permissions", "external_group", "application_group").
|
Columns("name", "permissions", "external_group").
|
||||||
Values(role.Name, role.Permissions, role.ExternalGroup, role.ApplicationGroup).
|
Values(role.Name, role.Permissions, role.ExternalGroup).
|
||||||
Suffix("RETURNING *").ToSql()
|
Suffix("RETURNING *").ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "build query")
|
return nil, errors.WithMessage(err, "build query")
|
||||||
@@ -173,7 +128,6 @@ func (r Role) Update(ctx context.Context, role entity.Role) (*entity.Role, error
|
|||||||
Set("name", role.Name).
|
Set("name", role.Name).
|
||||||
Set("permissions", role.Permissions).
|
Set("permissions", role.Permissions).
|
||||||
Set("external_group", role.ExternalGroup).
|
Set("external_group", role.ExternalGroup).
|
||||||
Set("application_group", role.ApplicationGroup).
|
|
||||||
Where(squirrel.Eq{"id": role.Id}).
|
Where(squirrel.Eq{"id": role.Id}).
|
||||||
Suffix("RETURNING *").ToSql()
|
Suffix("RETURNING *").ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/txix-open/isp-kit/http/httpcli"
|
||||||
|
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Sudir struct {
|
||||||
|
httpCli *httpcli.Client
|
||||||
|
cfg *conf.SudirAuth
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSudir(httpCli *httpcli.Client, cfg *conf.SudirAuth) Sudir {
|
||||||
|
return Sudir{
|
||||||
|
httpCli: httpCli,
|
||||||
|
cfg: cfg,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Sudir) GetToken(ctx context.Context, authCode string) (*entity.SudirTokenResponse, error) {
|
||||||
|
urlString, err := url.JoinPath(s.cfg.Host, "/blitz/oauth/te")
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "build url")
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx = http_metrics.ClientEndpointToContext(ctx, urlString)
|
||||||
|
|
||||||
|
response := entity.SudirTokenResponse{}
|
||||||
|
err = s.httpCli.Post(urlString).
|
||||||
|
BasicAuth(httpcli.BasicAuth{
|
||||||
|
Username: s.cfg.ClientId,
|
||||||
|
Password: s.cfg.ClientSecret,
|
||||||
|
}).
|
||||||
|
Header("Content-Type", "application/x-www-form-urlencoded").
|
||||||
|
QueryParams(map[string]any{
|
||||||
|
"grant_type": "authorization_code",
|
||||||
|
"code": authCode,
|
||||||
|
"redirect_uri": s.cfg.RedirectURI,
|
||||||
|
}).
|
||||||
|
JsonResponseBody(&response).
|
||||||
|
StatusCodeToError().
|
||||||
|
DoWithoutResponse(ctx)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "http request")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Sudir) GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error) {
|
||||||
|
urlString, err := url.JoinPath(s.cfg.Host, "/blitz/oauth/me")
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "build url")
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx = http_metrics.ClientEndpointToContext(ctx, urlString)
|
||||||
|
|
||||||
|
response := entity.SudirUserResponse{}
|
||||||
|
err = s.httpCli.
|
||||||
|
Get(urlString).
|
||||||
|
Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)).
|
||||||
|
JsonResponseBody(&response).
|
||||||
|
StatusCodeToError().
|
||||||
|
DoWithoutResponse(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "http request")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response, nil
|
||||||
|
}
|
||||||
+44
-112
@@ -3,29 +3,15 @@ package repository
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"strconv"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
"github.com/Masterminds/squirrel"
|
||||||
"github.com/iancoleman/strcase"
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/db"
|
"github.com/txix-open/isp-kit/db"
|
||||||
"github.com/txix-open/isp-kit/db/query"
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
)
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
const (
|
|
||||||
idTokensColumn = "id"
|
|
||||||
tokenColumn = "token"
|
|
||||||
userIdTokensColumn = "user_id"
|
|
||||||
statusTokensColumn = "status"
|
|
||||||
expiredAtTokensColumn = "expired_at"
|
|
||||||
createdAtTokensColumn = "created_at"
|
|
||||||
updatedAtTokensColumn = "updated_at"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Token struct {
|
type Token struct {
|
||||||
@@ -90,36 +76,17 @@ func (r Token) RevokeByUserId(ctx context.Context, userId int64, updatedAt time.
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Token) All(ctx context.Context) ([]entity.Token, error) {
|
//nolint:gosec
|
||||||
|
func (r Token) All(ctx context.Context, limit int, offset int) ([]entity.Token, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.All")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.All")
|
||||||
|
|
||||||
query, args, err := query.New().Select(idTokensColumn, tokenColumn, userIdTokensColumn, statusTokensColumn,
|
query, args, err := query.New().
|
||||||
expiredAtTokensColumn, createdAtTokensColumn, updatedAtTokensColumn).From("tokens").ToSql()
|
Select("*").
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
tokens := make([]entity.Token, 0)
|
|
||||||
err = r.db.Select(ctx, &tokens, query, args...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "select query %s", query)
|
|
||||||
}
|
|
||||||
|
|
||||||
return tokens, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Token) AllByRequest(ctx context.Context, req domain.SessionPageRequest) ([]entity.Token, error) {
|
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.AllByRequest")
|
|
||||||
|
|
||||||
q := query.New().
|
|
||||||
Select(idTokensColumn, tokenColumn, userIdTokensColumn, statusTokensColumn, expiredAtTokensColumn, createdAtTokensColumn,
|
|
||||||
updatedAtTokensColumn).
|
|
||||||
From("tokens").
|
From("tokens").
|
||||||
OrderBy(strcase.ToSnake(req.Order.Field) + " " + req.Order.Type).
|
OrderBy("created_at DESC").
|
||||||
Offset(req.Offset).
|
Offset(uint64(offset)).
|
||||||
Limit(req.Limit)
|
Limit(uint64(limit)).
|
||||||
|
ToSql()
|
||||||
query, args, err := reqTokenQuery(q, req.Query).ToSql()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "build query")
|
return nil, errors.WithMessage(err, "build query")
|
||||||
}
|
}
|
||||||
@@ -147,40 +114,11 @@ func (r Token) UpdateStatus(ctx context.Context, id int, status string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Token) SetExpiredStatusByIds(ctx context.Context, ids []int) error {
|
func (r Token) Count(ctx context.Context) (int64, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.SetExpiredStatusByIds")
|
|
||||||
|
|
||||||
query, args, err := query.New().
|
|
||||||
Update("tokens").
|
|
||||||
Set("status", entity.TokenStatusExpired).
|
|
||||||
Where(squirrel.Eq{"id": ids}).
|
|
||||||
ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = r.db.Exec(ctx, query, args...)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "set tokens expired status")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Token) Count(ctx context.Context, reqQuery *domain.SessionQuery) (int64, error) {
|
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.Count")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.Count")
|
||||||
|
|
||||||
q := query.New().
|
|
||||||
Select("count(*)").
|
|
||||||
From("tokens")
|
|
||||||
|
|
||||||
query, args, err := reqTokenQuery(q, reqQuery).ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
count := int64(0)
|
count := int64(0)
|
||||||
err = r.db.SelectRow(ctx, &count, query, args...)
|
err := r.db.SelectRow(ctx, &count, "select count(*) from tokens")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, errors.WithMessage(err, "select count")
|
return 0, errors.WithMessage(err, "select count")
|
||||||
}
|
}
|
||||||
@@ -201,10 +139,33 @@ func (r Token) UpdateStatusByUserId(ctx context.Context, userId int, status stri
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Token) LastAccessByUserIds(ctx context.Context, userIds []int) (map[int64]*time.Time, error) {
|
func (r Token) LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessByUserIds")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessNotBlockedUsers")
|
||||||
|
|
||||||
query, args, err := query.New().
|
query := `
|
||||||
|
select t.user_id, max(t.created_at) as created_at from tokens t
|
||||||
|
join users u on t.user_id = u.id
|
||||||
|
where u.blocked = false
|
||||||
|
group by t.user_id
|
||||||
|
`
|
||||||
|
tokens := make([]entity.Token, 0)
|
||||||
|
err := r.db.Select(ctx, &tokens, query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessagef(err, "select query: %s", query)
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make(map[int64]time.Time, 0)
|
||||||
|
for _, token := range tokens {
|
||||||
|
result[token.UserId] = token.CreatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Token) LastAccessByUserIds(ctx context.Context, userIds []int) (map[int64]*time.Time, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessNotBlockedUsers")
|
||||||
|
|
||||||
|
q, args, err := query.New().
|
||||||
Select("user_id", "max(created_at) as created_at").
|
Select("user_id", "max(created_at) as created_at").
|
||||||
From("tokens").
|
From("tokens").
|
||||||
Where(squirrel.Eq{"user_id": userIds}).
|
Where(squirrel.Eq{"user_id": userIds}).
|
||||||
@@ -215,45 +176,16 @@ func (r Token) LastAccessByUserIds(ctx context.Context, userIds []int) (map[int6
|
|||||||
}
|
}
|
||||||
|
|
||||||
tokens := make([]entity.Token, 0)
|
tokens := make([]entity.Token, 0)
|
||||||
err = r.db.Select(ctx, &tokens, query, args...)
|
err = r.db.Select(ctx, &tokens, q, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select query: %s", query)
|
return nil, errors.WithMessagef(err, "select query: %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
result := make(map[int64]*time.Time)
|
result := make(map[int64]*time.Time, 0)
|
||||||
for _, token := range tokens {
|
for _, token := range tokens {
|
||||||
result[token.UserId] = new(token.CreatedAt)
|
createdAt := token.CreatedAt
|
||||||
|
result[token.UserId] = &createdAt
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func reqTokenQuery(q squirrel.SelectBuilder, reqQuery *domain.SessionQuery) squirrel.SelectBuilder {
|
|
||||||
if reqQuery == nil {
|
|
||||||
return q
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.Id != nil {
|
|
||||||
q = q.Where(squirrel.ILike{"id::text": "%" + strconv.Itoa(*reqQuery.Id) + "%"})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.UserId != nil {
|
|
||||||
q = q.Where(squirrel.Eq{"user_id": reqQuery.UserId})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.Status != nil {
|
|
||||||
q = q.Where(squirrel.Eq{"status": reqQuery.Status})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.CreatedAt != nil {
|
|
||||||
q = q.Where(squirrel.GtOrEq{"created_at": reqQuery.CreatedAt.From}).
|
|
||||||
Where(squirrel.Lt{"created_at": reqQuery.CreatedAt.To})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.ExpiredAt != nil {
|
|
||||||
q = q.Where(squirrel.GtOrEq{"expired_at": reqQuery.ExpiredAt.From}).
|
|
||||||
Where(squirrel.Lt{"expired_at": reqQuery.ExpiredAt.To})
|
|
||||||
}
|
|
||||||
|
|
||||||
return q
|
|
||||||
}
|
|
||||||
+36
-201
@@ -3,33 +3,14 @@ package repository
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
"github.com/Masterminds/squirrel"
|
||||||
"github.com/iancoleman/strcase"
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/isp-kit/db"
|
"github.com/txix-open/isp-kit/db"
|
||||||
"github.com/txix-open/isp-kit/db/query"
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
)
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
const (
|
|
||||||
idUsersColumn = "id"
|
|
||||||
firstNameUsersColumn = "first_name"
|
|
||||||
lastNameUsersColumn = "last_name"
|
|
||||||
emailUsersColumn = "email"
|
|
||||||
passwordUsersColumn = "password"
|
|
||||||
createdAtUsersColumn = "created_at"
|
|
||||||
updatedAtUsersColumn = "updated_at"
|
|
||||||
oauthUserIdUsersColumn = "oauth_user_id"
|
|
||||||
blockedUsersColumn = "blocked"
|
|
||||||
descriptionUsersColumn = "description"
|
|
||||||
lastActiveAtUsersColumn = "last_active_at"
|
|
||||||
fullNameUsersColumn = "full_name"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
@@ -44,9 +25,7 @@ func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, e
|
|||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select("*").
|
||||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
|
||||||
fullNameUsersColumn).
|
|
||||||
From("users").
|
From("users").
|
||||||
Where(squirrel.Eq{"email": email}).
|
Where(squirrel.Eq{"email": email}).
|
||||||
ToSql()
|
ToSql()
|
||||||
@@ -71,9 +50,7 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
|||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserById")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserById")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select("*").
|
||||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
|
||||||
fullNameUsersColumn).
|
|
||||||
From("users").
|
From("users").
|
||||||
Where(squirrel.Eq{"id": identity}).
|
Where(squirrel.Eq{"id": identity}).
|
||||||
ToSql()
|
ToSql()
|
||||||
@@ -94,48 +71,15 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error) {
|
func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmailAndOauthId")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertBySudirUserId")
|
||||||
|
|
||||||
equalClause := squirrel.Eq{"email": email, "oauth_user_id": nil}
|
|
||||||
if oauthUserId != "" {
|
|
||||||
equalClause["oauth_user_id"] = oauthUserId
|
|
||||||
}
|
|
||||||
|
|
||||||
q, args, err := query.New().
|
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
|
||||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
|
||||||
fullNameUsersColumn).
|
|
||||||
From("users").
|
|
||||||
Where(equalClause).
|
|
||||||
ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
user := entity.User{}
|
|
||||||
err = u.db.SelectRow(ctx, &user, q, args...)
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, sql.ErrNoRows):
|
|
||||||
return nil, domain.ErrNotFound
|
|
||||||
case err != nil:
|
|
||||||
return nil, errors.WithMessage(err, "db select")
|
|
||||||
default:
|
|
||||||
return &user, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u User) UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertByOauthUserId")
|
|
||||||
|
|
||||||
selectQ := `
|
selectQ := `
|
||||||
insert into users as u (first_name, last_name, full_name, email, created_at, updated_at, oauth_user_id)
|
insert into users as u (first_name, last_name, email, created_at, updated_at, sudir_user_id)
|
||||||
values ($1, $2, $3, $4, $5, $6, $7)
|
values ($1, $2, $3, $4, $5, $6)
|
||||||
on conflict (oauth_user_id) do update
|
on conflict (sudir_user_id) do update
|
||||||
set first_name = excluded.first_name,
|
set first_name = excluded.first_name,
|
||||||
last_name = excluded.last_name,
|
last_name = excluded.last_name,
|
||||||
full_name = excluded.full_name,
|
|
||||||
email = excluded.email,
|
email = excluded.email,
|
||||||
updated_at = excluded.updated_at
|
updated_at = excluded.updated_at
|
||||||
where u.blocked = false
|
where u.blocked = false
|
||||||
@@ -145,7 +89,7 @@ func (u User) UpsertByOauthUserId(ctx context.Context, user entity.User) (*entit
|
|||||||
err := u.db.SelectRow(ctx,
|
err := u.db.SelectRow(ctx,
|
||||||
&result,
|
&result,
|
||||||
selectQ,
|
selectQ,
|
||||||
user.FirstName, user.LastName, user.FullName, user.Email, user.CreatedAt, user.UpdatedAt, user.OauthUserId,
|
user.FirstName, user.LastName, user.Email, user.CreatedAt, user.UpdatedAt, user.SudirUserId,
|
||||||
)
|
)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return nil, domain.ErrUserIsBlocked
|
return nil, domain.ErrUserIsBlocked
|
||||||
@@ -157,83 +101,36 @@ func (u User) UpsertByOauthUserId(ctx context.Context, user entity.User) (*entit
|
|||||||
return &result, nil
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]entity.User, error) {
|
//nolint:gosec
|
||||||
|
func (u User) GetUsers(ctx context.Context, ids []int64, offset, limit int, email string) ([]entity.User, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUsers")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUsers")
|
||||||
|
|
||||||
q := query.New().
|
q := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select("*").
|
||||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
From("users")
|
||||||
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
|
||||||
From("users").
|
|
||||||
Offset(req.Offset).
|
|
||||||
Limit(req.Limit)
|
|
||||||
|
|
||||||
if req.Order.Field == "userId" {
|
if len(ids) > 0 {
|
||||||
q = q.OrderBy("full_name " + req.Order.Type)
|
q = q.Where(squirrel.Eq{"id": ids})
|
||||||
} else {
|
|
||||||
q = q.OrderBy(strcase.ToSnake(req.Order.Field) + " " + req.Order.Type)
|
|
||||||
}
|
}
|
||||||
|
if email != "" {
|
||||||
query, args, err := reqUsersQuery(q, req.Query).ToSql()
|
q = q.Where("email LIKE ?", "%"+email+"%")
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "build query")
|
|
||||||
}
|
}
|
||||||
|
qstring, args, err := q.
|
||||||
users := make([]entity.User, 0)
|
Limit(uint64(limit)).
|
||||||
err = u.db.Select(ctx, &users, query, args...)
|
Offset(uint64(offset)).
|
||||||
if err != nil {
|
OrderBy("created_at DESC").
|
||||||
return nil, errors.WithMessage(err, "db select")
|
|
||||||
}
|
|
||||||
|
|
||||||
return users, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u User) GetAllUsers(ctx context.Context) ([]entity.User, error) {
|
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUsers")
|
|
||||||
|
|
||||||
query, args, err := query.New().
|
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
|
||||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
|
||||||
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
|
||||||
From("users").ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
users := make([]entity.User, 0)
|
|
||||||
err = u.db.Select(ctx, &users, query, args...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "db select")
|
|
||||||
}
|
|
||||||
|
|
||||||
return users, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u User) GetUsersByEmail(ctx context.Context, email string) ([]entity.User, error) {
|
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
|
||||||
|
|
||||||
q, args, err := query.New().
|
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
|
||||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
|
||||||
fullNameUsersColumn).
|
|
||||||
From("users").
|
|
||||||
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")
|
||||||
}
|
}
|
||||||
|
|
||||||
users := make([]entity.User, 0)
|
users := make([]entity.User, 0)
|
||||||
err = u.db.Select(ctx, &users, q, args...)
|
err = u.db.Select(ctx, &users, qstring, args...)
|
||||||
|
if err != nil {
|
||||||
switch {
|
|
||||||
case errors.Is(err, sql.ErrNoRows) || len(users) == 0:
|
|
||||||
return nil, domain.ErrNotFound
|
|
||||||
case err != nil:
|
|
||||||
return nil, errors.WithMessage(err, "db select")
|
return nil, errors.WithMessage(err, "db select")
|
||||||
default:
|
|
||||||
return users, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return users, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) Insert(ctx context.Context, user entity.User) (int, error) {
|
func (u User) Insert(ctx context.Context, user entity.User) (int, error) {
|
||||||
@@ -241,9 +138,9 @@ func (u User) Insert(ctx context.Context, user entity.User) (int, error) {
|
|||||||
|
|
||||||
insertQ, args, err := query.New().
|
insertQ, args, err := query.New().
|
||||||
Insert("users").
|
Insert("users").
|
||||||
Columns(firstNameUsersColumn, lastNameUsersColumn, fullNameUsersColumn, descriptionUsersColumn,
|
Columns("first_name", "last_name", "description",
|
||||||
emailUsersColumn, passwordUsersColumn, createdAtUsersColumn, updatedAtUsersColumn).
|
"email", "password", "created_at", "updated_at").
|
||||||
Values(user.FirstName, user.LastName, user.FullName, user.Description,
|
Values(user.FirstName, user.LastName, user.Description,
|
||||||
user.Email, user.Password, user.CreatedAt, user.UpdatedAt).
|
user.Email, user.Password, user.CreatedAt, user.UpdatedAt).
|
||||||
Suffix("returning id").
|
Suffix("returning id").
|
||||||
ToSql()
|
ToSql()
|
||||||
@@ -266,15 +163,14 @@ func (u User) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser)
|
|||||||
// return every except password
|
// return every except password
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Update("users").
|
Update("users").
|
||||||
SetMap(map[string]any{
|
SetMap(map[string]interface{}{
|
||||||
firstNameUsersColumn: user.FirstName,
|
"first_name": user.FirstName,
|
||||||
lastNameUsersColumn: user.LastName,
|
"last_name": user.LastName,
|
||||||
fullNameUsersColumn: user.FullName,
|
"email": user.Email,
|
||||||
emailUsersColumn: user.Email,
|
"description": user.Description,
|
||||||
descriptionUsersColumn: user.Description,
|
|
||||||
}).
|
}).
|
||||||
Where(squirrel.Eq{"id": id}).
|
Where(squirrel.Eq{"id": id}).
|
||||||
Suffix("RETURNING id, first_name, last_name, full_name, email, oauth_user_id, description, created_at, updated_at").
|
Suffix("RETURNING id, first_name, last_name, email, sudir_user_id, description, created_at, updated_at").
|
||||||
ToSql()
|
ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "build query")
|
return nil, errors.WithMessage(err, "build query")
|
||||||
@@ -337,32 +233,6 @@ func (u User) Block(ctx context.Context, userId int) (*entity.User, error) {
|
|||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error) {
|
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.LastAccessNotBlockedUsers")
|
|
||||||
|
|
||||||
q, args, err := query.New().
|
|
||||||
Select("id, last_active_at").
|
|
||||||
From("users").
|
|
||||||
Where(squirrel.Eq{"blocked": false}).
|
|
||||||
ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
users := make([]entity.User, 0)
|
|
||||||
err = u.db.Select(ctx, &users, q, args...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "select query: %s", q)
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make(map[int64]time.Time, 0)
|
|
||||||
for _, user := range users {
|
|
||||||
result[user.Id] = user.LastActiveAt
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u User) ChangePassword(ctx context.Context, userId int64, newPassword string) error {
|
func (u User) ChangePassword(ctx context.Context, userId int64, newPassword string) error {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.ChangePassword")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "User.ChangePassword")
|
||||||
|
|
||||||
@@ -382,38 +252,3 @@ func (u User) ChangePassword(ctx context.Context, userId int64, newPassword stri
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error {
|
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpdateLastActiveAt")
|
|
||||||
|
|
||||||
q := "update users set last_active_at = $1 where id = $2"
|
|
||||||
_, err := u.db.Exec(ctx, q, lastActiveAt, userId)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessagef(err, "user.repo.UpdateLastActiveAt: exec query: %s", q)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func reqUsersQuery(q squirrel.SelectBuilder, reqQuery *domain.UserQuery) squirrel.SelectBuilder {
|
|
||||||
if reqQuery == nil {
|
|
||||||
return q
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.Id != nil {
|
|
||||||
q = q.Where(squirrel.ILike{"id::text": "%" + strconv.Itoa(*reqQuery.Id) + "%"})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.UserId != nil || len(reqQuery.UserId) != 0 { // поиск в ui по фио, но в бд - по id юзера
|
|
||||||
q = q.Where(squirrel.Eq{"id": reqQuery.UserId})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.Description != nil {
|
|
||||||
q = q.Where(squirrel.ILike{"description": "%" + *reqQuery.Description + "%"})
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.Email != nil {
|
|
||||||
q = q.Where(squirrel.ILike{"email": "%" + *reqQuery.Email + "%"})
|
|
||||||
}
|
|
||||||
|
|
||||||
return q
|
|
||||||
}
|
|
||||||
@@ -3,13 +3,12 @@ package repository
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
"github.com/Masterminds/squirrel"
|
||||||
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/isp-kit/db"
|
"github.com/txix-open/isp-kit/db"
|
||||||
"github.com/txix-open/isp-kit/db/query"
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
type UserRole struct {
|
type UserRole struct {
|
||||||
|
|||||||
+94
-191
@@ -1,14 +1,11 @@
|
|||||||
package routes
|
package routes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"isp-admin-service/controller"
|
|
||||||
"isp-admin-service/docs"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/cluster"
|
"github.com/txix-open/isp-kit/cluster"
|
||||||
"github.com/txix-open/isp-kit/common_endpoints"
|
"github.com/txix-open/isp-kit/grpc"
|
||||||
httpEndpoint "github.com/txix-open/isp-kit/http/endpoint"
|
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||||
"github.com/txix-open/isp-kit/http/router"
|
"github.com/txix-open/isp-kit/grpc/isp"
|
||||||
|
"msp-admin-service/controller"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Controllers struct {
|
type Controllers struct {
|
||||||
@@ -20,24 +17,16 @@ type Controllers struct {
|
|||||||
Audit controller.Audit
|
Audit controller.Audit
|
||||||
Role controller.Role
|
Role controller.Role
|
||||||
Permissions controller.Permissions
|
Permissions controller.Permissions
|
||||||
UiSettings controller.UiSettings
|
|
||||||
Download controller.Download
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func EndpointDescriptors() []cluster.EndpointDescriptor {
|
func EndpointDescriptors() []cluster.EndpointDescriptor {
|
||||||
return concatEndpoints(
|
return endpointDescriptors(Controllers{})
|
||||||
endpointDescriptors(Controllers{}),
|
|
||||||
commonEndpoints(),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn
|
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { // nolint:ireturn
|
||||||
muxer := router.New()
|
muxer := grpc.NewMux()
|
||||||
for _, descriptor := range endpointDescriptors(c) {
|
for _, descriptor := range endpointDescriptors(c) {
|
||||||
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||||
}
|
|
||||||
for _, descriptor := range commonEndpoints() {
|
|
||||||
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
|
||||||
}
|
}
|
||||||
return muxer
|
return muxer
|
||||||
}
|
}
|
||||||
@@ -46,224 +35,138 @@ func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // no
|
|||||||
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||||
return []cluster.EndpointDescriptor{
|
return []cluster.EndpointDescriptor{
|
||||||
{
|
{
|
||||||
Path: "admin/auth/login",
|
Path: "admin/auth/login",
|
||||||
Inner: false,
|
Inner: false,
|
||||||
Handler: c.Auth.Login,
|
Handler: c.Auth.Login,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/auth/login_with_oauth",
|
Path: "admin/auth/login_with_sudir",
|
||||||
Inner: false,
|
Inner: false,
|
||||||
Handler: c.Auth.LoginWithOauth,
|
Handler: c.Auth.LoginWithSudir,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/auth/logout",
|
Path: "admin/auth/logout",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.Auth.Logout,
|
Handler: c.Auth.Logout,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/auth/logout_with_reason",
|
Path: "admin/user/get_profile",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.Auth.LogoutWithReason,
|
Handler: c.User.GetProfile,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/get_profile",
|
Path: "admin/user/get_design",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.User.GetProfile,
|
Handler: c.Customization.GetUIDesign,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/get_design",
|
Path: "admin/user/get_users",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.Customization.GetUIDesign,
|
Handler: c.User.GetUsers,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/get_users",
|
Path: "admin/user/create_user",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.User.GetUsers,
|
Extra: cluster.RequireAdminPermission("user_create"),
|
||||||
HttpMethod: http.MethodPost,
|
Handler: c.User.CreateUser,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/get_all_users",
|
Path: "admin/user/update_user",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.User.GetAllUsers,
|
Extra: cluster.RequireAdminPermission("user_update"),
|
||||||
HttpMethod: http.MethodPost,
|
Handler: c.User.UpdateUser,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/create_user",
|
Path: "admin/user/delete_user",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("user_create"),
|
Extra: cluster.RequireAdminPermission("user_delete"),
|
||||||
Handler: c.User.CreateUser,
|
Handler: c.User.DeleteUser,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/update_user",
|
Path: "admin/user/block_user",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("user_update"),
|
Extra: cluster.RequireAdminPermission("user_block"),
|
||||||
Handler: c.User.UpdateUser,
|
Handler: c.User.Block,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/delete_user",
|
Path: "admin/user/get_by_id",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("user_delete"),
|
Handler: c.User.GetById,
|
||||||
Handler: c.User.DeleteUser,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/block_user",
|
Path: "admin/user/change_password",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("user_block"),
|
Handler: c.User.ChangePassword,
|
||||||
Handler: c.User.Block,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/get_by_id",
|
Path: "admin/role/all",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.User.GetById,
|
Extra: cluster.RequireAdminPermission("role_view"),
|
||||||
HttpMethod: http.MethodPost,
|
Handler: c.Role.All,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/change_password",
|
Path: "admin/user/get_permissions",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.User.ChangePassword,
|
Extra: cluster.RequireAdminPermission("role_view"),
|
||||||
HttpMethod: http.MethodPost,
|
Handler: c.Permissions.GetPermissions,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/role/all",
|
Path: "admin/role/create",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("role_view"),
|
Extra: cluster.RequireAdminPermission("role_add"),
|
||||||
Handler: c.Role.All,
|
Handler: c.Role.CreateRole,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/user/get_permissions",
|
Path: "admin/role/update",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("role_view"),
|
Extra: cluster.RequireAdminPermission("role_update"),
|
||||||
Handler: c.Permissions.GetPermissions,
|
Handler: c.Role.UpdateRole,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/role/create",
|
Path: "admin/role/delete",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("role_add"),
|
Extra: cluster.RequireAdminPermission("role_delete"),
|
||||||
Handler: c.Role.CreateRole,
|
Handler: c.Role.DeleteRole,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/role/update",
|
Path: "admin/session/all",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("role_update"),
|
Extra: cluster.RequireAdminPermission("session_view"),
|
||||||
Handler: c.Role.UpdateRole,
|
Handler: c.Session.All,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/role/delete",
|
Path: "admin/session/revoke",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("role_delete"),
|
Extra: cluster.RequireAdminPermission("session_revoke"),
|
||||||
Handler: c.Role.DeleteRole,
|
Handler: c.Session.Revoke,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/session/all",
|
Path: "admin/log/all",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("session_view"),
|
Extra: cluster.RequireAdminPermission("security_log_view"),
|
||||||
Handler: c.Session.All,
|
Handler: c.Audit.All,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/session/revoke",
|
Path: "admin/log/events",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("session_revoke"),
|
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||||
Handler: c.Session.Revoke,
|
Handler: c.Audit.Events,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/log/all",
|
Path: "admin/log/set_events",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("security_log_view"),
|
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||||
Handler: c.Audit.All,
|
Handler: c.Audit.SetEvents,
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/log/events",
|
Path: "admin/secure/authenticate",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
Handler: c.Secure.Authenticate,
|
||||||
Handler: c.Audit.Events,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/log/set_events",
|
Path: "admin/secure/authorize",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
Handler: c.Secure.Authorize,
|
||||||
Handler: c.Audit.SetEvents,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "admin/secure/authenticate",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Secure.Authenticate,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "admin/secure/authorize",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Secure.Authorize,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "admin/ui_settings/oauth",
|
|
||||||
Inner: false,
|
|
||||||
Handler: c.UiSettings.OauthSettings,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
|
||||||
// download
|
|
||||||
{
|
|
||||||
Path: "user/download",
|
|
||||||
Inner: true,
|
|
||||||
Extra: cluster.RequireAdminPermission("data_download"),
|
|
||||||
Handler: c.Download.Users,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "session/download",
|
|
||||||
Inner: true,
|
|
||||||
Extra: cluster.RequireAdminPermission("data_download"),
|
|
||||||
Handler: c.Download.Sessions,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "log/download",
|
|
||||||
Inner: true,
|
|
||||||
Extra: cluster.RequireAdminPermission("data_download"),
|
|
||||||
Handler: c.Download.Audit,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "role/download",
|
|
||||||
Inner: true,
|
|
||||||
Extra: cluster.RequireAdminPermission("data_download"),
|
|
||||||
Handler: c.Download.Roles,
|
|
||||||
HttpMethod: http.MethodPost,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func commonEndpoints() []cluster.EndpointDescriptor {
|
|
||||||
return common_endpoints.CommonEndpoints(
|
|
||||||
"isp-admin-service",
|
|
||||||
common_endpoints.WithSwaggerEndpoint(docs.SwaggerJson),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concatEndpoints(endpoints ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
|
|
||||||
var result []cluster.EndpointDescriptor
|
|
||||||
for _, desc := range endpoints {
|
|
||||||
result = append(result, desc...)
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
+19
-23
@@ -4,19 +4,18 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/conf"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
"golang.org/x/sync/errgroup"
|
"golang.org/x/sync/errgroup"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuditRepository interface {
|
type AuditRepository interface {
|
||||||
Insert(ctx context.Context, log entity.Audit) (int, error)
|
Insert(ctx context.Context, log entity.Audit) (int, error)
|
||||||
AllByRequest(ctx context.Context, req domain.AuditPageRequest) ([]entity.Audit, error)
|
All(ctx context.Context, limit int, offset int) ([]entity.Audit, error)
|
||||||
Count(ctx context.Context, reqQuery *domain.AuditQuery) (int64, error)
|
Count(ctx context.Context) (int64, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuditEventRepository interface {
|
type AuditEventRepository interface {
|
||||||
@@ -46,7 +45,6 @@ func NewAudit(
|
|||||||
entity.EventSuccessLogout: true,
|
entity.EventSuccessLogout: true,
|
||||||
entity.EventRoleChanged: true,
|
entity.EventRoleChanged: true,
|
||||||
entity.EventUserChanged: true,
|
entity.EventUserChanged: true,
|
||||||
entity.EventUserBlocked: true,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
eventName := make(map[string]conf.AuditEventSetting)
|
eventName := make(map[string]conf.AuditEventSetting)
|
||||||
@@ -87,46 +85,44 @@ func (s Audit) SaveAuditAsync(ctx context.Context, userId int64, message string,
|
|||||||
Event: event,
|
Event: event,
|
||||||
CreatedAt: time.Now().UTC(),
|
CreatedAt: time.Now().UTC(),
|
||||||
}
|
}
|
||||||
_, err = s.auditRep.Insert(ctx, audit)
|
_, err = s.auditRep.Insert(context.Background(), audit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.logger.Error(ctx, "insert audit", log.Any("error", err))
|
s.logger.Error(ctx, "insert audit", log.Any("error", err))
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) {
|
func (s Audit) All(ctx context.Context, limit int, offset int) (*domain.AuditResponse, error) {
|
||||||
var logs []entity.Audit
|
|
||||||
var total int64
|
|
||||||
|
|
||||||
group, ctx := errgroup.WithContext(ctx)
|
group, ctx := errgroup.WithContext(ctx)
|
||||||
|
var tokens []entity.Audit
|
||||||
|
var total int64
|
||||||
|
var err error
|
||||||
group.Go(func() error {
|
group.Go(func() error {
|
||||||
var err error
|
tokens, err = s.auditRep.All(ctx, limit, offset)
|
||||||
logs, err = s.auditRep.AllByRequest(ctx, req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "get all audit")
|
return errors.WithMessage(err, "get all audit")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
group.Go(func() error {
|
group.Go(func() error {
|
||||||
var err error
|
total, err = s.auditRep.Count(ctx)
|
||||||
total, err = s.auditRep.Count(ctx, req.Query)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "count all audit")
|
return errors.WithMessage(err, "count all audit")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
err := group.Wait()
|
err = group.Wait()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "wait workers")
|
return nil, errors.WithMessage(err, "wait workers")
|
||||||
}
|
}
|
||||||
|
|
||||||
items := make([]domain.Audit, 0)
|
items := make([]domain.Audit, 0)
|
||||||
for _, log := range logs {
|
for _, token := range tokens {
|
||||||
items = append(items, domain.Audit{
|
items = append(items, domain.Audit{
|
||||||
Id: log.Id,
|
Id: token.Id,
|
||||||
UserId: log.UserId,
|
UserId: token.UserId,
|
||||||
Message: log.Message,
|
Message: token.Message,
|
||||||
CreatedAt: log.CreatedAt,
|
CreatedAt: token.CreatedAt,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
result := domain.AuditResponse{
|
result := domain.AuditResponse{
|
||||||
|
|||||||
+34
-66
@@ -5,12 +5,11 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuthTransaction interface {
|
type AuthTransaction interface {
|
||||||
@@ -30,9 +29,8 @@ type auditService interface {
|
|||||||
|
|
||||||
type userRepository interface {
|
type userRepository interface {
|
||||||
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||||
UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
||||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||||
UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type tokenService interface {
|
type tokenService interface {
|
||||||
@@ -40,15 +38,15 @@ type tokenService interface {
|
|||||||
RevokeAllByUserId(ctx context.Context, userId int64) error
|
RevokeAllByUserId(ctx context.Context, userId int64) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type oauthService interface {
|
type sudirService interface {
|
||||||
Authenticate(ctx context.Context, request domain.LoginOauthRequest, repo roleRepo) (*entity.OauthUser, error)
|
Authenticate(ctx context.Context, authCode string, repo roleRepo) (*entity.SudirUser, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Auth struct {
|
type Auth struct {
|
||||||
userRepository userRepository
|
userRepository userRepository
|
||||||
txRunner AuthTransactionRunner
|
txRunner AuthTransactionRunner
|
||||||
tokenService tokenService
|
tokenService tokenService
|
||||||
oauthService oauthService
|
sudirService sudirService
|
||||||
auditService auditService
|
auditService auditService
|
||||||
logger log.Logger
|
logger log.Logger
|
||||||
maxInFlightLoginRequests int64
|
maxInFlightLoginRequests int64
|
||||||
@@ -60,7 +58,7 @@ func NewAuth(
|
|||||||
userRepository userRepository,
|
userRepository userRepository,
|
||||||
txRunner AuthTransactionRunner,
|
txRunner AuthTransactionRunner,
|
||||||
tokenService tokenService,
|
tokenService tokenService,
|
||||||
oauthService oauthService,
|
sudirService sudirService,
|
||||||
auditService auditService,
|
auditService auditService,
|
||||||
logger log.Logger,
|
logger log.Logger,
|
||||||
delayLoginRequestInSec int,
|
delayLoginRequestInSec int,
|
||||||
@@ -70,7 +68,7 @@ func NewAuth(
|
|||||||
userRepository: userRepository,
|
userRepository: userRepository,
|
||||||
txRunner: txRunner,
|
txRunner: txRunner,
|
||||||
tokenService: tokenService,
|
tokenService: tokenService,
|
||||||
oauthService: oauthService,
|
sudirService: sudirService,
|
||||||
auditService: auditService,
|
auditService: auditService,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
delayLoginRequest: time.Duration(delayLoginRequestInSec) * time.Second,
|
delayLoginRequest: time.Duration(delayLoginRequestInSec) * time.Second,
|
||||||
@@ -100,8 +98,8 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
|||||||
return errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
return errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return errors.WithMessage(err, "get user by email")
|
return errors.WithMessage(err, "get user by email")
|
||||||
case user.OauthUserId != nil:
|
case user.SudirUserId != nil:
|
||||||
return domain.ErrOauthAuthorization
|
return domain.ErrSudirAuthorization
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Blocked {
|
if user.Blocked {
|
||||||
@@ -120,12 +118,6 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
|||||||
return errors.WithMessage(err, "generate token")
|
return errors.WithMessage(err, "generate token")
|
||||||
}
|
}
|
||||||
|
|
||||||
lastActiveAt := time.Now().UTC()
|
|
||||||
err = tx.UpdateLastActiveAt(ctx, user.Id, lastActiveAt)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "update user last_active_at")
|
|
||||||
}
|
|
||||||
|
|
||||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через форму входа", entity.EventSuccessLogin)
|
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через форму входа", entity.EventSuccessLogin)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -141,7 +133,7 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
||||||
var (
|
var (
|
||||||
user *entity.User
|
user *entity.User
|
||||||
|
|
||||||
@@ -150,41 +142,40 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
|
|||||||
)
|
)
|
||||||
|
|
||||||
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
||||||
oauthUser, err := a.oauthService.Authenticate(ctx, request, tx)
|
sudirUser, err := a.sudirService.Authenticate(ctx, request.AuthCode, tx)
|
||||||
|
|
||||||
var authErr *entity.OauthAuthError
|
var authErr *entity.SudirAuthError
|
||||||
switch {
|
switch {
|
||||||
case errors.As(err, &authErr):
|
case errors.As(err, &authErr):
|
||||||
a.logger.Error(ctx, "oauth authenticate: error occurred", log.String("error", err.Error()))
|
a.logger.Error(ctx, "sudir authenticate: error occurred", log.String("error", err.Error()))
|
||||||
return domain.ErrUnauthenticated
|
return domain.ErrUnauthenticated
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return errors.WithMessage(err, "oauth authenticate")
|
return errors.WithMessage(err, "sudir authenticate")
|
||||||
case oauthUser.OauthUserId == "" || oauthUser.Email == "":
|
case sudirUser.SudirUserId == "" || sudirUser.Email == "":
|
||||||
a.logger.Error(ctx, "oauth authenticate: missing oauthUserId or email",
|
a.logger.Error(ctx, "sudir authenticate: missing sudirUserId or email",
|
||||||
log.String("userId", oauthUser.OauthUserId),
|
log.String("userId", sudirUser.SudirUserId),
|
||||||
log.String("email", oauthUser.Email))
|
log.String("email", sudirUser.Email))
|
||||||
return domain.ErrUnauthenticated
|
return domain.ErrUnauthenticated
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err = tx.UpsertByOauthUserId(ctx, entity.User{
|
user, err = tx.UpsertBySudirUserId(ctx, entity.User{
|
||||||
OauthUserId: &oauthUser.OauthUserId,
|
SudirUserId: &sudirUser.SudirUserId,
|
||||||
FirstName: oauthUser.FirstName,
|
FirstName: sudirUser.FirstName,
|
||||||
LastName: oauthUser.LastName,
|
LastName: sudirUser.LastName,
|
||||||
FullName: oauthUser.FullName,
|
Email: sudirUser.Email,
|
||||||
Email: oauthUser.Email,
|
|
||||||
Password: "",
|
Password: "",
|
||||||
Blocked: false,
|
Blocked: false,
|
||||||
UpdatedAt: time.Now().UTC(),
|
UpdatedAt: time.Now().UTC(),
|
||||||
CreatedAt: time.Now().UTC(),
|
CreatedAt: time.Now().UTC(),
|
||||||
})
|
})
|
||||||
if errors.Is(err, domain.ErrUserIsBlocked) {
|
if errors.Is(err, domain.ErrUserIsBlocked) {
|
||||||
return errors.Errorf("user with oauth user id = %s is blocked", oauthUser.OauthUserId)
|
return errors.Errorf("user with sudir user id = %s is blocked", sudirUser.SudirUserId)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "upsert by oauth user id")
|
return errors.WithMessage(err, "upsert by sudir user id")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), oauthUser.RoleIds)
|
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), sudirUser.RoleIds)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "upsert user role links")
|
return errors.WithMessage(err, "upsert user role links")
|
||||||
}
|
}
|
||||||
@@ -194,19 +185,13 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
|
|||||||
return errors.WithMessage(err, "generate token")
|
return errors.WithMessage(err, "generate token")
|
||||||
}
|
}
|
||||||
|
|
||||||
lastActiveAt := time.Now().UTC()
|
|
||||||
err = tx.UpdateLastActiveAt(ctx, user.Id, lastActiveAt)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "update user last_active_at")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "auth transaction")
|
return nil, errors.WithMessage(err, "auth transaction")
|
||||||
}
|
}
|
||||||
|
|
||||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через OAuth", entity.EventSuccessLogin)
|
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через СУДИР", entity.EventSuccessLogin)
|
||||||
|
|
||||||
return &domain.LoginResponse{
|
return &domain.LoginResponse{
|
||||||
Token: tokenString,
|
Token: tokenString,
|
||||||
@@ -215,30 +200,13 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a Auth) Logout(ctx context.Context, adminId int64, request *domain.LogoutRequest) error {
|
func (a Auth) Logout(ctx context.Context, adminId int64) error {
|
||||||
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
err := a.tokenService.RevokeAllByUserId(ctx, adminId)
|
||||||
err := a.tokenService.RevokeAllByUserId(ctx, adminId)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "revoke all tokens by user id")
|
|
||||||
}
|
|
||||||
|
|
||||||
lastActiveAt := time.Now().UTC()
|
|
||||||
err = tx.UpdateLastActiveAt(ctx, adminId, lastActiveAt)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "update user last_active_at")
|
|
||||||
}
|
|
||||||
|
|
||||||
if request != nil && request.Reason == "idle" {
|
|
||||||
a.auditService.SaveAuditAsync(ctx, adminId, "Выход по бездействию", entity.EventSuccessLogout)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
a.auditService.SaveAuditAsync(ctx, adminId, "Выход", entity.EventSuccessLogout)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "auth transaction")
|
return errors.WithMessage(err, "revoke all tokens by user id")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
a.auditService.SaveAuditAsync(ctx, adminId, "Выход", entity.EventSuccessLogout)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -3,9 +3,9 @@ package delete_old_audit_worker
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/bgjob"
|
"github.com/txix-open/bgjob"
|
||||||
"github.com/txix-open/isp-kit/bgjobx"
|
"github.com/txix-open/isp-kit/bgjobx"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -4,12 +4,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/conf"
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"github.com/txix-open/bgjob"
|
"github.com/txix-open/bgjob"
|
||||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
|
"msp-admin-service/conf"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -40,13 +38,13 @@ func NewService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Service) Handle(ctx context.Context, _ bgjob.Job) handler.Result {
|
func (s Service) Handle(ctx context.Context, _ bgjob.Job) bgjob.Result {
|
||||||
err := s.deleteOldAudit(ctx)
|
err := s.deleteOldAudit(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return handler.Retry(defaultRetryTimeout, errors.WithMessage(err, "sync state with worker"))
|
return bgjob.Retry(defaultRetryTimeout, errors.WithMessage(err, "sync state with worker"))
|
||||||
}
|
}
|
||||||
|
|
||||||
return handler.Reschedule(handler.ByAfterTime(s.syncPeriod, time.Now()))
|
return bgjob.Reschedule(s.syncPeriod)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Service) deleteOldAudit(ctx context.Context) error {
|
func (s Service) deleteOldAudit(ctx context.Context) error {
|
||||||
|
|||||||
@@ -1,325 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/csv"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"slices"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
requestLimit = 1000
|
|
||||||
foundSymbol = "+"
|
|
||||||
notFoundSymbol = "-"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Download struct {
|
|
||||||
auditService Audit
|
|
||||||
userService User
|
|
||||||
tokenService Token
|
|
||||||
roleService Role
|
|
||||||
permissionService Permission
|
|
||||||
loc *time.Location
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDownload(
|
|
||||||
auditService Audit,
|
|
||||||
userService User,
|
|
||||||
tokenService Token,
|
|
||||||
roleService Role,
|
|
||||||
permissionService Permission,
|
|
||||||
) Download {
|
|
||||||
loc, _ := time.LoadLocation("Europe/Moscow")
|
|
||||||
return Download{
|
|
||||||
auditService: auditService,
|
|
||||||
userService: userService,
|
|
||||||
tokenService: tokenService,
|
|
||||||
roleService: roleService,
|
|
||||||
permissionService: permissionService,
|
|
||||||
loc: loc,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Download) DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
|
|
||||||
req.Limit = requestLimit
|
|
||||||
req.Offset = 0
|
|
||||||
|
|
||||||
response, err := s.auditService.All(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get audit")
|
|
||||||
}
|
|
||||||
|
|
||||||
if response.TotalCount == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Audit")))
|
|
||||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
|
||||||
w.Header().Set("transfer-encoding", "chunked")
|
|
||||||
|
|
||||||
csvWriter := csv.NewWriter(w)
|
|
||||||
defer csvWriter.Flush()
|
|
||||||
|
|
||||||
err = writeCsvLine(csvWriter, entity.AuditColumnNames())
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write auditColumns to csv")
|
|
||||||
}
|
|
||||||
|
|
||||||
userById, err := s.getUsersList(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get users list")
|
|
||||||
}
|
|
||||||
|
|
||||||
itemsCount := len(response.Items)
|
|
||||||
for {
|
|
||||||
for _, audit := range response.Items {
|
|
||||||
username := getUsername(userById, audit.UserId)
|
|
||||||
|
|
||||||
row := []string{username, s.formatTime(&audit.CreatedAt, false), audit.Message}
|
|
||||||
err = writeCsvLine(csvWriter, row)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write audit row to csv")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if itemsCount >= response.TotalCount {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Offset += requestLimit
|
|
||||||
response, err = s.auditService.All(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get audit")
|
|
||||||
}
|
|
||||||
|
|
||||||
itemsCount += len(response.Items)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Download) DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
|
|
||||||
req.Limit = requestLimit
|
|
||||||
req.Offset = 0
|
|
||||||
|
|
||||||
response, err := s.tokenService.All(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get sessions")
|
|
||||||
}
|
|
||||||
|
|
||||||
if response.TotalCount == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Sessions")))
|
|
||||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
|
||||||
w.Header().Set("transfer-encoding", "chunked")
|
|
||||||
|
|
||||||
csvWriter := csv.NewWriter(w)
|
|
||||||
defer csvWriter.Flush()
|
|
||||||
|
|
||||||
err = writeCsvLine(csvWriter, entity.SessionColumnNames())
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write sessionColumns to csv")
|
|
||||||
}
|
|
||||||
|
|
||||||
userById, err := s.getUsersList(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get users list")
|
|
||||||
}
|
|
||||||
|
|
||||||
itemsCount := len(response.Items)
|
|
||||||
for {
|
|
||||||
for _, session := range response.Items {
|
|
||||||
row := []string{
|
|
||||||
getUsername(userById, session.UserId),
|
|
||||||
strconv.Itoa(session.Id),
|
|
||||||
s.formatTime(&session.CreatedAt, false),
|
|
||||||
s.formatTime(&session.ExpiredAt, false),
|
|
||||||
session.StatusRus()}
|
|
||||||
|
|
||||||
err = writeCsvLine(csvWriter, row)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write session row to csv")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if itemsCount >= response.TotalCount {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Offset += requestLimit
|
|
||||||
response, err = s.tokenService.All(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get sessions")
|
|
||||||
}
|
|
||||||
|
|
||||||
itemsCount += len(response.Items)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
|
|
||||||
req.Limit = requestLimit
|
|
||||||
req.Offset = 0
|
|
||||||
|
|
||||||
users, err := s.userService.GetUsers(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get users")
|
|
||||||
}
|
|
||||||
|
|
||||||
roles, err := s.roleService.All(ctx, domain.RoleAllRequest{})
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get roles")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(users.Items) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Users")))
|
|
||||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
|
||||||
w.Header().Set("transfer-encoding", "chunked")
|
|
||||||
|
|
||||||
csvWriter := csv.NewWriter(w)
|
|
||||||
defer csvWriter.Flush()
|
|
||||||
|
|
||||||
err = writeCsvLine(csvWriter, entity.UserColumnNames())
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write userColumns to csv")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, user := range users.Items {
|
|
||||||
row := []string{strconv.Itoa(int(user.Id)),
|
|
||||||
user.FullName,
|
|
||||||
user.Description,
|
|
||||||
user.Email,
|
|
||||||
getRoleNamesByIds(roles, user.Roles),
|
|
||||||
s.formatTime(user.LastSessionCreatedAt, true)}
|
|
||||||
|
|
||||||
err = writeCsvLine(csvWriter, row)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write user row to csv")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) error {
|
|
||||||
roles, err := s.roleService.All(ctx, domain.RoleAllRequest{})
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get roles")
|
|
||||||
}
|
|
||||||
|
|
||||||
perms := s.permissionService.All(ctx)
|
|
||||||
|
|
||||||
if len(perms) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
columns := entity.RoleColumnNames()
|
|
||||||
for _, role := range roles {
|
|
||||||
columns = append(columns, role.Name)
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Roles")))
|
|
||||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
|
||||||
w.Header().Set("transfer-encoding", "chunked")
|
|
||||||
|
|
||||||
csvWriter := csv.NewWriter(w)
|
|
||||||
defer csvWriter.Flush()
|
|
||||||
|
|
||||||
err = writeCsvLine(csvWriter, columns)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write role columns to csv")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, perm := range perms {
|
|
||||||
row := []string{perm.Name, perm.Key}
|
|
||||||
|
|
||||||
for _, role := range roles {
|
|
||||||
if slices.Contains(role.Permissions, perm.Key) {
|
|
||||||
row = append(row, foundSymbol)
|
|
||||||
} else {
|
|
||||||
row = append(row, notFoundSymbol)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
err = writeCsvLine(csvWriter, row)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write role row to csv")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
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]domain.User)
|
|
||||||
for _, user := range users.Items {
|
|
||||||
userById[int(user.Id)] = user
|
|
||||||
}
|
|
||||||
|
|
||||||
return userById, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func getUsername(userById map[int]domain.User, userId int) string {
|
|
||||||
user, ok := userById[userId]
|
|
||||||
if !ok {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return user.FullName
|
|
||||||
}
|
|
||||||
|
|
||||||
func getRoleNamesByIds(roles []domain.Role, roleIds []int) string {
|
|
||||||
names := make([]string, 0)
|
|
||||||
for _, role := range roles {
|
|
||||||
if slices.Contains(roleIds, role.Id) {
|
|
||||||
names = append(names, role.Name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return strings.Join(names, ", ")
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeCsvLine(csvWriter *csv.Writer, line []string) error {
|
|
||||||
err := csvWriter.Write(line)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "write line to csv")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func getCsvFileName(pageName string) string {
|
|
||||||
return fmt.Sprintf("%s_%s.%s", pageName, time.Now().Format("02-01-2006_15:04:05"), "csv")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Download) formatTime(t *time.Time, onlyDate bool) string {
|
|
||||||
if t == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
if onlyDate {
|
|
||||||
return t.In(s.loc).Format("02-01-2006")
|
|
||||||
}
|
|
||||||
|
|
||||||
return t.In(s.loc).Format("02-01-2006 15:04:05")
|
|
||||||
}
|
|
||||||
@@ -3,9 +3,9 @@ package inactive_worker
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/bgjob"
|
"github.com/txix-open/bgjob"
|
||||||
"github.com/txix-open/isp-kit/bgjobx"
|
"github.com/txix-open/isp-kit/bgjobx"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -4,13 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/conf"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/bgjob"
|
"github.com/txix-open/bgjob"
|
||||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -21,54 +19,67 @@ type AuditRepo interface {
|
|||||||
SaveAuditAsync(ctx context.Context, userId int64, message string, event string)
|
SaveAuditAsync(ctx context.Context, userId int64, message string, event string)
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserRepo interface {
|
type TokenRepo interface {
|
||||||
LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error)
|
LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserRepo interface {
|
||||||
Block(ctx context.Context, userId int) (*entity.User, error)
|
Block(ctx context.Context, userId int) (*entity.User, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type LdapService interface {
|
||||||
|
SyncGroups(ctx context.Context, user entity.User) error
|
||||||
|
}
|
||||||
|
|
||||||
type UserRoleRepo interface {
|
type UserRoleRepo interface {
|
||||||
UpsertUserRoleLinks(ctx context.Context, id int, roleIds []int) error
|
UpsertUserRoleLinks(ctx context.Context, id int, roleIds []int) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
|
tokenRepo TokenRepo
|
||||||
userRepo UserRepo
|
userRepo UserRepo
|
||||||
auditRepo AuditRepo
|
auditRepo AuditRepo
|
||||||
userRoleRepo UserRoleRepo
|
userRoleRepo UserRoleRepo
|
||||||
|
ldapService LdapService
|
||||||
threshold time.Duration
|
threshold time.Duration
|
||||||
syncPeriod time.Duration
|
syncPeriod time.Duration
|
||||||
logger log.Logger
|
logger log.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInactiveBlocker(
|
func NewInactiveBlocker(
|
||||||
|
tokensRepo TokenRepo,
|
||||||
userRepo UserRepo,
|
userRepo UserRepo,
|
||||||
auditRepo AuditRepo,
|
auditRepo AuditRepo,
|
||||||
userRoleRepo UserRoleRepo,
|
userRoleRepo UserRoleRepo,
|
||||||
|
ldapService LdapService,
|
||||||
config conf.BlockInactiveWorker,
|
config conf.BlockInactiveWorker,
|
||||||
logger log.Logger,
|
logger log.Logger,
|
||||||
) Service {
|
) Service {
|
||||||
return Service{
|
return Service{
|
||||||
|
tokenRepo: tokensRepo,
|
||||||
userRepo: userRepo,
|
userRepo: userRepo,
|
||||||
auditRepo: auditRepo,
|
auditRepo: auditRepo,
|
||||||
userRoleRepo: userRoleRepo,
|
userRoleRepo: userRoleRepo,
|
||||||
|
ldapService: ldapService,
|
||||||
threshold: time.Duration(config.DaysThreshold) * 24 * time.Hour,
|
threshold: time.Duration(config.DaysThreshold) * 24 * time.Hour,
|
||||||
syncPeriod: time.Minute * time.Duration(config.RunIntervalInMinutes),
|
syncPeriod: time.Minute * time.Duration(config.RunIntervalInMinutes),
|
||||||
logger: logger,
|
logger: logger,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w Service) Handle(ctx context.Context, _ bgjob.Job) handler.Result {
|
func (w Service) Handle(ctx context.Context, _ bgjob.Job) bgjob.Result {
|
||||||
ctx = log.ToContext(ctx, log.String("worker", "inactiveBlocker"))
|
ctx = log.ToContext(ctx, log.String("worker", "inactiveBlocker"))
|
||||||
w.logger.Debug(ctx, "begin work")
|
w.logger.Debug(ctx, "begin work")
|
||||||
err := w.do(ctx)
|
err := w.do(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return handler.Retry(defaultRetryTimeout, errors.WithMessage(err, "sync state with worker"))
|
return bgjob.Retry(defaultRetryTimeout, errors.WithMessage(err, "sync state with worker"))
|
||||||
}
|
}
|
||||||
w.logger.Debug(ctx, "end work")
|
w.logger.Debug(ctx, "end work")
|
||||||
return handler.Reschedule(handler.ByAfterTime(w.syncPeriod, time.Now()))
|
return bgjob.Reschedule(w.syncPeriod)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w Service) do(ctx context.Context) error {
|
func (w Service) do(ctx context.Context) error {
|
||||||
lastAccess, err := w.userRepo.LastAccessNotBlockedUsers(ctx)
|
lastAccess, err := w.tokenRepo.LastAccessNotBlockedUsers(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "get last access times")
|
return errors.WithMessage(err, "get last access times")
|
||||||
}
|
}
|
||||||
@@ -81,7 +92,7 @@ func (w Service) do(ctx context.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
w.logger.Info(ctx, "block inactive user", log.Int64("userId", userId), log.Any("lastAccessTime", lastAccess))
|
w.logger.Info(ctx, "block inactive user", log.Int64("userId", userId), log.Any("lastAccessTime", lastAccess))
|
||||||
_, err := w.userRepo.Block(ctx, int(userId))
|
user, err := w.userRepo.Block(ctx, int(userId))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessagef(err, "block user %d", userId)
|
return errors.WithMessagef(err, "block user %d", userId)
|
||||||
}
|
}
|
||||||
@@ -91,6 +102,11 @@ func (w Service) do(ctx context.Context) error {
|
|||||||
return errors.WithMessage(err, "empty user roles links")
|
return errors.WithMessage(err, "empty user roles links")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = w.ldapService.SyncGroups(ctx, *user)
|
||||||
|
if err != nil {
|
||||||
|
w.logger.Error(ctx, errors.WithMessage(err, "remove ldap groups"))
|
||||||
|
}
|
||||||
|
|
||||||
w.auditRepo.SaveAuditAsync(ctx, userId, "Блокировка неактивной УЗ", entity.EventUserChanged)
|
w.auditRepo.SaveAuditAsync(ctx, userId, "Блокировка неактивной УЗ", entity.EventUserChanged)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package ldap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/txix-open/isp-kit/log"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Repo interface {
|
||||||
|
IsExist(ctx context.Context, dn string) (bool, error)
|
||||||
|
DnByUserPrincipalName(ctx context.Context, principalName string) (string, error)
|
||||||
|
ModifyMemberAttr(ctx context.Context, userDn string, groupDn string, operation string) error
|
||||||
|
Close() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type RoleRepo interface {
|
||||||
|
All(ctx context.Context) ([]entity.Role, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserRoleRepo interface {
|
||||||
|
GetRolesByUserIds(ctx context.Context, identity []int) ([]entity.UserRole, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepoSupplier func(config *conf.Ldap) (Repo, error)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
config *conf.Ldap
|
||||||
|
repoSuppler RepoSupplier
|
||||||
|
userRoleRepo UserRoleRepo
|
||||||
|
roleRepo RoleRepo
|
||||||
|
logger log.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(
|
||||||
|
config *conf.Ldap,
|
||||||
|
repoSuppler RepoSupplier,
|
||||||
|
userRoleRepo UserRoleRepo,
|
||||||
|
roleRepo RoleRepo,
|
||||||
|
logger log.Logger,
|
||||||
|
) Service {
|
||||||
|
return Service{
|
||||||
|
config: config,
|
||||||
|
repoSuppler: repoSuppler,
|
||||||
|
userRoleRepo: userRoleRepo,
|
||||||
|
roleRepo: roleRepo,
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Service) SyncGroupsAsync(ctx context.Context, user entity.User) {
|
||||||
|
ctx = context.WithoutCancel(ctx)
|
||||||
|
go func() {
|
||||||
|
err := s.SyncGroups(ctx, user)
|
||||||
|
if err != nil {
|
||||||
|
s.logger.Warn(ctx, errors.WithMessage(err, "ldap sync groups"))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Service) SyncGroups(ctx context.Context, user entity.User) error {
|
||||||
|
ctx = log.ToContext(ctx, log.String("process", "ldap"), log.Int64("userId", user.Id))
|
||||||
|
|
||||||
|
ldapRepo, err := s.repoSuppler(s.config)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "init ldap repository")
|
||||||
|
}
|
||||||
|
defer ldapRepo.Close()
|
||||||
|
|
||||||
|
if user.SudirUserId == nil || *user.SudirUserId == "" {
|
||||||
|
s.logger.Info(ctx, "user has not sudir user id, skip")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
userDn, err := ldapRepo.DnByUserPrincipalName(ctx, *user.SudirUserId)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessagef(err, "get user dn by principal name %s", *user.SudirUserId)
|
||||||
|
}
|
||||||
|
|
||||||
|
userRoles, err := s.userRoleRepo.GetRolesByUserIds(ctx, []int{int(user.Id)})
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "ger roles by user ids")
|
||||||
|
}
|
||||||
|
|
||||||
|
allRoles, err := s.roleRepo.All(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "get all roles")
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range allRoles {
|
||||||
|
role := allRoles[i]
|
||||||
|
contains := slices.ContainsFunc(userRoles, func(userRole entity.UserRole) bool {
|
||||||
|
return userRole.RoleId == role.Id
|
||||||
|
})
|
||||||
|
operation := entity.GroupOperationDelete
|
||||||
|
if contains {
|
||||||
|
operation = entity.GroupOperationAdd
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.handleRole(ctx, role, userDn, operation, ldapRepo)
|
||||||
|
if errors.Is(err, domain.ErrNoActionRequired) {
|
||||||
|
s.logger.Info(ctx, "no action required, role is already synced")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.logger.Error(ctx, errors.WithMessage(err, "handle role"))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Service) handleRole(
|
||||||
|
ctx context.Context,
|
||||||
|
role entity.Role,
|
||||||
|
userDn string,
|
||||||
|
operation string,
|
||||||
|
ldapRepo Repo,
|
||||||
|
) error {
|
||||||
|
if role.ExternalGroup == "" {
|
||||||
|
s.logger.Info(ctx, "role has no external group mapping, skip", log.Int("roleId", role.Id))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
exist, err := ldapRepo.IsExist(ctx, role.ExternalGroup)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessagef(err, "check dn %s is exist", role.ExternalGroup)
|
||||||
|
}
|
||||||
|
if !exist {
|
||||||
|
s.logger.Info(ctx, "role doesn't exist in ldap, skip", log.Int("roleId", role.Id))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err = ldapRepo.ModifyMemberAttr(ctx, userDn, role.ExternalGroup, operation)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "modify group member attr")
|
||||||
|
}
|
||||||
|
|
||||||
|
s.logger.Info(ctx, fmt.Sprintf("group %s synced for user %s, operation %s", role.ExternalGroup, userDn, operation))
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type oauthRepo interface {
|
|
||||||
GetToken(ctx context.Context, creds entity.ClientSetting) (*entity.OauthTokenResponse, error)
|
|
||||||
GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type roleRepo interface {
|
|
||||||
GetRolesByExternalGroup(ctx context.Context, groups []string) ([]entity.Role, error)
|
|
||||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Oauth struct {
|
|
||||||
oauthRepo oauthRepo
|
|
||||||
clientSettings map[string]conf.OauthClientConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewOauth(settings []conf.OauthClientConfig, oauthRepo oauthRepo) (Oauth, error) {
|
|
||||||
clientSettings := make(map[string]conf.OauthClientConfig, len(settings))
|
|
||||||
for i, setting := range settings {
|
|
||||||
_, ok := clientSettings[setting.ClientName]
|
|
||||||
if ok {
|
|
||||||
return Oauth{}, errors.Errorf("client setting [%d] has non-unique client name", i)
|
|
||||||
}
|
|
||||||
clientSettings[setting.ClientName] = setting
|
|
||||||
}
|
|
||||||
|
|
||||||
return Oauth{
|
|
||||||
oauthRepo: oauthRepo,
|
|
||||||
clientSettings: clientSettings,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Oauth) Authenticate(ctx context.Context, req domain.LoginOauthRequest, roleRepo roleRepo) (*entity.OauthUser, error) {
|
|
||||||
if len(s.clientSettings) == 0 {
|
|
||||||
return nil, domain.ErrOauthIsMissed
|
|
||||||
}
|
|
||||||
|
|
||||||
setting, ok := s.clientSettings[req.ClientName]
|
|
||||||
if !ok {
|
|
||||||
return nil, domain.ErrUnauthenticated
|
|
||||||
}
|
|
||||||
|
|
||||||
creds := entity.ClientSetting{
|
|
||||||
AuthCode: req.AuthCode,
|
|
||||||
ClientId: setting.ClientId,
|
|
||||||
ClientSecret: setting.ClientSecret,
|
|
||||||
RedirectURI: setting.RedirectURI,
|
|
||||||
}
|
|
||||||
tokenResponse, err := s.oauthRepo.GetToken(ctx, creds)
|
|
||||||
switch {
|
|
||||||
case err != nil:
|
|
||||||
return nil, errors.WithMessage(err, "get token")
|
|
||||||
case tokenResponse.OauthAuthError != nil:
|
|
||||||
return nil, errors.WithMessage(tokenResponse.OauthAuthError, "get token")
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := s.oauthRepo.GetUser(ctx, tokenResponse.AccessToken)
|
|
||||||
switch {
|
|
||||||
case err != nil:
|
|
||||||
return nil, errors.WithMessage(err, "get user")
|
|
||||||
case user.OauthAuthError != nil:
|
|
||||||
return nil, errors.WithMessage(user.OauthAuthError, "get user")
|
|
||||||
}
|
|
||||||
email := user.Email
|
|
||||||
if email == "" {
|
|
||||||
email = user.Sub
|
|
||||||
}
|
|
||||||
|
|
||||||
rolesIds := make([]int, 0)
|
|
||||||
if len(user.Groups) > 0 {
|
|
||||||
roles, err := roleRepo.GetRolesByExternalGroup(ctx, user.Groups)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get roles by external groups")
|
|
||||||
}
|
|
||||||
for _, role := range roles {
|
|
||||||
rolesIds = append(rolesIds, role.Id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &entity.OauthUser{
|
|
||||||
RoleIds: rolesIds,
|
|
||||||
OauthUserId: user.Sub,
|
|
||||||
FirstName: user.GivenName,
|
|
||||||
LastName: user.FamilyName,
|
|
||||||
FullName: user.Name,
|
|
||||||
Email: email,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -3,25 +3,25 @@ package service
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-admin-service/conf"
|
"msp-admin-service/conf"
|
||||||
"isp-admin-service/domain"
|
"msp-admin-service/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Permission struct {
|
type Permission struct {
|
||||||
permissions []domain.Permission
|
permissions []domain.Permission
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPermission(permissions []conf.Permission) Permission {
|
func NewPermission(permissions []conf.Permission) *Permission {
|
||||||
return Permission{
|
return &Permission{
|
||||||
permissions: toDomain(permissions),
|
permissions: toDomain(permissions),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
func (s Permission) All(_ context.Context) []domain.Permission {
|
func (s *Permission) All(_ context.Context) []domain.Permission {
|
||||||
return s.permissions
|
return s.permissions
|
||||||
}
|
}
|
||||||
|
|
||||||
func toDomain(permissions []conf.Permission) []domain.Permission {
|
func toDomain(permissions []conf.Permission) []domain.Permission {
|
||||||
permList := make([]domain.Permission, 0, len(permissions))
|
permList := make([]domain.Permission, 0)
|
||||||
for _, perm := range permissions {
|
for _, perm := range permissions {
|
||||||
permList = append(permList, domain.Permission{
|
permList = append(permList, domain.Permission{
|
||||||
Key: perm.Key,
|
Key: perm.Key,
|
||||||
|
|||||||
+36
-52
@@ -5,15 +5,13 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"slices"
|
"slices"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/entity"
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type roleRoleRepo interface {
|
type roleRoleRepo interface {
|
||||||
All(ctx context.Context) ([]entity.Role, error)
|
All(ctx context.Context) ([]entity.Role, error)
|
||||||
AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error)
|
|
||||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||||
Update(ctx context.Context, role entity.Role) (*entity.Role, error)
|
Update(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||||
Delete(ctx context.Context, id int) error
|
Delete(ctx context.Context, id int) error
|
||||||
@@ -33,17 +31,8 @@ func NewRole(roleRepo roleRoleRepo, audit auditService) Role {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||||
var (
|
roles, err := u.roleRepo.All(ctx)
|
||||||
roles []entity.Role
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
switch {
|
|
||||||
case req.ApplicationGroup != nil:
|
|
||||||
roles, err = u.roleRepo.AllWithFilter(ctx, *req.ApplicationGroup)
|
|
||||||
default:
|
|
||||||
roles, err = u.roleRepo.All(ctx)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get all roles")
|
return nil, errors.WithMessage(err, "get all roles")
|
||||||
}
|
}
|
||||||
@@ -68,10 +57,9 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
|
|||||||
}
|
}
|
||||||
|
|
||||||
role, err = u.roleRepo.InsertRole(ctx, entity.Role{
|
role, err = u.roleRepo.InsertRole(ctx, entity.Role{
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
ExternalGroup: req.ExternalGroup,
|
ExternalGroup: req.ExternalGroup,
|
||||||
ApplicationGroup: req.ApplicationGroup,
|
Permissions: req.Permissions,
|
||||||
Permissions: req.Permissions,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -80,22 +68,21 @@ 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{
|
||||||
"Название": "",
|
"Название": "",
|
||||||
"Группа ЕСК": "",
|
"Группа ЕСК": "",
|
||||||
"Группа приложений": "",
|
"Разрешения": []int{},
|
||||||
"Разрешения": []int{},
|
|
||||||
}, map[string]any{
|
}, map[string]any{
|
||||||
"Название": role.Name,
|
"Название": role.Name,
|
||||||
"Группа ЕСК": role.ExternalGroup,
|
"Группа ЕСК": role.ExternalGroup,
|
||||||
"Группа приложений": role.ApplicationGroup,
|
"Разрешения": 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),
|
||||||
entity.EventRoleChanged,
|
entity.EventRoleChanged,
|
||||||
)
|
)
|
||||||
|
|
||||||
return new(u.toDomain(*role)), nil
|
result := u.toDomain(*role)
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error) {
|
func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error) {
|
||||||
@@ -119,11 +106,10 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
|
|||||||
oldRole := roles[0]
|
oldRole := roles[0]
|
||||||
|
|
||||||
role, err := u.roleRepo.Update(ctx, entity.Role{
|
role, err := u.roleRepo.Update(ctx, entity.Role{
|
||||||
Id: req.Id,
|
Id: req.Id,
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
ExternalGroup: req.ExternalGroup,
|
ExternalGroup: req.ExternalGroup,
|
||||||
ApplicationGroup: req.ApplicationGroup,
|
Permissions: req.Permissions,
|
||||||
Permissions: req.Permissions,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -133,21 +119,20 @@ 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{
|
||||||
"Название": oldRole.Name,
|
"Название": oldRole.Name,
|
||||||
"Группа ЕСК": oldRole.ExternalGroup,
|
"Группа ЕСК": oldRole.ExternalGroup,
|
||||||
"Группа приложений": oldRole.ApplicationGroup,
|
"Разрешения": oldRole.Permissions,
|
||||||
"Разрешения": oldRole.Permissions,
|
|
||||||
}, map[string]any{
|
}, map[string]any{
|
||||||
"Название": role.Name,
|
"Название": role.Name,
|
||||||
"Группа ЕСК": role.ExternalGroup,
|
"Группа ЕСК": role.ExternalGroup,
|
||||||
"Группа приложений": role.ApplicationGroup,
|
"Разрешения": 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),
|
||||||
entity.EventRoleChanged,
|
entity.EventRoleChanged,
|
||||||
)
|
)
|
||||||
return new(u.toDomain(*role)), nil
|
result := u.toDomain(*role)
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error {
|
func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error {
|
||||||
@@ -164,14 +149,13 @@ func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId
|
|||||||
|
|
||||||
func (u Role) toDomain(role entity.Role) domain.Role {
|
func (u Role) toDomain(role entity.Role) domain.Role {
|
||||||
return domain.Role{
|
return domain.Role{
|
||||||
Id: role.Id,
|
Id: role.Id,
|
||||||
Name: role.Name,
|
Name: role.Name,
|
||||||
ExternalGroup: role.ExternalGroup,
|
ExternalGroup: role.ExternalGroup,
|
||||||
ApplicationGroup: role.ApplicationGroup,
|
Permissions: role.Permissions,
|
||||||
Permissions: role.Permissions,
|
Immutable: role.Immutable,
|
||||||
Immutable: role.Immutable,
|
Exclusive: role.Exclusive,
|
||||||
Exclusive: role.Exclusive,
|
CreatedAt: role.CreatedAt,
|
||||||
CreatedAt: role.CreatedAt,
|
UpdatedAt: role.UpdatedAt,
|
||||||
UpdatedAt: role.UpdatedAt,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,10 +5,9 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/entity"
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type TokenRep interface {
|
type TokenRep interface {
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
package session_worker
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/txix-open/bgjob"
|
|
||||||
"github.com/txix-open/isp-kit/bgjobx"
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
QueueName = "set_session_expired"
|
|
||||||
)
|
|
||||||
|
|
||||||
func EnqueueSeedJob(ctx context.Context, client *bgjobx.Client) error {
|
|
||||||
err := client.Enqueue(ctx, bgjob.EnqueueRequest{
|
|
||||||
Id: "set_session_expired",
|
|
||||||
Queue: QueueName,
|
|
||||||
Type: "set_session_expired",
|
|
||||||
})
|
|
||||||
if err != nil && !errors.Is(err, bgjob.ErrJobAlreadyExist) {
|
|
||||||
return errors.WithMessage(err, "enqueue job")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
package session_worker
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/bgjob"
|
|
||||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
defaultRetryTimeout = 5 * time.Minute
|
|
||||||
rescheduleInterval = 1 * time.Minute
|
|
||||||
)
|
|
||||||
|
|
||||||
type TokenTransactionRunner interface {
|
|
||||||
TokenTransaction(ctx context.Context, tx func(ctx context.Context, tx TokenTransaction) error) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type TokenTransaction interface {
|
|
||||||
All(ctx context.Context) ([]entity.Token, error)
|
|
||||||
SetExpiredStatusByIds(ctx context.Context, ids []int) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type Service struct {
|
|
||||||
logger log.Logger
|
|
||||||
txRunner TokenTransactionRunner
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewExpireSessionWorker(
|
|
||||||
logger log.Logger,
|
|
||||||
txRunner TokenTransactionRunner,
|
|
||||||
) Service {
|
|
||||||
return Service{
|
|
||||||
logger: logger,
|
|
||||||
txRunner: txRunner,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w Service) Handle(ctx context.Context, _ bgjob.Job) handler.Result {
|
|
||||||
ctx = log.ToContext(ctx, log.String("worker", "expireSessionWorker"))
|
|
||||||
w.logger.Debug(ctx, "begin work")
|
|
||||||
|
|
||||||
err := w.do(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return handler.Retry(defaultRetryTimeout, errors.WithMessage(err, "expireSessionWorker do"))
|
|
||||||
}
|
|
||||||
|
|
||||||
w.logger.Debug(ctx, "end work")
|
|
||||||
return handler.Reschedule(handler.ByAfterTime(rescheduleInterval, time.Now()))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w Service) do(ctx context.Context) error {
|
|
||||||
err := w.txRunner.TokenTransaction(ctx, func(ctx context.Context, tx TokenTransaction) error {
|
|
||||||
tokens, err := tx.All(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "get all tokens")
|
|
||||||
}
|
|
||||||
|
|
||||||
expiredTokenIds := make([]int, 0)
|
|
||||||
now := time.Now().UTC()
|
|
||||||
for _, token := range tokens {
|
|
||||||
if now.After(token.ExpiredAt) {
|
|
||||||
expiredTokenIds = append(expiredTokenIds, token.Id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(expiredTokenIds) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
err = tx.SetExpiredStatusByIds(ctx, expiredTokenIds)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "set expired status by id")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "token transaction")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
)
|
||||||
|
|
||||||
|
type sudirRepo interface {
|
||||||
|
GetToken(ctx context.Context, authCode string) (*entity.SudirTokenResponse, error)
|
||||||
|
GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type roleRepo interface {
|
||||||
|
GetRolesByExternalGroup(ctx context.Context, groups []string) ([]entity.Role, error)
|
||||||
|
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Sudir struct {
|
||||||
|
cfg *conf.SudirAuth
|
||||||
|
sudirRepo sudirRepo
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSudir(cfg *conf.SudirAuth, sudirRepo sudirRepo) Sudir {
|
||||||
|
return Sudir{
|
||||||
|
cfg: cfg,
|
||||||
|
sudirRepo: sudirRepo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Sudir) Authenticate(ctx context.Context, authCode string, roleRepo roleRepo) (*entity.SudirUser, error) {
|
||||||
|
if s.cfg == nil {
|
||||||
|
return nil, domain.ErrSudirAuthIsMissed
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenResponse, err := s.sudirRepo.GetToken(ctx, authCode)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessage(err, "get token")
|
||||||
|
case tokenResponse.SudirAuthError != nil:
|
||||||
|
return nil, errors.WithMessage(tokenResponse.SudirAuthError, "get token")
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := s.sudirRepo.GetUser(ctx, tokenResponse.AccessToken)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessage(err, "get user")
|
||||||
|
case user.SudirAuthError != nil:
|
||||||
|
return nil, errors.WithMessage(user.SudirAuthError, "get user")
|
||||||
|
}
|
||||||
|
email := user.Email
|
||||||
|
if email == "" {
|
||||||
|
email = user.Sub
|
||||||
|
}
|
||||||
|
|
||||||
|
rolesIds := make([]int, 0)
|
||||||
|
if len(user.Groups) > 0 {
|
||||||
|
roles, err := roleRepo.GetRolesByExternalGroup(ctx, user.Groups)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "get roles by external groups")
|
||||||
|
}
|
||||||
|
for _, role := range roles {
|
||||||
|
rolesIds = append(rolesIds, role.Id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &entity.SudirUser{
|
||||||
|
RoleIds: rolesIds,
|
||||||
|
SudirUserId: user.Sub,
|
||||||
|
FirstName: user.GivenName,
|
||||||
|
LastName: user.FamilyName,
|
||||||
|
Email: email,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
+16
-16
@@ -6,19 +6,18 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"golang.org/x/sync/errgroup"
|
"golang.org/x/sync/errgroup"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
type TokenRep interface {
|
type TokenRep interface {
|
||||||
TokenSaver
|
TokenSaver
|
||||||
Get(ctx context.Context, token string) (*entity.Token, error)
|
Get(ctx context.Context, token string) (*entity.Token, error)
|
||||||
RevokeByUserId(ctx context.Context, userId int64, updatedAt time.Time) error
|
RevokeByUserId(ctx context.Context, userId int64, updatedAt time.Time) error
|
||||||
AllByRequest(ctx context.Context, req domain.SessionPageRequest) ([]entity.Token, error)
|
All(ctx context.Context, limit int, offset int) ([]entity.Token, error)
|
||||||
Count(ctx context.Context, reqQuery *domain.SessionQuery) (int64, error)
|
Count(ctx context.Context) (int64, error)
|
||||||
UpdateStatus(ctx context.Context, id int, status string) error
|
UpdateStatus(ctx context.Context, id int, status string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,43 +73,44 @@ func (s Token) RevokeAllByUserId(ctx context.Context, userId int64) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Token) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) {
|
func (s Token) All(ctx context.Context, limit int, offset int) (*domain.SessionResponse, error) {
|
||||||
|
group, ctx := errgroup.WithContext(ctx)
|
||||||
var tokens []entity.Token
|
var tokens []entity.Token
|
||||||
var total int64
|
var total int64
|
||||||
|
var err error
|
||||||
group, ctx := errgroup.WithContext(ctx)
|
|
||||||
group.Go(func() error {
|
group.Go(func() error {
|
||||||
var err error
|
tokens, err = s.tokenRep.All(ctx, limit, offset)
|
||||||
tokens, err = s.tokenRep.AllByRequest(ctx, req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "get all tokens")
|
return errors.WithMessage(err, "get all tokens")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
group.Go(func() error {
|
group.Go(func() error {
|
||||||
var err error
|
total, err = s.tokenRep.Count(ctx)
|
||||||
total, err = s.tokenRep.Count(ctx, req.Query)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "count all tokens")
|
return errors.WithMessage(err, "count all tokens")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
err := group.Wait()
|
err = group.Wait()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "wait workers")
|
return nil, errors.WithMessage(err, "wait workers")
|
||||||
}
|
}
|
||||||
|
|
||||||
items := make([]domain.Session, 0)
|
items := make([]domain.Session, 0)
|
||||||
for _, token := range tokens {
|
for _, token := range tokens {
|
||||||
|
status := token.Status
|
||||||
|
if time.Now().UTC().After(token.ExpiredAt) {
|
||||||
|
status = entity.TokenStatusExpired
|
||||||
|
}
|
||||||
items = append(items, domain.Session{
|
items = append(items, domain.Session{
|
||||||
Id: token.Id,
|
Id: token.Id,
|
||||||
UserId: int(token.UserId),
|
UserId: int(token.UserId),
|
||||||
Status: token.Status,
|
Status: status,
|
||||||
ExpiredAt: token.ExpiredAt,
|
ExpiredAt: token.ExpiredAt,
|
||||||
CreatedAt: token.CreatedAt,
|
CreatedAt: token.CreatedAt,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
result := domain.SessionResponse{
|
result := domain.SessionResponse{
|
||||||
TotalCount: int(total),
|
TotalCount: int(total),
|
||||||
Items: items,
|
Items: items,
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"net/url"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UiSettings struct {
|
|
||||||
oauthBaseUrl string
|
|
||||||
settings map[string]conf.OauthClientConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUiSettings(oauthBaseUrl string, settings []conf.OauthClientConfig) UiSettings {
|
|
||||||
settingsMap := make(map[string]conf.OauthClientConfig, len(settings))
|
|
||||||
for _, setting := range settings {
|
|
||||||
if setting.UiSetting == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
settingsMap[setting.ClientName] = setting
|
|
||||||
}
|
|
||||||
return UiSettings{
|
|
||||||
oauthBaseUrl: oauthBaseUrl,
|
|
||||||
settings: settingsMap,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
|
||||||
setting, ok := s.settings[req.ClientName]
|
|
||||||
if !ok {
|
|
||||||
return nil, domain.ErrUnknownClient
|
|
||||||
}
|
|
||||||
|
|
||||||
loginUrl, err := s.buildUrl(
|
|
||||||
setting.UiSetting.LoginEndpoint,
|
|
||||||
map[string]string{
|
|
||||||
"client_id": setting.ClientId,
|
|
||||||
"redirect_uri": setting.RedirectURI,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Errorf("build url for login: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
logoutUrl, err := s.buildUrl(setting.UiSetting.LogoutEndpoint, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Errorf("build url for logout: %w", err)
|
|
||||||
}
|
|
||||||
return &domain.UiOauthSetting{
|
|
||||||
LoginUrl: loginUrl,
|
|
||||||
LogoutUrl: logoutUrl,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s UiSettings) buildUrl(methodPath string, additionalQuery map[string]string) (string, error) {
|
|
||||||
method, err := url.Parse(methodPath)
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.Errorf("parse method path")
|
|
||||||
}
|
|
||||||
|
|
||||||
joined, err := url.JoinPath(s.oauthBaseUrl, method.Path)
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.Errorf("join method path and baseUrl")
|
|
||||||
}
|
|
||||||
|
|
||||||
u, err := url.Parse(joined)
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.Errorf("parse joined")
|
|
||||||
}
|
|
||||||
|
|
||||||
q := method.Query()
|
|
||||||
for k, v := range additionalQuery {
|
|
||||||
q.Set(k, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
u.RawQuery = q.Encode()
|
|
||||||
return u.String(), nil
|
|
||||||
}
|
|
||||||
+83
-189
@@ -8,12 +8,11 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
type UserTransaction interface {
|
type UserTransaction interface {
|
||||||
@@ -26,19 +25,15 @@ type UserTransactionRunner interface {
|
|||||||
UserTransaction(ctx context.Context, tx func(ctx context.Context, tx UserTransaction) error) error
|
UserTransaction(ctx context.Context, tx func(ctx context.Context, tx UserTransaction) error) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint:interfacebloat
|
|
||||||
type UserRepo interface {
|
type UserRepo interface {
|
||||||
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
||||||
GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]entity.User, error)
|
GetUsers(ctx context.Context, ids []int64, offset, limit int, email string) ([]entity.User, error)
|
||||||
GetAllUsers(ctx context.Context) ([]entity.User, error)
|
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||||
GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error)
|
|
||||||
GetUsersByEmail(ctx context.Context, email string) ([]entity.User, error)
|
|
||||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||||
DeleteUser(ctx context.Context, ids []int64) (int, error)
|
DeleteUser(ctx context.Context, ids []int64) (int, error)
|
||||||
Insert(ctx context.Context, user entity.User) (int, error)
|
Insert(ctx context.Context, user entity.User) (int, error)
|
||||||
ChangeBlockStatus(ctx context.Context, userId int) (bool, error)
|
ChangeBlockStatus(ctx context.Context, userId int) (bool, error)
|
||||||
ChangePassword(ctx context.Context, userId int64, newPassword string) error
|
ChangePassword(ctx context.Context, userId int64, newPassword string) error
|
||||||
UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type TokenRepo interface {
|
type TokenRepo interface {
|
||||||
@@ -55,6 +50,10 @@ type roleRepoUser interface {
|
|||||||
GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error)
|
GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type LdapService interface {
|
||||||
|
SyncGroupsAsync(ctx context.Context, user entity.User)
|
||||||
|
}
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
userRepo UserRepo
|
userRepo UserRepo
|
||||||
userRoleRepo UserRoleRepo
|
userRoleRepo UserRoleRepo
|
||||||
@@ -62,6 +61,7 @@ type User struct {
|
|||||||
tokenRepo TokenRepo
|
tokenRepo TokenRepo
|
||||||
auditService auditService
|
auditService auditService
|
||||||
txRunner UserTransactionRunner
|
txRunner UserTransactionRunner
|
||||||
|
ldapService LdapService
|
||||||
tokenService tokenService
|
tokenService tokenService
|
||||||
idleTimeoutMs int
|
idleTimeoutMs int
|
||||||
logger log.Logger
|
logger log.Logger
|
||||||
@@ -74,6 +74,7 @@ func NewUser(
|
|||||||
tokenRepo TokenRepo,
|
tokenRepo TokenRepo,
|
||||||
service auditService,
|
service auditService,
|
||||||
txRunner UserTransactionRunner,
|
txRunner UserTransactionRunner,
|
||||||
|
ldapService LdapService,
|
||||||
tokenService tokenService,
|
tokenService tokenService,
|
||||||
idleTimeoutMs int,
|
idleTimeoutMs int,
|
||||||
logger log.Logger,
|
logger log.Logger,
|
||||||
@@ -85,6 +86,7 @@ func NewUser(
|
|||||||
tokenRepo: tokenRepo,
|
tokenRepo: tokenRepo,
|
||||||
auditService: service,
|
auditService: service,
|
||||||
txRunner: txRunner,
|
txRunner: txRunner,
|
||||||
|
ldapService: ldapService,
|
||||||
tokenService: tokenService,
|
tokenService: tokenService,
|
||||||
idleTimeoutMs: idleTimeoutMs,
|
idleTimeoutMs: idleTimeoutMs,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
@@ -107,9 +109,8 @@ func (u User) GetProfileById(ctx context.Context, userId int64) (*domain.AdminUs
|
|||||||
roleIds := RolesIds(roles)
|
roleIds := RolesIds(roles)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
roleList []entity.Role
|
roleList []entity.Role
|
||||||
roleName string
|
roleName string
|
||||||
roleNames []string
|
|
||||||
)
|
)
|
||||||
if len(roleIds) != 0 {
|
if len(roleIds) != 0 {
|
||||||
roleList, err = u.roleRepoUser.GetRoleByIds(ctx, roleIds)
|
roleList, err = u.roleRepoUser.GetRoleByIds(ctx, roleIds)
|
||||||
@@ -118,27 +119,22 @@ func (u User) GetProfileById(ctx context.Context, userId int64) (*domain.AdminUs
|
|||||||
}
|
}
|
||||||
if len(roleList) > 0 {
|
if len(roleList) > 0 {
|
||||||
roleName = roleList[0].Name
|
roleName = roleList[0].Name
|
||||||
for _, r := range roleList {
|
|
||||||
roleNames = append(roleNames, r.Name)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &domain.AdminUserShort{
|
return &domain.AdminUserShort{
|
||||||
FirstName: user.FirstName,
|
FirstName: user.FirstName,
|
||||||
LastName: user.LastName,
|
LastName: user.LastName,
|
||||||
FullName: user.FullName,
|
|
||||||
Email: user.Email,
|
Email: user.Email,
|
||||||
Role: roleName,
|
Role: roleName,
|
||||||
Roles: roleIds,
|
Roles: roleIds,
|
||||||
RoleNames: roleNames,
|
|
||||||
IdleTimeoutMs: u.idleTimeoutMs,
|
IdleTimeoutMs: u.idleTimeoutMs,
|
||||||
Permissions: mergePermissions(roleList),
|
Permissions: mergePermissions(roleList),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) {
|
func (u User) GetUsers(ctx context.Context, req domain.UsersRequest) (*domain.UsersResponse, error) {
|
||||||
users, err := u.userRepo.GetUsers(ctx, req)
|
users, err := u.userRepo.GetUsers(ctx, req.Ids, req.Offset, req.Limit, req.Email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get users from repo")
|
return nil, errors.WithMessage(err, "get users from repo")
|
||||||
}
|
}
|
||||||
@@ -148,56 +144,27 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
|
|||||||
userIds = append(userIds, int(user.Id))
|
userIds = append(userIds, int(user.Id))
|
||||||
}
|
}
|
||||||
|
|
||||||
userRoles, err := u.userRoleRepo.GetRolesByUserIds(ctx, userIds)
|
rolesByUsers, err := u.userRoleRepo.GetRolesByUserIds(ctx, userIds)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get roles by user ids and roles id")
|
return nil, errors.WithMessage(err, "get roles by user ids")
|
||||||
|
}
|
||||||
|
|
||||||
|
lastSessionsByUsers, err := u.tokenRepo.LastAccessByUserIds(ctx, userIds)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "get last sessions by user ids")
|
||||||
}
|
}
|
||||||
|
|
||||||
items := make([]domain.User, 0, len(users))
|
items := make([]domain.User, 0, len(users))
|
||||||
for _, user := range users {
|
for _, user := range users {
|
||||||
roles := make([]int, 0)
|
roles := make([]int, 0)
|
||||||
|
|
||||||
for _, role := range userRoles {
|
for _, role := range rolesByUsers {
|
||||||
if role.UserId == int(user.Id) {
|
if role.UserId == int(user.Id) {
|
||||||
roles = append(roles, role.RoleId)
|
roles = append(roles, role.RoleId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if filteredRoles(req.Query, roles) && filteredLastSession(req.Query, user.LastSessionCreatedAt) {
|
items = append(items, u.toDomain(user, roles, lastSessionsByUsers[user.Id]))
|
||||||
items = append(items, u.toDomain(user, roles, user.LastSessionCreatedAt))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &domain.UsersResponse{Items: items}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
|
||||||
users, err := u.userRepo.GetAllUsers(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get all users from repo")
|
|
||||||
}
|
|
||||||
|
|
||||||
userIds := make([]int, 0)
|
|
||||||
for _, user := range users {
|
|
||||||
userIds = append(userIds, int(user.Id))
|
|
||||||
}
|
|
||||||
|
|
||||||
userRoles, err := u.userRoleRepo.GetRolesByUserIds(ctx, userIds)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get roles by user ids and roles id")
|
|
||||||
}
|
|
||||||
|
|
||||||
items := make([]domain.User, 0, len(users))
|
|
||||||
for _, user := range users {
|
|
||||||
roles := make([]int, 0)
|
|
||||||
|
|
||||||
for _, role := range userRoles {
|
|
||||||
if role.UserId == int(user.Id) {
|
|
||||||
roles = append(roles, role.RoleId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
items = append(items, u.toDomain(user, roles, user.LastSessionCreatedAt))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &domain.UsersResponse{Items: items}, nil
|
return &domain.UsersResponse{Items: items}, nil
|
||||||
@@ -207,7 +174,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
|||||||
var usr entity.User
|
var usr entity.User
|
||||||
|
|
||||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||||
user, err := tx.GetUserByEmailAndOauthId(ctx, req.Email, "")
|
user, err := tx.GetUserByEmail(ctx, req.Email)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
break
|
break
|
||||||
@@ -223,11 +190,10 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
|||||||
}
|
}
|
||||||
|
|
||||||
usr = entity.User{
|
usr = entity.User{
|
||||||
OauthUserId: nil,
|
SudirUserId: nil,
|
||||||
Id: 0,
|
Id: 0,
|
||||||
FirstName: req.FirstName,
|
FirstName: req.FirstName,
|
||||||
LastName: req.LastName,
|
LastName: req.LastName,
|
||||||
FullName: createFullName(req.FirstName, req.LastName),
|
|
||||||
Email: req.Email,
|
Email: req.Email,
|
||||||
Password: encryptedPassword,
|
Password: encryptedPassword,
|
||||||
Description: req.Description,
|
Description: req.Description,
|
||||||
@@ -251,14 +217,18 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
|||||||
return nil, errors.WithMessage(err, "create user transaction")
|
return nil, errors.WithMessage(err, "create user transaction")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
u.ldapService.SyncGroupsAsync(ctx, usr)
|
||||||
|
|
||||||
slices.Sort(req.Roles)
|
slices.Sort(req.Roles)
|
||||||
diff := diffToString(map[string]any{
|
diff := diffToString(map[string]any{
|
||||||
"ФИО": "",
|
"Имя": "",
|
||||||
|
"Фамилия": "",
|
||||||
"Описание": "",
|
"Описание": "",
|
||||||
"Email": "",
|
"Email": "",
|
||||||
"Роли (ID)": []int{},
|
"Роли (ID)": []int{},
|
||||||
}, map[string]any{
|
}, map[string]any{
|
||||||
"ФИО": usr.FullName,
|
"Имя": req.FirstName,
|
||||||
|
"Фамилия": req.LastName,
|
||||||
"Описание": req.Description,
|
"Описание": req.Description,
|
||||||
"Email": req.Email,
|
"Email": req.Email,
|
||||||
"Роли (ID)": req.Roles,
|
"Роли (ID)": req.Roles,
|
||||||
@@ -268,14 +238,13 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
|||||||
entity.EventUserChanged,
|
entity.EventUserChanged,
|
||||||
)
|
)
|
||||||
|
|
||||||
return new(u.toDomain(usr, req.Roles, nil)), nil
|
result := u.toDomain(usr, req.Roles, nil)
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//nolint:cyclop,funlen
|
|
||||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, adminId int64) (*domain.User, error) {
|
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, adminId int64) (*domain.User, error) {
|
||||||
var (
|
var (
|
||||||
user *entity.User
|
user *entity.User
|
||||||
updatedUser *entity.User
|
|
||||||
lastSessionCreatedAt *time.Time
|
lastSessionCreatedAt *time.Time
|
||||||
)
|
)
|
||||||
oldRoles, err := u.userRoleRepo.GetRolesByUserIds(ctx, []int{int(req.Id)})
|
oldRoles, err := u.userRoleRepo.GetRolesByUserIds(ctx, []int{int(req.Id)})
|
||||||
@@ -283,7 +252,7 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
|
|||||||
return nil, errors.WithMessage(err, "get user roles")
|
return nil, errors.WithMessage(err, "get user roles")
|
||||||
}
|
}
|
||||||
err = u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
err = u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||||
user, err = tx.GetUserById(ctx, req.Id)
|
_, err := tx.GetUserById(ctx, req.Id)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
return err // nolint:wrapcheck
|
return err // nolint:wrapcheck
|
||||||
@@ -291,48 +260,37 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
|
|||||||
return errors.WithMessage(err, "get user by id")
|
return errors.WithMessage(err, "get user by id")
|
||||||
}
|
}
|
||||||
|
|
||||||
users, err := tx.GetUsersByEmail(ctx, req.Email)
|
user, err = tx.GetUserByEmail(ctx, req.Email)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
break
|
break
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return errors.WithMessage(err, "get user by email or phone")
|
return errors.WithMessage(err, "get user by email or phone")
|
||||||
}
|
case user.Id != req.Id:
|
||||||
|
return domain.ErrAlreadyExists
|
||||||
for _, usr := range users {
|
|
||||||
// check in internal user space
|
|
||||||
if (user.OauthUserId == nil && usr.OauthUserId == nil) && (usr.Id != req.Id) {
|
|
||||||
return domain.ErrAlreadyExists
|
|
||||||
}
|
|
||||||
|
|
||||||
// check in oauth user space
|
|
||||||
if usr.OauthUserId != nil && user.OauthUserId != nil && (*user.OauthUserId != *usr.OauthUserId) {
|
|
||||||
return domain.ErrAlreadyExists
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
updateEntity := entity.UpdateUser{
|
updateEntity := entity.UpdateUser{
|
||||||
FirstName: req.FirstName,
|
FirstName: req.FirstName,
|
||||||
LastName: req.LastName,
|
LastName: req.LastName,
|
||||||
FullName: createFullName(req.FirstName, req.LastName),
|
|
||||||
Email: req.Email,
|
Email: req.Email,
|
||||||
Description: req.Description,
|
Description: req.Description,
|
||||||
}
|
}
|
||||||
updatedUser, err = tx.UpdateUser(ctx, req.Id, updateEntity)
|
user, err = tx.UpdateUser(ctx, req.Id, updateEntity)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "update user")
|
return errors.WithMessage(err, "update user")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = tx.UpsertUserRoleLinks(ctx, int(updatedUser.Id), req.Roles)
|
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), req.Roles)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "update user role links")
|
return errors.WithMessage(err, "update user role links")
|
||||||
}
|
}
|
||||||
|
|
||||||
userLastSession, err := tx.LastAccessByUserIds(ctx, []int{int(updatedUser.Id)})
|
userLastSession, err := tx.LastAccessByUserIds(ctx, []int{int(user.Id)})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "get last user session")
|
return errors.WithMessage(err, "get last user session")
|
||||||
}
|
}
|
||||||
lastSessionCreatedAt = userLastSession[updatedUser.Id]
|
lastSessionCreatedAt = userLastSession[user.Id]
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -340,24 +298,29 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
|
|||||||
return nil, errors.WithMessage(err, "update user transaction")
|
return nil, errors.WithMessage(err, "update user transaction")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
u.ldapService.SyncGroupsAsync(ctx, *user)
|
||||||
|
|
||||||
slices.Sort(req.Roles)
|
slices.Sort(req.Roles)
|
||||||
diff := diffToString(map[string]any{
|
diff := diffToString(map[string]any{
|
||||||
"ФИО": user.FullName,
|
"Имя": user.FirstName,
|
||||||
|
"Фамилия": user.LastName,
|
||||||
"Описание": user.Description,
|
"Описание": user.Description,
|
||||||
"Email": user.Email,
|
"Email": user.Email,
|
||||||
"Роли (ID)": RolesIds(oldRoles),
|
"Роли (ID)": RolesIds(oldRoles),
|
||||||
}, map[string]any{
|
}, map[string]any{
|
||||||
"ФИО": updatedUser.FullName,
|
"Имя": req.FirstName,
|
||||||
|
"Фамилия": req.LastName,
|
||||||
"Описание": req.Description,
|
"Описание": req.Description,
|
||||||
"Email": req.Email,
|
"Email": req.Email,
|
||||||
"Роли (ID)": 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", user.Id, diff),
|
||||||
entity.EventUserChanged,
|
entity.EventUserChanged,
|
||||||
)
|
)
|
||||||
|
|
||||||
return new(u.toDomain(*updatedUser, req.Roles, lastSessionCreatedAt)), nil
|
result := u.toDomain(*user, req.Roles, lastSessionCreatedAt)
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) DeleteUsers(ctx context.Context, ids []int64, adminId int64) (int, error) {
|
func (u User) DeleteUsers(ctx context.Context, ids []int64, adminId int64) (int, error) {
|
||||||
@@ -394,7 +357,8 @@ func (u User) GetById(ctx context.Context, userId int) (*domain.User, error) {
|
|||||||
return nil, errors.WithMessage(err, "get last sessions by user id")
|
return nil, errors.WithMessage(err, "get last sessions by user id")
|
||||||
}
|
}
|
||||||
|
|
||||||
return new(u.toDomain(*user, RolesIds(roles), lastSessions[int64(userId)])), nil
|
result := u.toDomain(*user, RolesIds(roles), lastSessions[int64(userId)])
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) Block(ctx context.Context, adminId int64, userId int) error {
|
func (u User) Block(ctx context.Context, adminId int64, userId int) error {
|
||||||
@@ -407,7 +371,7 @@ func (u User) Block(ctx context.Context, adminId int64, userId int) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if blocked {
|
if blocked {
|
||||||
err = tx.UpdateStatusByUserId(ctx, userId, entity.TokenStatusRevoked)
|
err := tx.UpdateStatusByUserId(ctx, userId, entity.TokenStatusRevoked)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "revoke tokens")
|
return errors.WithMessage(err, "revoke tokens")
|
||||||
}
|
}
|
||||||
@@ -415,11 +379,6 @@ func (u User) Block(ctx context.Context, adminId int64, userId int) error {
|
|||||||
|
|
||||||
if !blocked {
|
if !blocked {
|
||||||
userBlocked = "разблокировка"
|
userBlocked = "разблокировка"
|
||||||
lastActiveAt := time.Now().UTC()
|
|
||||||
err = tx.UpdateLastActiveAt(ctx, int64(userId), lastActiveAt)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "update user last_active_at")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -430,14 +389,14 @@ func (u User) Block(ctx context.Context, adminId int64, userId int) error {
|
|||||||
|
|
||||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||||
fmt.Sprintf("Пользователь. %s пользователя ID %d.", userBlocked, userId),
|
fmt.Sprintf("Пользователь. %s пользователя ID %d.", userBlocked, userId),
|
||||||
entity.EventUserBlocked,
|
entity.EventUserChanged,
|
||||||
)
|
)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func RolesIds(roles []entity.UserRole) []int {
|
func RolesIds(roles []entity.UserRole) []int {
|
||||||
roleList := make([]int, 0, len(roles))
|
roleList := make([]int, 0)
|
||||||
|
|
||||||
for _, role := range roles {
|
for _, role := range roles {
|
||||||
roleList = append(roleList, role.RoleId)
|
roleList = append(roleList, role.RoleId)
|
||||||
@@ -485,50 +444,37 @@ func diffToString(a map[string]any, b map[string]any) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u User) ChangePassword(ctx context.Context, adminId int64, oldPassword string, newPassword string) error {
|
func (u User) ChangePassword(ctx context.Context, adminId int64, oldPassword string, newPassword string) error {
|
||||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
admin, err := u.userRepo.GetUserById(ctx, adminId)
|
||||||
admin, err := tx.GetUserById(ctx, adminId)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "user.service.ChangePassword: get user by id")
|
|
||||||
}
|
|
||||||
|
|
||||||
err = bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(oldPassword))
|
|
||||||
if err != nil {
|
|
||||||
u.auditService.SaveAuditAsync(ctx, adminId, "Указан неверный старый пароль", entity.EventErrorPasswordChange)
|
|
||||||
return domain.ErrInvalidPassword
|
|
||||||
}
|
|
||||||
|
|
||||||
encryptedPassword, err := u.cryptPassword(newPassword)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "user.service.ChangePassword: crypt new password")
|
|
||||||
}
|
|
||||||
|
|
||||||
err = tx.ChangePassword(ctx, adminId, encryptedPassword)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "user.service.ChangePassword: change password ")
|
|
||||||
}
|
|
||||||
|
|
||||||
err = u.tokenService.RevokeAllByUserId(ctx, adminId)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "revoke all tokens by user id")
|
|
||||||
}
|
|
||||||
|
|
||||||
lastActiveAt := time.Now().UTC()
|
|
||||||
err = tx.UpdateLastActiveAt(ctx, adminId, lastActiveAt)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "update user last_active_at")
|
|
||||||
}
|
|
||||||
|
|
||||||
u.auditService.SaveAuditAsync(ctx, adminId, "Сменил пароль", entity.EventUserPasswordChanged)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "user transaction")
|
return errors.WithMessage(err, "user.service.ChangePassword: get user by id")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(oldPassword)); err != nil {
|
||||||
|
u.auditService.SaveAuditAsync(ctx, adminId, "Указан неверный старый пароль", entity.EventErrorPasswordChange)
|
||||||
|
return domain.ErrInvalidPassword
|
||||||
|
}
|
||||||
|
|
||||||
|
encryptedPassword, err := u.cryptPassword(newPassword)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "user.service.ChangePassword: crypt new password")
|
||||||
|
}
|
||||||
|
|
||||||
|
err = u.userRepo.ChangePassword(ctx, adminId, encryptedPassword)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "user.service.ChangePassword: change password ")
|
||||||
|
}
|
||||||
|
|
||||||
|
err = u.tokenService.RevokeAllByUserId(ctx, adminId)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "revoke all tokens by user id")
|
||||||
|
}
|
||||||
|
|
||||||
|
u.auditService.SaveAuditAsync(ctx, adminId, "Сменил пароль", entity.EventUserPasswordChanged)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//nolint:gomnd
|
||||||
func (u User) cryptPassword(password string) (string, error) {
|
func (u User) cryptPassword(password string) (string, error) {
|
||||||
passwordBytes, err := bcrypt.GenerateFromPassword([]byte(password), 12) //nolint:mnd
|
passwordBytes, err := bcrypt.GenerateFromPassword([]byte(password), 12) //nolint:mnd
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -543,9 +489,8 @@ func (u User) toDomain(user entity.User, roleIds []int, lastSessionCreatedAt *ti
|
|||||||
Id: user.Id,
|
Id: user.Id,
|
||||||
Roles: roleIds,
|
Roles: roleIds,
|
||||||
FirstName: user.FirstName,
|
FirstName: user.FirstName,
|
||||||
LastName: user.LastName,
|
|
||||||
FullName: user.FullName,
|
|
||||||
Description: user.Description,
|
Description: user.Description,
|
||||||
|
LastName: user.LastName,
|
||||||
Email: user.Email,
|
Email: user.Email,
|
||||||
Blocked: user.Blocked,
|
Blocked: user.Blocked,
|
||||||
UpdatedAt: user.UpdatedAt,
|
UpdatedAt: user.UpdatedAt,
|
||||||
@@ -553,54 +498,3 @@ func (u User) toDomain(user entity.User, roleIds []int, lastSessionCreatedAt *ti
|
|||||||
LastSessionCreatedAt: lastSessionCreatedAt,
|
LastSessionCreatedAt: lastSessionCreatedAt,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func filteredRoles(reqQuery *domain.UserQuery, roleIds []int) bool {
|
|
||||||
if reqQuery == nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.Roles == nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(reqQuery.Roles) == 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, roleId := range roleIds {
|
|
||||||
if slices.Contains(reqQuery.Roles, roleId) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func filteredLastSession(reqQuery *domain.UserQuery, lastSessionCreatedAt *time.Time) bool {
|
|
||||||
if reqQuery == nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.LastSessionCreatedAt == nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if lastSessionCreatedAt == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqQuery.LastSessionCreatedAt.From.Compare(*lastSessionCreatedAt) <= 0 &&
|
|
||||||
reqQuery.LastSessionCreatedAt.To.Compare(*lastSessionCreatedAt) > 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func createFullName(firstName string, lastName string) string {
|
|
||||||
if len(lastName) == 0 {
|
|
||||||
return firstName
|
|
||||||
}
|
|
||||||
|
|
||||||
return strings.Join([]string{lastName, firstName}, " ")
|
|
||||||
}
|
|
||||||
+58
-127
@@ -1,22 +1,24 @@
|
|||||||
package tests_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
"isp-admin-service/repository"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
"github.com/stretchr/testify/suite"
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
"github.com/txix-open/isp-kit/http/httpcli"
|
||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
"msp-admin-service/assembly"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
"msp-admin-service/repository"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAuditSuite(t *testing.T) {
|
func TestAuditSuite(t *testing.T) {
|
||||||
@@ -26,16 +28,15 @@ func TestAuditSuite(t *testing.T) {
|
|||||||
|
|
||||||
type AuditSuite struct {
|
type AuditSuite struct {
|
||||||
suite.Suite
|
suite.Suite
|
||||||
|
|
||||||
test *test.Test
|
test *test.Test
|
||||||
db *dbt.TestDb
|
db *dbt.TestDb
|
||||||
httpCli *httpcli.Client
|
grpcCli *client.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuditSuite) SetupTest() {
|
func (t *AuditSuite) SetupTest() {
|
||||||
testInstance, _ := test.New(s.T())
|
testInstance, _ := test.New(t.T())
|
||||||
s.test = testInstance
|
t.test = testInstance
|
||||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
t.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||||
|
|
||||||
remote := conf.Remote{
|
remote := conf.Remote{
|
||||||
Audit: conf.Audit{
|
Audit: conf.Audit{
|
||||||
@@ -60,34 +61,28 @@ func (s *AuditSuite) SetupTest() {
|
|||||||
Event: entity.EventUserChanged,
|
Event: entity.EventUserChanged,
|
||||||
Name: "изменение пользователя",
|
Name: "изменение пользователя",
|
||||||
},
|
},
|
||||||
{
|
|
||||||
Event: entity.EventUserBlocked,
|
|
||||||
Name: "изменение статуса блокировки пользователя",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
AuditTTl: conf.AuditTTlSetting{},
|
AuditTTl: conf.AuditTTlSetting{},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
|
cfg := assembly.NewLocator(testInstance.Logger(), httpcli.New(), t.db).
|
||||||
Config(s.T().Context(), remote, time.Minute)
|
Config(context.Background(), emptyLdap, remote, time.Minute)
|
||||||
s.Require().NoError(err)
|
|
||||||
s.insertAuditLogs()
|
|
||||||
|
|
||||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||||
s.httpCli = cli
|
t.grpcCli = apiCli
|
||||||
|
|
||||||
testInstance.T().Cleanup(func() {
|
testInstance.T().Cleanup(func() {
|
||||||
server.Close()
|
server.Shutdown()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuditSuite) Test_Events_DefaultEvents() {
|
func (t *AuditSuite) Test_Events_DefaultEvents() {
|
||||||
response := make([]domain.AuditEvent, 0)
|
response := make([]domain.AuditEvent, 0)
|
||||||
err := s.httpCli.
|
err := t.grpcCli.
|
||||||
Post("admin/log/events").
|
Invoke("admin/log/events").
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
t.Require().NoError(err)
|
||||||
|
|
||||||
expectedEventList := map[string]string{
|
expectedEventList := map[string]string{
|
||||||
entity.EventSuccessLogin: "успешный вход",
|
entity.EventSuccessLogin: "успешный вход",
|
||||||
@@ -95,56 +90,54 @@ func (s *AuditSuite) Test_Events_DefaultEvents() {
|
|||||||
entity.EventSuccessLogout: "успешный выход",
|
entity.EventSuccessLogout: "успешный выход",
|
||||||
entity.EventRoleChanged: "изменение роли",
|
entity.EventRoleChanged: "изменение роли",
|
||||||
entity.EventUserChanged: "изменение пользователя",
|
entity.EventUserChanged: "изменение пользователя",
|
||||||
entity.EventUserBlocked: "изменение статуса блокировки пользователя",
|
|
||||||
}
|
}
|
||||||
for _, event := range response {
|
for _, event := range response {
|
||||||
name, found := expectedEventList[event.Event]
|
name, found := expectedEventList[event.Event]
|
||||||
s.Require().Equal(found, event.Enabled)
|
t.Require().Equal(found, event.Enabled)
|
||||||
s.Require().Equal(name, event.Name)
|
t.Require().Equal(name, event.Name)
|
||||||
delete(expectedEventList, event.Event)
|
delete(expectedEventList, event.Event)
|
||||||
}
|
}
|
||||||
s.Require().Empty(expectedEventList)
|
t.Require().Empty(expectedEventList)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuditSuite) Test_Events_SortEvents() {
|
func (t *AuditSuite) Test_Events_SortEvents() {
|
||||||
eventRep := repository.NewAuditEvent(s.db)
|
eventRep := repository.NewAuditEvent(t.db)
|
||||||
err := eventRep.Upsert(s.T().Context(), []entity.AuditEvent{
|
err := eventRep.Upsert(context.Background(), []entity.AuditEvent{
|
||||||
{Event: "новый#1", Enable: false},
|
{Event: "новый#1", Enable: false},
|
||||||
{Event: entity.EventSuccessLogin, Enable: false},
|
{Event: entity.EventSuccessLogin, Enable: false},
|
||||||
{Event: entity.EventErrorLogin, Enable: true},
|
{Event: entity.EventErrorLogin, Enable: true},
|
||||||
{Event: entity.EventSuccessLogout, Enable: true},
|
{Event: entity.EventSuccessLogout, Enable: true},
|
||||||
{Event: entity.EventRoleChanged, Enable: false},
|
{Event: entity.EventRoleChanged, Enable: false},
|
||||||
{Event: entity.EventUserChanged, Enable: true},
|
{Event: entity.EventUserChanged, Enable: true},
|
||||||
{Event: entity.EventUserBlocked, Enable: true},
|
|
||||||
{Event: "новый#2", Enable: false},
|
{Event: "новый#2", Enable: false},
|
||||||
})
|
})
|
||||||
s.Require().NoError(err)
|
t.Require().NoError(err)
|
||||||
|
|
||||||
response := make([]domain.AuditEvent, 0)
|
response := make([]domain.AuditEvent, 0)
|
||||||
err = s.httpCli.
|
err = t.grpcCli.
|
||||||
Post("admin/log/events").
|
Invoke("admin/log/events").
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
t.Require().NoError(err)
|
||||||
|
|
||||||
expectedSort := []bool{
|
expectedSort := []bool{
|
||||||
true, true, true, true, false, false, false, false,
|
true, true, true, false, false, false, false,
|
||||||
}
|
}
|
||||||
s.Require().Equal(len(expectedSort), len(response)) // nolint:testifylint
|
t.Require().Equal(len(expectedSort), len(response)) // nolint:testifylint
|
||||||
for i, event := range response {
|
for i, event := range response {
|
||||||
s.Require().Equal(expectedSort[i], event.Enabled)
|
t.Require().Equal(expectedSort[i], event.Enabled)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuditSuite) Test_SetEvents_HappyPath() {
|
func (t *AuditSuite) Test_SetEvents_HappyPath() {
|
||||||
err := s.httpCli.
|
err := t.grpcCli.
|
||||||
Post("admin/log/set_events").
|
Invoke("admin/log/set_events").
|
||||||
JsonRequestBody([]domain.SetAuditEvent{
|
JsonRequestBody([]domain.SetAuditEvent{
|
||||||
{Event: entity.EventUserChanged, Enabled: true},
|
{Event: entity.EventUserChanged, Enabled: true},
|
||||||
{Event: entity.EventRoleChanged, Enabled: false},
|
{Event: entity.EventRoleChanged, Enabled: false},
|
||||||
}).
|
}).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
t.Require().NoError(err)
|
||||||
|
|
||||||
expectedEventList := map[string]bool{
|
expectedEventList := map[string]bool{
|
||||||
entity.EventSuccessLogin: true,
|
entity.EventSuccessLogin: true,
|
||||||
@@ -152,91 +145,29 @@ func (s *AuditSuite) Test_SetEvents_HappyPath() {
|
|||||||
entity.EventSuccessLogout: true,
|
entity.EventSuccessLogout: true,
|
||||||
entity.EventRoleChanged: false,
|
entity.EventRoleChanged: false,
|
||||||
entity.EventUserChanged: true,
|
entity.EventUserChanged: true,
|
||||||
entity.EventUserBlocked: true,
|
|
||||||
}
|
}
|
||||||
eventRep := repository.NewAuditEvent(s.db)
|
eventRep := repository.NewAuditEvent(t.db)
|
||||||
eventList, err := eventRep.All(s.T().Context())
|
eventList, err := eventRep.All(context.Background())
|
||||||
s.Require().NoError(err)
|
t.Require().NoError(err)
|
||||||
for _, event := range eventList {
|
for _, event := range eventList {
|
||||||
enable, found := expectedEventList[event.Event]
|
enable, found := expectedEventList[event.Event]
|
||||||
s.Require().True(found)
|
t.Require().True(found)
|
||||||
s.Require().Equal(enable, event.Enable)
|
t.Require().Equal(enable, event.Enable)
|
||||||
delete(expectedEventList, event.Event)
|
delete(expectedEventList, event.Event)
|
||||||
}
|
}
|
||||||
s.Require().Empty(expectedEventList)
|
t.Require().Empty(expectedEventList)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
|
func (t *AuditSuite) Test_SetEvents_InvalidEvent() {
|
||||||
err := s.httpCli.Post("admin/log/set_events").
|
err := t.grpcCli.
|
||||||
|
Invoke("admin/log/set_events").
|
||||||
JsonRequestBody([]domain.SetAuditEvent{
|
JsonRequestBody([]domain.SetAuditEvent{
|
||||||
{Event: entity.EventUserChanged, Enabled: true},
|
{Event: entity.EventUserChanged, Enabled: true},
|
||||||
{Event: "новый#2", Enabled: false},
|
{Event: "новый#2", Enabled: false},
|
||||||
}).
|
}).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
t.Require().Error(err)
|
||||||
s.Require().Error(err)
|
s, isStatus := status.FromError(err)
|
||||||
|
t.Require().True(isStatus)
|
||||||
var httpErr httpcli.ErrorResponse
|
t.Require().Equal(codes.InvalidArgument, s.Code())
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
|
||||||
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *AuditSuite) Test_All_Logs() {
|
|
||||||
request := domain.AuditPageRequest{
|
|
||||||
Limit: 3,
|
|
||||||
Offset: 5,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "user_id",
|
|
||||||
Type: "desc",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var response *domain.AuditResponse
|
|
||||||
err := s.httpCli.
|
|
||||||
Post("admin/log/all").
|
|
||||||
JsonRequestBody(request).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 3)
|
|
||||||
s.Require().EqualValues(5, response.Items[0].UserId)
|
|
||||||
s.Require().EqualValues(4, response.Items[1].UserId)
|
|
||||||
s.Require().EqualValues(3, response.Items[2].UserId)
|
|
||||||
|
|
||||||
request.Query = &domain.AuditQuery{
|
|
||||||
Message: new("Выход"),
|
|
||||||
}
|
|
||||||
request.Limit = 10
|
|
||||||
request.Offset = 0
|
|
||||||
|
|
||||||
err = s.httpCli.
|
|
||||||
Post("admin/log/all").
|
|
||||||
JsonRequestBody(request).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 6)
|
|
||||||
s.Require().EqualValues(6, response.TotalCount)
|
|
||||||
s.Require().EqualValues(10, response.Items[0].UserId)
|
|
||||||
s.Require().EqualValues(9, response.Items[1].UserId)
|
|
||||||
s.Require().EqualValues(8, response.Items[2].UserId)
|
|
||||||
s.Require().EqualValues(7, response.Items[3].UserId)
|
|
||||||
s.Require().EqualValues(6, response.Items[4].UserId)
|
|
||||||
s.Require().EqualValues(5, response.Items[5].UserId)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *AuditSuite) insertAuditLogs() {
|
|
||||||
s.db.Must().Exec(`INSERT INTO audit (user_id, message, created_at, event)
|
|
||||||
VALUES (1, 'Успешный вход', NOW(), 'success_login'),
|
|
||||||
(2, 'Успешный вход', NOW(), 'success_login'),
|
|
||||||
(3, 'Неуспешный вход', NOW(), 'unsuccess_login'),
|
|
||||||
(4, 'Неуспешный вход', NOW(), 'unsuccess_login'),
|
|
||||||
(5, 'Успешный выход', NOW(), 'success_logout'),
|
|
||||||
(6, 'Успешный выход', NOW(), 'success_logout'),
|
|
||||||
(7, 'Неуспешный выход', NOW(), 'unsuccess_logout'),
|
|
||||||
(8, 'Неуспешный выход', NOW(), 'unsuccess_logout'),
|
|
||||||
(9, 'Выход', NOW(), 'logout'),
|
|
||||||
(10, 'Выход', NOW(), 'logout')`)
|
|
||||||
}
|
}
|
||||||
+75
-142
@@ -1,32 +1,33 @@
|
|||||||
package tests_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
"github.com/pkg/errors"
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
"isp-admin-service/repository"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/test/fake"
|
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
|
||||||
"golang.org/x/sync/errgroup"
|
"golang.org/x/sync/errgroup"
|
||||||
|
"msp-admin-service/assembly"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
"msp-admin-service/repository"
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
"github.com/stretchr/testify/suite"
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
"github.com/txix-open/isp-kit/http/httpcli"
|
||||||
"github.com/txix-open/isp-kit/json"
|
"github.com/txix-open/isp-kit/json"
|
||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAuthTestSuite(t *testing.T) {
|
func TestAuthTestSuite(t *testing.T) {
|
||||||
@@ -36,36 +37,26 @@ func TestAuthTestSuite(t *testing.T) {
|
|||||||
|
|
||||||
type AuthTestSuite struct {
|
type AuthTestSuite struct {
|
||||||
suite.Suite
|
suite.Suite
|
||||||
|
test *test.Test
|
||||||
test *test.Test
|
db *dbt.TestDb
|
||||||
db *dbt.TestDb
|
grpcCli *client.Client
|
||||||
httpCli *httpcli.Client
|
httpCli *httpcli.Client
|
||||||
oauthCli *httpcli.Client
|
|
||||||
oauthClientName string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) SetupTest() {
|
func (s *AuthTestSuite) SetupTest() {
|
||||||
testInstance, _ := test.New(s.T())
|
testInstance, _ := test.New(s.T())
|
||||||
s.test = testInstance
|
s.test = testInstance
|
||||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||||
s.oauthCli = httpcli.New()
|
s.httpCli = httpcli.New()
|
||||||
s.oauthClientName = fake.It[string]()
|
|
||||||
|
|
||||||
mocksrv, host := s.initMockOauth()
|
mocksrv, host := s.initMockSudir()
|
||||||
oauthHost, _ := url.JoinPath(host, "/blitz/")
|
|
||||||
s.oauthCli.GlobalRequestConfig().BaseUrl = oauthHost
|
|
||||||
|
|
||||||
remote := conf.Remote{
|
remote := conf.Remote{
|
||||||
Oauth: &conf.Oauth{
|
SudirAuth: &conf.SudirAuth{
|
||||||
Host: host,
|
ClientId: "admin",
|
||||||
Clients: []conf.OauthClientConfig{
|
ClientSecret: "admin",
|
||||||
{
|
Host: host,
|
||||||
ClientName: s.oauthClientName,
|
RedirectURI: "http://localhost",
|
||||||
ClientId: "admin",
|
|
||||||
ClientSecret: "admin",
|
|
||||||
RedirectURI: "http://localhost",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
ExpireSec: 3600,
|
ExpireSec: 3600,
|
||||||
AntiBruteforce: conf.AntiBruteforce{
|
AntiBruteforce: conf.AntiBruteforce{
|
||||||
@@ -73,16 +64,14 @@ func (s *AuthTestSuite) SetupTest() {
|
|||||||
DelayLoginRequestInSec: 1,
|
DelayLoginRequestInSec: 1,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
|
||||||
|
Config(context.Background(), emptyLdap, remote, time.Minute)
|
||||||
|
|
||||||
cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, s.db).
|
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||||
Config(s.T().Context(), remote, time.Minute)
|
s.grpcCli = apiCli
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
|
||||||
s.httpCli = cli
|
|
||||||
|
|
||||||
testInstance.T().Cleanup(func() {
|
testInstance.T().Cleanup(func() {
|
||||||
server.Close()
|
server.Shutdown()
|
||||||
mocksrv.Close()
|
mocksrv.Close()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -96,36 +85,30 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
response := domain.LoginResponse{}
|
response := domain.LoginResponse{}
|
||||||
err := s.httpCli.Post("admin/auth/login").
|
err := s.grpcCli.Invoke("admin/auth/login").
|
||||||
JsonRequestBody(domain.LoginRequest{
|
JsonRequestBody(domain.LoginRequest{
|
||||||
Email: "a@a.ru",
|
Email: "a@a.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||||
s.Require().Equal(tokenInfo.UserId, id)
|
s.Require().Equal(tokenInfo.UserId, id)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestLoginNotFound() {
|
func (s *AuthTestSuite) TestLoginNotFound() {
|
||||||
err := s.httpCli.Post("admin/auth/login").
|
err := s.grpcCli.Invoke("admin/auth/login").
|
||||||
JsonRequestBody(domain.LoginRequest{
|
JsonRequestBody(domain.LoginRequest{
|
||||||
Email: "a1@a.ru",
|
Email: "a1@a.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
}).
|
}).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
st, ok := status.FromError(err)
|
||||||
var httpErr httpcli.ErrorResponse
|
s.Require().True(ok)
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestBlockedUser() {
|
func (s *AuthTestSuite) TestBlockedUser() {
|
||||||
@@ -137,20 +120,16 @@ func (s *AuthTestSuite) TestBlockedUser() {
|
|||||||
Blocked: true,
|
Blocked: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
err := s.httpCli.Post("admin/auth/login").
|
err := s.grpcCli.Invoke("admin/auth/login").
|
||||||
JsonRequestBody(domain.LoginRequest{
|
JsonRequestBody(domain.LoginRequest{
|
||||||
Email: "a@a.ru",
|
Email: "a@a.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
}).
|
}).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
st, ok := status.FromError(err)
|
||||||
var httpErr httpcli.ErrorResponse
|
s.Require().True(ok)
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestLoginWrongPassword() {
|
func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||||
@@ -161,60 +140,34 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
|||||||
Password: "password",
|
Password: "password",
|
||||||
})
|
})
|
||||||
|
|
||||||
err := s.httpCli.Post("admin/auth/login").
|
err := s.grpcCli.Invoke("admin/auth/login").
|
||||||
JsonRequestBody(domain.LoginRequest{
|
JsonRequestBody(domain.LoginRequest{
|
||||||
Email: "a@a.ru",
|
Email: "a@a.ru",
|
||||||
Password: "WrongPassword",
|
Password: "WrongPassword",
|
||||||
}).
|
}).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
st, ok := status.FromError(err)
|
||||||
var httpErr httpcli.ErrorResponse
|
s.Require().True(ok)
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestOauthLoginHappyPath() {
|
func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
||||||
response := domain.LoginResponse{}
|
response := domain.LoginResponse{}
|
||||||
|
|
||||||
err := s.httpCli.Post("admin/auth/login_with_oauth").
|
err := s.grpcCli.Invoke("admin/auth/login_with_sudir").
|
||||||
JsonRequestBody(domain.LoginOauthRequest{
|
JsonRequestBody(domain.LoginSudirRequest{
|
||||||
AuthCode: "code",
|
AuthCode: "code",
|
||||||
ClientName: s.oauthClientName,
|
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
user := entity.User{}
|
user := entity.User{}
|
||||||
s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1")
|
s.db.Must().SelectRow(&user, "select id, email from users where sudir_user_id = $1", "sudirUser1")
|
||||||
s.Require().Equal("oauth@email.ru", user.Email)
|
s.Require().Equal("sudir@email.ru", user.Email)
|
||||||
s.Require().Equal("surname name patronymic", user.FullName)
|
|
||||||
|
|
||||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||||
s.Require().Equal(tokenInfo.UserId, user.Id)
|
s.Require().Equal(tokenInfo.UserId, user.Id)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
|
|
||||||
response := domain.LoginResponse{}
|
|
||||||
|
|
||||||
err := s.httpCli.Post("admin/auth/login_with_oauth").
|
|
||||||
JsonRequestBody(domain.LoginOauthRequest{
|
|
||||||
AuthCode: "code",
|
|
||||||
ClientName: s.oauthClientName + fake.It[string](),
|
|
||||||
}).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
|
||||||
|
|
||||||
var httpErr httpcli.ErrorResponse
|
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
|
||||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||||
@@ -226,38 +179,27 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
|||||||
CreatedAt: time.Time{},
|
CreatedAt: time.Time{},
|
||||||
ExpiredAt: time.Time{},
|
ExpiredAt: time.Time{},
|
||||||
})
|
})
|
||||||
err := s.httpCli.Post("admin/auth/logout").
|
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
|
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
|
||||||
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
|
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) Test_Logout_NotFound() {
|
func (s *AuthTestSuite) Test_Logout_NotFound() {
|
||||||
err := s.httpCli.Post("admin/auth/logout").
|
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||||
Header(domain.AdminAuthIdHeader, "0143218411981").
|
AppendMetadata(domain.AdminAuthIdHeader, "0143218411981").
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
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.All(context.Background(), 10, 0)
|
||||||
Limit: 10,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "created_at",
|
|
||||||
Type: "desc",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
s.Require().Len(auditList, 1)
|
s.Require().Len(auditList, 1) //nolint:mnd
|
||||||
s.Require().Equal(entity.EventSuccessLogout, auditList[0].Event)
|
s.Require().Equal(entity.EventSuccessLogout, auditList[0].Event)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
||||||
@@ -269,15 +211,13 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
|||||||
CreatedAt: time.Time{},
|
CreatedAt: time.Time{},
|
||||||
ExpiredAt: time.Time{},
|
ExpiredAt: time.Time{},
|
||||||
})
|
})
|
||||||
err := s.httpCli.Post("admin/auth/logout").
|
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
|
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
|
||||||
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
|
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestBruteForceLogin() {
|
func (s *AuthTestSuite) TestBruteForceLogin() {
|
||||||
@@ -290,29 +230,25 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
|||||||
|
|
||||||
tooManyRequestsErrorCount := &atomic.Int32{}
|
tooManyRequestsErrorCount := &atomic.Int32{}
|
||||||
unauthorizedErrorCount := &atomic.Int32{}
|
unauthorizedErrorCount := &atomic.Int32{}
|
||||||
group, ctx := errgroup.WithContext(s.T().Context())
|
group, ctx := errgroup.WithContext(context.Background())
|
||||||
for index := range 100 {
|
for index := range 100 {
|
||||||
group.Go(func() error {
|
group.Go(func() error {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
response := domain.LoginResponse{}
|
response := domain.LoginResponse{}
|
||||||
err := s.httpCli.Post("admin/auth/login").
|
err := s.grpcCli.Invoke("admin/auth/login").
|
||||||
JsonRequestBody(domain.LoginRequest{
|
JsonRequestBody(domain.LoginRequest{
|
||||||
Email: "a@a.ru",
|
Email: "a@a.ru",
|
||||||
Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
|
Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
StatusCodeToError().
|
Do(ctx)
|
||||||
DoWithoutResponse(ctx)
|
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
|
||||||
var httpErr httpcli.ErrorResponse
|
switch status.Code(err) { // nolint:exhaustive
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
case codes.ResourceExhausted:
|
||||||
|
|
||||||
switch httpErr.StatusCode { // nolint:exhaustive
|
|
||||||
case http.StatusTooManyRequests:
|
|
||||||
tooManyRequestsErrorCount.Add(1)
|
tooManyRequestsErrorCount.Add(1)
|
||||||
s.Require().True(time.Since(start) < time.Second)
|
s.Require().True(time.Since(start) < time.Second)
|
||||||
case http.StatusUnauthorized:
|
case codes.Unauthenticated:
|
||||||
unauthorizedErrorCount.Add(1)
|
unauthorizedErrorCount.Add(1)
|
||||||
s.Require().True(time.Since(start) > time.Second)
|
s.Require().True(time.Since(start) > time.Second)
|
||||||
default:
|
default:
|
||||||
@@ -328,15 +264,13 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
|||||||
|
|
||||||
s.Require().EqualValues(97, tooManyRequestsErrorCount.Load())
|
s.Require().EqualValues(97, tooManyRequestsErrorCount.Load())
|
||||||
s.Require().EqualValues(3, unauthorizedErrorCount.Load())
|
s.Require().EqualValues(3, unauthorizedErrorCount.Load())
|
||||||
|
|
||||||
time.Sleep(2 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) initMockOauth() (*httptest.Server, string) {
|
func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/blitz/oauth/te", func(writer http.ResponseWriter, request *http.Request) {
|
mux.HandleFunc("/blitz/oauth/te", func(writer http.ResponseWriter, request *http.Request) {
|
||||||
res := entity.OauthTokenResponse{
|
res := entity.SudirTokenResponse{
|
||||||
OauthAuthError: nil,
|
SudirAuthError: nil,
|
||||||
IdToken: "1",
|
IdToken: "1",
|
||||||
AccessToken: "token",
|
AccessToken: "token",
|
||||||
}
|
}
|
||||||
@@ -346,14 +280,13 @@ func (s *AuthTestSuite) initMockOauth() (*httptest.Server, string) {
|
|||||||
s.NoError(err)
|
s.NoError(err)
|
||||||
})
|
})
|
||||||
mux.HandleFunc("/blitz/oauth/me", func(writer http.ResponseWriter, request *http.Request) {
|
mux.HandleFunc("/blitz/oauth/me", func(writer http.ResponseWriter, request *http.Request) {
|
||||||
res := entity.OauthUserResponse{
|
res := entity.SudirUserResponse{
|
||||||
OauthAuthError: nil,
|
SudirAuthError: nil,
|
||||||
Email: "oauth@email.ru",
|
Email: "sudir@email.ru",
|
||||||
Groups: []string{"DIT-KKD-Admins"},
|
Groups: []string{"DIT-KKD-Admins"},
|
||||||
Sub: "oauthUser1",
|
Sub: "sudirUser1",
|
||||||
GivenName: "name",
|
GivenName: "name",
|
||||||
FamilyName: "surname",
|
FamilyName: "surname",
|
||||||
Name: "surname name patronymic",
|
|
||||||
}
|
}
|
||||||
data, err := json.Marshal(res)
|
data, err := json.Marshal(res)
|
||||||
s.Require().NoError(err) //nolint:testifylint
|
s.Require().NoError(err) //nolint:testifylint
|
||||||
|
|||||||
+14
-16
@@ -1,18 +1,18 @@
|
|||||||
package tests_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
"github.com/stretchr/testify/suite"
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
"msp-admin-service/assembly"
|
||||||
|
"msp-admin-service/conf"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCustomizationTestSuite(t *testing.T) {
|
func TestCustomizationTestSuite(t *testing.T) {
|
||||||
@@ -22,10 +22,9 @@ func TestCustomizationTestSuite(t *testing.T) {
|
|||||||
|
|
||||||
type CustomizationTestSuite struct {
|
type CustomizationTestSuite struct {
|
||||||
suite.Suite
|
suite.Suite
|
||||||
|
|
||||||
test *test.Test
|
test *test.Test
|
||||||
db *dbt.TestDb
|
db *dbt.TestDb
|
||||||
httpCli *httpcli.Client
|
grpcCli *client.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *CustomizationTestSuite) SetupTest() {
|
func (s *CustomizationTestSuite) SetupTest() {
|
||||||
@@ -40,25 +39,24 @@ func (s *CustomizationTestSuite) SetupTest() {
|
|||||||
},
|
},
|
||||||
ExpireSec: 0,
|
ExpireSec: 0,
|
||||||
}
|
}
|
||||||
cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
cfg := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
||||||
Config(s.T().Context(), remote, time.Minute)
|
Config(context.Background(), emptyLdap, remote, time.Minute)
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||||
s.httpCli = cli
|
s.grpcCli = apiCli
|
||||||
|
|
||||||
testInstance.T().Cleanup(func() {
|
testInstance.T().Cleanup(func() {
|
||||||
server.Close()
|
server.Shutdown()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *CustomizationTestSuite) TestGetDesign() {
|
func (s *CustomizationTestSuite) TestGetDesign() {
|
||||||
response := conf.UIDesign{}
|
response := conf.UIDesign{}
|
||||||
err := s.httpCli.
|
err := s.grpcCli.
|
||||||
Post("admin/user/get_design").
|
Invoke("admin/user/get_design").
|
||||||
JsonRequestBody(struct{}{}).
|
JsonRequestBody(struct{}{}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
expected := conf.UIDesign{
|
expected := conf.UIDesign{
|
||||||
Name: "test",
|
Name: "test",
|
||||||
|
|||||||
+13
-17
@@ -1,35 +1,35 @@
|
|||||||
package tests_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"isp-admin-service/entity"
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/db/query"
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//nolint:gomnd
|
||||||
func InsertUser(db *dbt.TestDb, user entity.User) int64 {
|
func InsertUser(db *dbt.TestDb, user entity.User) int64 {
|
||||||
if user.Password != "" {
|
if user.Password != "" {
|
||||||
passwordBytes, _ := bcrypt.GenerateFromPassword([]byte(user.Password), 12)
|
passwordBytes, _ := bcrypt.GenerateFromPassword([]byte(user.Password), 12)
|
||||||
user.Password = string(passwordBytes)
|
user.Password = string(passwordBytes)
|
||||||
}
|
}
|
||||||
var id int64
|
var id int64
|
||||||
db.Must().SelectRow(&id, `insert into users (first_name, last_name, full_name, email, password, blocked, last_active_at)
|
db.Must().SelectRow(&id, `insert into users (first_name, last_name, email, password, blocked)
|
||||||
values($1,$2,$3,$4,$5,$6,$7) returning id`,
|
values($1,$2,$3,$4,$5) returning id`,
|
||||||
user.FirstName, user.LastName, user.FullName, user.Email, user.Password, user.Blocked, user.LastActiveAt)
|
user.FirstName, user.LastName, user.Email, user.Password, user.Blocked)
|
||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
func InsertOauthUser(db *dbt.TestDb, user entity.OauthUser) int64 {
|
func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) int64 {
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Insert("users").
|
Insert("users").
|
||||||
Columns("oauth_user_id", "first_name", "last_name", "full_name", "email").
|
Columns("sudir_user_id", "first_name", "last_name", "email").
|
||||||
Values(user.OauthUserId, user.FirstName, user.LastName, user.FullName, user.Email).
|
Values(user.SudirUserId, user.FirstName, user.LastName, user.Email).
|
||||||
Suffix("RETURNING id").
|
Suffix("RETURNING id").
|
||||||
ToSql()
|
ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(errors.WithMessagef(err, "insert oauth user"))
|
panic(errors.WithMessagef(err, "insert sudir user"))
|
||||||
}
|
}
|
||||||
var id int64
|
var id int64
|
||||||
db.Must().SelectRow(&id, q, args...)
|
db.Must().SelectRow(&id, q, args...)
|
||||||
@@ -42,13 +42,9 @@ func InsertRole(db *dbt.TestDb, role entity.Role) int64 {
|
|||||||
}
|
}
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Insert("roles").
|
Insert("roles").
|
||||||
Columns("name", "permissions", "application_group").
|
Columns("name", "permissions").
|
||||||
Values(role.Name, role.Permissions, role.ApplicationGroup).
|
Values(role.Name, role.Permissions).
|
||||||
Suffix(`ON CONFLICT (name) DO UPDATE SET
|
Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, permissions = EXCLUDED.permissions RETURNING id").
|
||||||
name = EXCLUDED.name,
|
|
||||||
permissions = EXCLUDED.permissions,
|
|
||||||
application_group = EXCLUDED.application_group
|
|
||||||
RETURNING id`).
|
|
||||||
ToSql()
|
ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(errors.WithMessagef(err, "insert role"))
|
panic(errors.WithMessagef(err, "insert role"))
|
||||||
|
|||||||
@@ -1,243 +0,0 @@
|
|||||||
// nolint: funlen
|
|
||||||
package tests_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/csv"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
"isp-admin-service/repository"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
|
||||||
"github.com/txix-open/isp-kit/test"
|
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestDownloadSuite(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
suite.Run(t, &DownloadSuite{})
|
|
||||||
}
|
|
||||||
|
|
||||||
type DownloadSuite struct {
|
|
||||||
suite.Suite
|
|
||||||
|
|
||||||
test *test.Test
|
|
||||||
db *dbt.TestDb
|
|
||||||
httpCli *httpcli.Client
|
|
||||||
permissions entity.PermList
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *DownloadSuite) SetupTest() {
|
|
||||||
testInstance, _ := test.New(s.T())
|
|
||||||
s.test = testInstance
|
|
||||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
|
||||||
|
|
||||||
remote := conf.Remote{
|
|
||||||
Permissions: []conf.Permission{
|
|
||||||
{
|
|
||||||
Key: "data_download",
|
|
||||||
Name: "123",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
|
||||||
Config(s.T().Context(), remote, time.Minute)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
|
||||||
s.httpCli = cli
|
|
||||||
|
|
||||||
s.permissions = entity.PermList{
|
|
||||||
"data_download",
|
|
||||||
}
|
|
||||||
|
|
||||||
testInstance.T().Cleanup(func() {
|
|
||||||
server.Close()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *DownloadSuite) TestUsersHappyPath() {
|
|
||||||
id1 := InsertUser(s.db, entity.User{
|
|
||||||
FirstName: "Alice",
|
|
||||||
LastName: "Bob",
|
|
||||||
FullName: "Bob Alice",
|
|
||||||
Email: "alice@a.ru",
|
|
||||||
Password: "password",
|
|
||||||
})
|
|
||||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)})
|
|
||||||
|
|
||||||
resp, err := s.httpCli.Post("user/download").
|
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
|
||||||
Limit: 1000,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "id",
|
|
||||||
Type: "desc",
|
|
||||||
},
|
|
||||||
}).
|
|
||||||
Do(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
defer resp.Raw.Body.Close()
|
|
||||||
s.Require().Equal(http.StatusOK, resp.StatusCode())
|
|
||||||
|
|
||||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
|
||||||
s.Require().NoError(err)
|
|
||||||
s.Require().NotEmpty(records)
|
|
||||||
|
|
||||||
header := records[0]
|
|
||||||
col := make(map[string]int, len(header))
|
|
||||||
for i, name := range header {
|
|
||||||
col[name] = i
|
|
||||||
}
|
|
||||||
|
|
||||||
idIdx, ok := col["id"]
|
|
||||||
s.Require().True(ok)
|
|
||||||
emailIdx, ok := col["Email"]
|
|
||||||
s.Require().True(ok)
|
|
||||||
fullNameIdx, ok := col["Пользователь"]
|
|
||||||
s.Require().True(ok)
|
|
||||||
|
|
||||||
s.Require().Len(records, 4)
|
|
||||||
|
|
||||||
row := records[1]
|
|
||||||
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() {
|
|
||||||
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(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.SessionPageRequest{
|
|
||||||
Limit: 1000,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "user_id",
|
|
||||||
Type: "desc",
|
|
||||||
},
|
|
||||||
}).
|
|
||||||
Do(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
defer resp.Raw.Body.Close()
|
|
||||||
s.Require().Equal(http.StatusOK, resp.StatusCode())
|
|
||||||
|
|
||||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
|
||||||
s.Require().NoError(err)
|
|
||||||
s.Require().NotEmpty(records)
|
|
||||||
|
|
||||||
header := records[0]
|
|
||||||
col := make(map[string]int, len(header))
|
|
||||||
for i, name := range header {
|
|
||||||
col[name] = i
|
|
||||||
}
|
|
||||||
|
|
||||||
userIdx, ok := col["Пользователь"]
|
|
||||||
s.Require().True(ok)
|
|
||||||
idIdx, ok := col["Идентификатор"]
|
|
||||||
s.Require().True(ok)
|
|
||||||
|
|
||||||
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() {
|
|
||||||
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(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.AuditPageRequest{
|
|
||||||
Limit: 1000,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "user_id",
|
|
||||||
Type: "desc",
|
|
||||||
},
|
|
||||||
}).
|
|
||||||
StatusCodeToError().
|
|
||||||
Do(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
|
||||||
s.Require().NoError(err)
|
|
||||||
s.Require().NotEmpty(records)
|
|
||||||
|
|
||||||
header := records[0]
|
|
||||||
col := make(map[string]int, len(header))
|
|
||||||
for i, name := range header {
|
|
||||||
col[name] = i
|
|
||||||
}
|
|
||||||
|
|
||||||
idIdx, ok := col["Пользователь"]
|
|
||||||
s.Require().True(ok)
|
|
||||||
moveIdx, ok := col["Действие"]
|
|
||||||
s.Require().True(ok)
|
|
||||||
|
|
||||||
s.Require().Len(records, 2)
|
|
||||||
row := records[1]
|
|
||||||
s.Require().EqualValues("Bob Alice", row[idIdx])
|
|
||||||
s.Require().EqualValues("audit1@a.ru", row[moveIdx])
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *DownloadSuite) TestRolesHappyPath() {
|
|
||||||
resp, err := s.httpCli.Post("role/download").
|
|
||||||
StatusCodeToError().
|
|
||||||
Do(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
|
||||||
s.Require().NoError(err)
|
|
||||||
s.Require().NotEmpty(records)
|
|
||||||
}
|
|
||||||
+25
-24
@@ -1,21 +1,18 @@
|
|||||||
package tests_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"msp-admin-service/service/inactive_worker"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/service/inactive_worker"
|
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
"isp-admin-service/repository"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/bgjobx"
|
"github.com/txix-open/isp-kit/bgjobx"
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
|
"msp-admin-service/assembly"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
"msp-admin-service/repository"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestInactiveWorker(t *testing.T) {
|
func TestInactiveWorker(t *testing.T) {
|
||||||
@@ -24,20 +21,33 @@ func TestInactiveWorker(t *testing.T) {
|
|||||||
test, require := test.New(t)
|
test, require := test.New(t)
|
||||||
db := dbt.New(test, dbx.WithMigrationRunner("../migrations", test.Logger()))
|
db := dbt.New(test, dbx.WithMigrationRunner("../migrations", test.Logger()))
|
||||||
|
|
||||||
userId := InsertUser(db, entity.User{Email: "a@test", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)})
|
userId := InsertUser(db, entity.User{Email: "a@test"})
|
||||||
InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()})
|
InsertUser(db, entity.User{Email: "b@test"})
|
||||||
|
InsertTokenEntity(db, entity.Token{
|
||||||
|
Id: 0,
|
||||||
|
Token: "123",
|
||||||
|
UserId: userId,
|
||||||
|
Status: entity.TokenStatusAllowed,
|
||||||
|
CreatedAt: time.Now().UTC().Add(-48 * time.Hour),
|
||||||
|
})
|
||||||
|
InsertTokenEntity(db, entity.Token{
|
||||||
|
Id: 0,
|
||||||
|
Token: "234",
|
||||||
|
UserId: userId,
|
||||||
|
Status: entity.TokenStatusAllowed,
|
||||||
|
CreatedAt: time.Now().UTC().Add(-5 * 24 * time.Hour),
|
||||||
|
})
|
||||||
|
|
||||||
config, err := assembly.NewLocator(test.Logger(), nil, db).
|
config := assembly.NewLocator(test.Logger(), nil, db).
|
||||||
Config(t.Context(), conf.Remote{
|
Config(t.Context(), emptyLdap, conf.Remote{
|
||||||
BlockInactiveWorker: conf.BlockInactiveWorker{
|
BlockInactiveWorker: conf.BlockInactiveWorker{
|
||||||
DaysThreshold: 1,
|
DaysThreshold: 1,
|
||||||
RunIntervalInMinutes: 1,
|
RunIntervalInMinutes: 1,
|
||||||
},
|
},
|
||||||
}, 500*time.Millisecond)
|
}, 500*time.Millisecond)
|
||||||
require.NoError(err)
|
|
||||||
|
|
||||||
bgjobCli := bgjobx.NewClient(db, test.Logger())
|
bgjobCli := bgjobx.NewClient(db, test.Logger())
|
||||||
err = inactive_worker.EnqueueSeedJob(t.Context(), bgjobCli)
|
err := inactive_worker.EnqueueSeedJob(t.Context(), bgjobCli)
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
err = bgjobCli.Upgrade(t.Context(), config.BgJobCfg)
|
err = bgjobCli.Upgrade(t.Context(), config.BgJobCfg)
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
@@ -48,16 +58,7 @@ func TestInactiveWorker(t *testing.T) {
|
|||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
require.True(user.Blocked)
|
require.True(user.Blocked)
|
||||||
|
|
||||||
list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{
|
list, err := repository.NewAudit(db).All(t.Context(), 10, 0)
|
||||||
Limit: 10,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "created_at",
|
|
||||||
Type: "desc",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
require.Len(list, 1)
|
require.Len(list, 1)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package tests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/service/ldap"
|
||||||
|
)
|
||||||
|
|
||||||
|
type mockLdap struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m mockLdap) IsExist(ctx context.Context, dn string) (bool, error) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m mockLdap) DnByUserPrincipalName(ctx context.Context, principalName string) (string, error) {
|
||||||
|
return principalName, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m mockLdap) ModifyMemberAttr(ctx context.Context, userDn string, groupDn string, operation string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m mockLdap) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
//nolint:gochecknoglobals
|
||||||
|
emptyLdap = ldap.RepoSupplier(func(config *conf.Ldap) (ldap.Repo, error) {
|
||||||
|
return mockLdap{}, nil
|
||||||
|
})
|
||||||
|
)
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
package tests_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
|
||||||
"github.com/txix-open/isp-kit/test"
|
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestRoleTestSuite(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
suite.Run(t, &RoleTestSuite{})
|
|
||||||
}
|
|
||||||
|
|
||||||
type RoleTestSuite struct {
|
|
||||||
suite.Suite
|
|
||||||
|
|
||||||
test *test.Test
|
|
||||||
db *dbt.TestDb
|
|
||||||
httpCli *httpcli.Client
|
|
||||||
adminId int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *RoleTestSuite) SetupTest() {
|
|
||||||
testInstance, _ := test.New(s.T())
|
|
||||||
s.test = testInstance
|
|
||||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
|
||||||
|
|
||||||
remote := conf.Remote{
|
|
||||||
ExpireSec: 0,
|
|
||||||
}
|
|
||||||
cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
|
|
||||||
Config(s.T().Context(), remote, time.Minute)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
|
|
||||||
s.httpCli = apiCli
|
|
||||||
|
|
||||||
testInstance.T().Cleanup(func() {
|
|
||||||
server.Close()
|
|
||||||
})
|
|
||||||
|
|
||||||
roleId := InsertRole(s.db, entity.Role{
|
|
||||||
Name: "admin_test",
|
|
||||||
Permissions: []string{
|
|
||||||
"role_view",
|
|
||||||
"role_add",
|
|
||||||
"role_update",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
s.adminId = InsertUser(s.db, entity.User{
|
|
||||||
Email: "admin@test.ru",
|
|
||||||
})
|
|
||||||
InsertUserRole(s.db, entity.UserRole{
|
|
||||||
UserId: int(s.adminId),
|
|
||||||
RoleId: int(roleId),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *RoleTestSuite) TestAllRolesWithoutFilter() {
|
|
||||||
InsertRole(s.db, entity.Role{Name: "empty"})
|
|
||||||
InsertRole(s.db, entity.Role{Name: "groupA_1", ApplicationGroup: "groupA"})
|
|
||||||
InsertRole(s.db, entity.Role{Name: "groupA_2", ApplicationGroup: "groupA"})
|
|
||||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
|
||||||
|
|
||||||
roles := []domain.Role{}
|
|
||||||
_, err := s.request("admin/role/all", domain.RoleAllRequest{}, &roles)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
groups := make(map[string]string, len(roles))
|
|
||||||
for _, role := range roles {
|
|
||||||
groups[role.Name] = role.ApplicationGroup
|
|
||||||
}
|
|
||||||
|
|
||||||
s.Require().Empty(groups["empty"])
|
|
||||||
s.Require().Equal("groupA", groups["groupA_1"])
|
|
||||||
s.Require().Equal("groupA", groups["groupA_2"])
|
|
||||||
s.Require().Equal("groupB", groups["groupB"])
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *RoleTestSuite) TestAllRolesInvalidArgument() {
|
|
||||||
roles := []domain.Role{}
|
|
||||||
statusCode, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles)
|
|
||||||
|
|
||||||
s.Require().Error(err)
|
|
||||||
s.Require().Equal(http.StatusBadRequest, statusCode)
|
|
||||||
s.Require().Empty(roles)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *RoleTestSuite) TestAllRolesFilterByApplicationGroup() {
|
|
||||||
InsertRole(s.db, entity.Role{Name: "groupA", ApplicationGroup: "groupA"})
|
|
||||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
|
||||||
|
|
||||||
roles := []domain.Role{}
|
|
||||||
_, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(roles, 1)
|
|
||||||
s.Require().Equal("groupA", roles[0].ApplicationGroup)
|
|
||||||
|
|
||||||
roles = []domain.Role{}
|
|
||||||
_, err = s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Empty(roles)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *RoleTestSuite) TestCreateRoleApplicationGroup() {
|
|
||||||
role := domain.Role{}
|
|
||||||
_, err := s.request("admin/role/create", domain.CreateRoleRequest{
|
|
||||||
Name: "role_new",
|
|
||||||
ApplicationGroup: "group",
|
|
||||||
Permissions: []string{},
|
|
||||||
}, &role)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
roleEmpty := domain.Role{}
|
|
||||||
_, err = s.request("admin/role/create", domain.CreateRoleRequest{
|
|
||||||
Name: "role_empty",
|
|
||||||
Permissions: []string{},
|
|
||||||
}, &roleEmpty)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Equal("role_new", role.Name)
|
|
||||||
s.Require().Equal("group", role.ApplicationGroup)
|
|
||||||
s.Require().Equal("role_empty", roleEmpty.Name)
|
|
||||||
s.Require().Empty(roleEmpty.ApplicationGroup)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *RoleTestSuite) TestUpdateRoleApplicationGroup() {
|
|
||||||
roleId := InsertRole(s.db, entity.Role{
|
|
||||||
Name: "role_old",
|
|
||||||
ApplicationGroup: "group_old",
|
|
||||||
})
|
|
||||||
|
|
||||||
role := domain.Role{}
|
|
||||||
_, err := s.request("admin/role/update", domain.UpdateRoleRequest{
|
|
||||||
Id: int(roleId),
|
|
||||||
Name: "role_new",
|
|
||||||
ApplicationGroup: "group_new",
|
|
||||||
Permissions: []string{},
|
|
||||||
}, &role)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
s.Require().Equal("role_new", role.Name)
|
|
||||||
s.Require().Equal("group_new", role.ApplicationGroup)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *RoleTestSuite) request(path string, req, resp any) (int, error) {
|
|
||||||
err := s.httpCli.Post(path).
|
|
||||||
JsonRequestBody(req).
|
|
||||||
JsonResponseBody(resp).
|
|
||||||
StatusCodeToError().
|
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
if err != nil {
|
|
||||||
return http.StatusBadRequest, errors.WithMessagef(err, "request %s", path)
|
|
||||||
}
|
|
||||||
|
|
||||||
return http.StatusOK, nil
|
|
||||||
}
|
|
||||||
+27
-28
@@ -1,21 +1,22 @@
|
|||||||
package tests_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"github.com/stretchr/testify/suite"
|
"github.com/stretchr/testify/suite"
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
"github.com/txix-open/isp-kit/http/httpcli"
|
||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
"msp-admin-service/assembly"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSecureSuite(t *testing.T) {
|
func TestSecureSuite(t *testing.T) {
|
||||||
@@ -25,11 +26,10 @@ func TestSecureSuite(t *testing.T) {
|
|||||||
|
|
||||||
type SecureSuite struct {
|
type SecureSuite struct {
|
||||||
suite.Suite
|
suite.Suite
|
||||||
|
|
||||||
test *test.Test
|
test *test.Test
|
||||||
require *require.Assertions
|
require *require.Assertions
|
||||||
db *dbt.TestDb
|
db *dbt.TestDb
|
||||||
httpCli *httpcli.Client
|
grpcCli *client.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SecureSuite) SetupTest() {
|
func (s *SecureSuite) SetupTest() {
|
||||||
@@ -39,15 +39,14 @@ func (s *SecureSuite) SetupTest() {
|
|||||||
remote := conf.Remote{
|
remote := conf.Remote{
|
||||||
ExpireSec: 3600,
|
ExpireSec: 3600,
|
||||||
}
|
}
|
||||||
cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, s.db).
|
cfg := assembly.NewLocator(s.test.Logger(), httpCli, s.db).
|
||||||
Config(s.T().Context(), remote, time.Minute)
|
Config(context.Background(), emptyLdap, remote, time.Minute)
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
server, apiCli := httpt.TestServer(s.test, cfg.Handler)
|
server, apiCli := grpct.TestServer(s.test, cfg.Handler)
|
||||||
s.test.T().Cleanup(func() {
|
s.test.T().Cleanup(func() {
|
||||||
server.Close()
|
server.Shutdown()
|
||||||
})
|
})
|
||||||
s.httpCli = apiCli
|
s.grpcCli = apiCli
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||||
@@ -60,12 +59,12 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
result := domain.SecureAuthResponse{}
|
result := domain.SecureAuthResponse{}
|
||||||
err := s.httpCli.Post("admin/secure/authenticate").
|
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||||
JsonRequestBody(domain.SecureAuthRequest{
|
JsonRequestBody(domain.SecureAuthRequest{
|
||||||
Token: "happy_path",
|
Token: "happy_path",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&result).
|
JsonResponseBody(&result).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.require.NoError(err)
|
s.require.NoError(err)
|
||||||
s.require.Equal(domain.SecureAuthResponse{
|
s.require.Equal(domain.SecureAuthResponse{
|
||||||
Authenticated: true,
|
Authenticated: true,
|
||||||
@@ -84,12 +83,12 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
result := domain.SecureAuthResponse{}
|
result := domain.SecureAuthResponse{}
|
||||||
err := s.httpCli.Post("admin/secure/authenticate").
|
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||||
JsonRequestBody(domain.SecureAuthRequest{
|
JsonRequestBody(domain.SecureAuthRequest{
|
||||||
Token: "revoked",
|
Token: "revoked",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&result).
|
JsonResponseBody(&result).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.require.NoError(err)
|
s.require.NoError(err)
|
||||||
s.require.Equal(domain.SecureAuthResponse{
|
s.require.Equal(domain.SecureAuthResponse{
|
||||||
Authenticated: false,
|
Authenticated: false,
|
||||||
@@ -108,12 +107,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
result := domain.SecureAuthResponse{}
|
result := domain.SecureAuthResponse{}
|
||||||
err := s.httpCli.Post("admin/secure/authenticate").
|
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||||
JsonRequestBody(domain.SecureAuthRequest{
|
JsonRequestBody(domain.SecureAuthRequest{
|
||||||
Token: "expired",
|
Token: "expired",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&result).
|
JsonResponseBody(&result).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.require.NoError(err)
|
s.require.NoError(err)
|
||||||
s.require.Equal(domain.SecureAuthResponse{
|
s.require.Equal(domain.SecureAuthResponse{
|
||||||
Authenticated: false,
|
Authenticated: false,
|
||||||
@@ -124,12 +123,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
|
|||||||
|
|
||||||
func (s *SecureSuite) Test_Authenticate_NotFound() {
|
func (s *SecureSuite) Test_Authenticate_NotFound() {
|
||||||
result := domain.SecureAuthResponse{}
|
result := domain.SecureAuthResponse{}
|
||||||
err := s.httpCli.Post("admin/secure/authenticate").
|
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||||
JsonRequestBody(domain.SecureAuthRequest{
|
JsonRequestBody(domain.SecureAuthRequest{
|
||||||
Token: "not_found",
|
Token: "not_found",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&result).
|
JsonResponseBody(&result).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.require.NoError(err)
|
s.require.NoError(err)
|
||||||
s.require.Equal(domain.SecureAuthResponse{
|
s.require.Equal(domain.SecureAuthResponse{
|
||||||
Authenticated: false,
|
Authenticated: false,
|
||||||
@@ -164,35 +163,35 @@ func (s *SecureSuite) Test_Authorize_HappyPath() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
result := domain.SecureAuthzResponse{}
|
result := domain.SecureAuthzResponse{}
|
||||||
err := s.httpCli.Post("admin/secure/authorize").
|
err := s.grpcCli.Invoke("admin/secure/authorize").
|
||||||
JsonRequestBody(domain.SecureAuthzRequest{
|
JsonRequestBody(domain.SecureAuthzRequest{
|
||||||
AdminId: int(userId),
|
AdminId: int(userId),
|
||||||
Permission: "perm1",
|
Permission: "perm1",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&result).
|
JsonResponseBody(&result).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.require.NoError(err)
|
s.require.NoError(err)
|
||||||
s.require.True(result.Authorized)
|
s.require.True(result.Authorized)
|
||||||
|
|
||||||
result = domain.SecureAuthzResponse{}
|
result = domain.SecureAuthzResponse{}
|
||||||
err = s.httpCli.Post("admin/secure/authorize").
|
err = s.grpcCli.Invoke("admin/secure/authorize").
|
||||||
JsonRequestBody(domain.SecureAuthzRequest{
|
JsonRequestBody(domain.SecureAuthzRequest{
|
||||||
AdminId: int(userId),
|
AdminId: int(userId),
|
||||||
Permission: "perm2",
|
Permission: "perm2",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&result).
|
JsonResponseBody(&result).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.require.NoError(err)
|
s.require.NoError(err)
|
||||||
s.require.True(result.Authorized)
|
s.require.True(result.Authorized)
|
||||||
|
|
||||||
result = domain.SecureAuthzResponse{}
|
result = domain.SecureAuthzResponse{}
|
||||||
err = s.httpCli.Post("admin/secure/authorize").
|
err = s.grpcCli.Invoke("admin/secure/authorize").
|
||||||
JsonRequestBody(domain.SecureAuthzRequest{
|
JsonRequestBody(domain.SecureAuthzRequest{
|
||||||
AdminId: int(userId),
|
AdminId: int(userId),
|
||||||
Permission: "perm3",
|
Permission: "perm3",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&result).
|
JsonResponseBody(&result).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.require.NoError(err)
|
s.require.NoError(err)
|
||||||
s.require.False(result.Authorized)
|
s.require.False(result.Authorized)
|
||||||
}
|
}
|
||||||
@@ -1,271 +0,0 @@
|
|||||||
package tests_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strconv"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
"isp-admin-service/service/session_worker"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
|
||||||
"github.com/txix-open/isp-kit/bgjobx"
|
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
|
||||||
"github.com/txix-open/isp-kit/test"
|
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestSessionSuite(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
suite.Run(t, &SessionSuite{})
|
|
||||||
}
|
|
||||||
|
|
||||||
type SessionSuite struct {
|
|
||||||
suite.Suite
|
|
||||||
|
|
||||||
test *test.Test
|
|
||||||
db *dbt.TestDb
|
|
||||||
config assembly.Config
|
|
||||||
httpCli *httpcli.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SessionSuite) SetupTest() {
|
|
||||||
testInstance, _ := test.New(s.T())
|
|
||||||
s.test = testInstance
|
|
||||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
|
||||||
|
|
||||||
remote := conf.Remote{
|
|
||||||
Audit: conf.Audit{
|
|
||||||
EventSettings: []conf.AuditEventSetting{
|
|
||||||
{
|
|
||||||
Event: entity.EventSuccessLogin,
|
|
||||||
Name: "успешный вход",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Event: entity.EventErrorLogin,
|
|
||||||
Name: "неуспешный вход",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Event: entity.EventSuccessLogout,
|
|
||||||
Name: "успешный выход",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Event: entity.EventRoleChanged,
|
|
||||||
Name: "изменение роли",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Event: entity.EventUserChanged,
|
|
||||||
Name: "изменение пользователя",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Event: entity.EventUserBlocked,
|
|
||||||
Name: "изменение статуса блокировки пользователя",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
AuditTTl: conf.AuditTTlSetting{},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
|
|
||||||
Config(s.T().Context(), remote, 500*time.Millisecond)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.config = config
|
|
||||||
|
|
||||||
server, cli := httpt.TestServer(s.test, config.Handler)
|
|
||||||
s.httpCli = cli
|
|
||||||
|
|
||||||
testInstance.T().Cleanup(func() {
|
|
||||||
server.Close()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
//nolint:funlen
|
|
||||||
func (s *SessionSuite) Test_All_Session() {
|
|
||||||
userId := InsertUser(s.db, entity.User{Email: "test_1@aa.ru"})
|
|
||||||
timeNow := time.Now().UTC()
|
|
||||||
|
|
||||||
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,
|
|
||||||
})
|
|
||||||
|
|
||||||
// Дефолт сортировка, лимит и оффсет
|
|
||||||
request := domain.SessionPageRequest{
|
|
||||||
Limit: 5,
|
|
||||||
Offset: 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
var response *domain.SessionResponse
|
|
||||||
err := s.httpCli.
|
|
||||||
Post("admin/session/all").
|
|
||||||
JsonRequestBody(request).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 2)
|
|
||||||
s.Require().EqualValues(3, response.TotalCount)
|
|
||||||
s.Require().EqualValues(2, response.Items[0].Id)
|
|
||||||
s.Require().EqualValues(3, response.Items[1].Id)
|
|
||||||
|
|
||||||
// Дефолт сортировка, поиск по expired_at
|
|
||||||
request.Offset = 0
|
|
||||||
request.Query = &domain.SessionQuery{
|
|
||||||
ExpiredAt: &domain.DateFromToParams{
|
|
||||||
From: timeNow,
|
|
||||||
To: timeNow.Add(24 * time.Hour),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
err = s.httpCli.
|
|
||||||
Post("admin/session/all").
|
|
||||||
JsonRequestBody(request).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 2)
|
|
||||||
s.Require().EqualValues(2, response.TotalCount)
|
|
||||||
s.Require().EqualValues(1, response.Items[0].Id)
|
|
||||||
s.Require().EqualValues(2, response.Items[1].Id)
|
|
||||||
|
|
||||||
// Сортировка по статусу, пустой запрос
|
|
||||||
request.Query = nil
|
|
||||||
request.Order = &domain.OrderParams{
|
|
||||||
Field: "status",
|
|
||||||
Type: "asc",
|
|
||||||
}
|
|
||||||
|
|
||||||
err = s.httpCli.
|
|
||||||
Post("admin/session/all").
|
|
||||||
JsonRequestBody(request).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 3)
|
|
||||||
s.Require().EqualValues(3, response.TotalCount)
|
|
||||||
s.Require().EqualValues(1, response.Items[0].Id)
|
|
||||||
s.Require().EqualValues(3, response.Items[1].Id)
|
|
||||||
s.Require().EqualValues(2, response.Items[2].Id)
|
|
||||||
|
|
||||||
// Сортировка по статусу, поиск по userId & status
|
|
||||||
resUserId := int(userId)
|
|
||||||
request.Query = &domain.SessionQuery{
|
|
||||||
UserId: []int{resUserId},
|
|
||||||
Status: []string{entity.TokenStatusExpired},
|
|
||||||
}
|
|
||||||
|
|
||||||
err = s.httpCli.
|
|
||||||
Post("admin/session/all").
|
|
||||||
JsonRequestBody(request).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 1)
|
|
||||||
s.Require().EqualValues(1, response.TotalCount)
|
|
||||||
s.Require().EqualValues(3, response.Items[0].Id)
|
|
||||||
|
|
||||||
// Сортировка по id, поиск по id
|
|
||||||
for i := range 20 {
|
|
||||||
userId = InsertUser(s.db, entity.User{Email: "test_11" + strconv.Itoa(i) + "@aa.ru"})
|
|
||||||
InsertTokenEntity(s.db, entity.Token{
|
|
||||||
Token: "test_token_1" + strconv.Itoa(i),
|
|
||||||
UserId: userId,
|
|
||||||
Status: entity.TokenStatusAllowed,
|
|
||||||
ExpiredAt: timeNow.Add(1 * time.Hour),
|
|
||||||
CreatedAt: timeNow,
|
|
||||||
UpdatedAt: timeNow,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
request = domain.SessionPageRequest{
|
|
||||||
Limit: 5,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "id",
|
|
||||||
Type: "desc",
|
|
||||||
},
|
|
||||||
Query: &domain.SessionQuery{
|
|
||||||
Id: new(2),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
err = s.httpCli.
|
|
||||||
Post("admin/session/all").
|
|
||||||
JsonRequestBody(request).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 5)
|
|
||||||
s.Require().EqualValues(6, response.TotalCount)
|
|
||||||
s.Require().EqualValues(23, response.Items[0].Id)
|
|
||||||
s.Require().EqualValues(22, response.Items[1].Id)
|
|
||||||
s.Require().EqualValues(21, response.Items[2].Id)
|
|
||||||
s.Require().EqualValues(20, response.Items[3].Id)
|
|
||||||
s.Require().EqualValues(12, response.Items[4].Id)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SessionSuite) Test_Session_Expired_Worker() {
|
|
||||||
userId := InsertUser(s.db, entity.User{Email: "a@test"})
|
|
||||||
|
|
||||||
InsertTokenEntity(s.db, entity.Token{
|
|
||||||
Token: "token_allowed",
|
|
||||||
UserId: userId,
|
|
||||||
Status: entity.TokenStatusAllowed,
|
|
||||||
ExpiredAt: time.Now().UTC().Add(24 * time.Hour)})
|
|
||||||
|
|
||||||
InsertTokenEntity(s.db, entity.Token{
|
|
||||||
Token: "token_expired",
|
|
||||||
UserId: userId,
|
|
||||||
Status: entity.TokenStatusAllowed,
|
|
||||||
ExpiredAt: time.Now().UTC().Add(-2 * time.Hour)})
|
|
||||||
|
|
||||||
InsertTokenEntity(s.db, entity.Token{
|
|
||||||
Token: "token_expired2",
|
|
||||||
UserId: userId,
|
|
||||||
Status: entity.TokenStatusAllowed,
|
|
||||||
ExpiredAt: time.Now().UTC().Add(-24 * time.Hour)})
|
|
||||||
|
|
||||||
bgjobCli := bgjobx.NewClient(s.db, s.test.Logger())
|
|
||||||
|
|
||||||
err := session_worker.EnqueueSeedJob(s.T().Context(), bgjobCli)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
err = bgjobCli.Upgrade(s.T().Context(), s.config.BgJobCfg)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
time.Sleep(2 * time.Second)
|
|
||||||
|
|
||||||
tokens := make([]entity.Token, 0)
|
|
||||||
s.db.Must().Select(&tokens, "SELECT * FROM tokens ORDER BY status ASC")
|
|
||||||
|
|
||||||
s.Require().EqualValues(entity.TokenStatusAllowed, tokens[0].Status)
|
|
||||||
s.Require().EqualValues(entity.TokenStatusExpired, tokens[1].Status)
|
|
||||||
s.Require().EqualValues(entity.TokenStatusExpired, tokens[2].Status)
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
package tests_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
|
||||||
"github.com/txix-open/isp-kit/test"
|
|
||||||
"github.com/txix-open/isp-kit/test/fake"
|
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UiSettingsSuite struct {
|
|
||||||
suite.Suite
|
|
||||||
|
|
||||||
test *test.Test
|
|
||||||
apiCli *httpcli.Client
|
|
||||||
oauthClientSetting conf.OauthClientConfig
|
|
||||||
baseOauthUrl string
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUiSettingsSuite(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
suite.Run(t, &UiSettingsSuite{
|
|
||||||
baseOauthUrl: "http://127.0.0.1/oauth",
|
|
||||||
oauthClientSetting: conf.OauthClientConfig{
|
|
||||||
ClientName: fake.It[string](),
|
|
||||||
ClientId: fake.It[string](),
|
|
||||||
ClientSecret: fake.It[string](),
|
|
||||||
RedirectURI: "https://127.0.0.1/test/redirected",
|
|
||||||
UiSetting: &conf.UiOauthSetting{
|
|
||||||
LoginEndpoint: "/login?someQueryParam=1&test=true",
|
|
||||||
LogoutEndpoint: "/logout?redirect=url",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *UiSettingsSuite) SetupTest() {
|
|
||||||
s.test, _ = test.New(s.T())
|
|
||||||
remote := conf.Remote{
|
|
||||||
Oauth: &conf.Oauth{
|
|
||||||
Host: s.baseOauthUrl,
|
|
||||||
Clients: []conf.OauthClientConfig{s.oauthClientSetting},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil).
|
|
||||||
Config(s.T().Context(), remote, 0)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
_, s.apiCli = httpt.TestServer(s.test, cfg.Handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *UiSettingsSuite) Test_HappyPath() {
|
|
||||||
var resp domain.UiOauthSetting
|
|
||||||
|
|
||||||
err := s.apiCli.Post("admin/ui_settings/oauth").
|
|
||||||
JsonRequestBody(domain.ClientNameRequest{
|
|
||||||
ClientName: s.oauthClientSetting.ClientName,
|
|
||||||
}).
|
|
||||||
JsonResponseBody(&resp).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
loginURL, err := url.Parse(resp.LoginUrl)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Equal(
|
|
||||||
"http://127.0.0.1/oauth/login",
|
|
||||||
loginURL.Scheme+"://"+loginURL.Host+loginURL.Path,
|
|
||||||
)
|
|
||||||
|
|
||||||
query := loginURL.Query()
|
|
||||||
s.Require().Equal(s.oauthClientSetting.ClientId, query.Get("client_id"))
|
|
||||||
s.Require().Equal(s.oauthClientSetting.RedirectURI, query.Get("redirect_uri"))
|
|
||||||
s.Require().Equal("1", query.Get("someQueryParam"))
|
|
||||||
s.Require().Equal("true", query.Get("test"))
|
|
||||||
|
|
||||||
logoutURL, err := url.Parse(resp.LogoutUrl)
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Equal(
|
|
||||||
"http://127.0.0.1/oauth/logout",
|
|
||||||
logoutURL.Scheme+"://"+logoutURL.Host+logoutURL.Path,
|
|
||||||
)
|
|
||||||
s.Require().Equal("url", logoutURL.Query().Get("redirect"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *UiSettingsSuite) Test_UnknownClient() {
|
|
||||||
err := s.apiCli.Post("admin/ui_settings/oauth").
|
|
||||||
JsonRequestBody(domain.ClientNameRequest{
|
|
||||||
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
|
|
||||||
}).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
|
||||||
|
|
||||||
var httpErr httpcli.ErrorResponse
|
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
|
||||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
|
||||||
}
|
|
||||||
+92
-345
@@ -2,28 +2,28 @@ package tests_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
"net/http"
|
"golang.org/x/crypto/bcrypt"
|
||||||
"strconv"
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
|
||||||
"isp-admin-service/conf"
|
|
||||||
"isp-admin-service/domain"
|
|
||||||
"isp-admin-service/entity"
|
|
||||||
"isp-admin-service/repository"
|
|
||||||
"isp-admin-service/service"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/stretchr/testify/suite"
|
"github.com/stretchr/testify/suite"
|
||||||
"github.com/txix-open/isp-kit/dbx"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
"github.com/txix-open/isp-kit/http/httpcli"
|
"github.com/txix-open/isp-kit/http/httpcli"
|
||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
"msp-admin-service/assembly"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/domain"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
"msp-admin-service/repository"
|
||||||
|
"msp-admin-service/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
type tokenService interface {
|
type tokenService interface {
|
||||||
@@ -37,10 +37,9 @@ func TestUserTestSuite(t *testing.T) {
|
|||||||
|
|
||||||
type UserTestSuite struct {
|
type UserTestSuite struct {
|
||||||
suite.Suite
|
suite.Suite
|
||||||
|
|
||||||
test *test.Test
|
test *test.Test
|
||||||
db *dbt.TestDb
|
db *dbt.TestDb
|
||||||
apiCli *httpcli.Client
|
grpcCli *client.Client
|
||||||
httpCli *httpcli.Client
|
httpCli *httpcli.Client
|
||||||
tokenService tokenService
|
tokenService tokenService
|
||||||
}
|
}
|
||||||
@@ -54,15 +53,14 @@ func (s *UserTestSuite) SetupTest() {
|
|||||||
remote := conf.Remote{
|
remote := conf.Remote{
|
||||||
ExpireSec: 0,
|
ExpireSec: 0,
|
||||||
}
|
}
|
||||||
cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
|
cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
|
||||||
Config(s.T().Context(), remote, time.Minute)
|
Config(context.Background(), emptyLdap, remote, time.Minute)
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
|
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||||
s.apiCli = apiCli
|
s.grpcCli = apiCli
|
||||||
|
|
||||||
testInstance.T().Cleanup(func() {
|
testInstance.T().Cleanup(func() {
|
||||||
server.Close()
|
server.Shutdown()
|
||||||
})
|
})
|
||||||
|
|
||||||
tokenRep := repository.NewToken(s.db)
|
tokenRep := repository.NewToken(s.db)
|
||||||
@@ -73,7 +71,6 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
|
|||||||
id := InsertUser(s.db, entity.User{
|
id := InsertUser(s.db, entity.User{
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
FullName: "surname name",
|
|
||||||
Email: "a@a.ru",
|
Email: "a@a.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
})
|
})
|
||||||
@@ -88,19 +85,17 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
response := domain.AdminUserShort{}
|
response := domain.AdminUserShort{}
|
||||||
err := s.apiCli.Post("admin/user/get_profile").
|
err := s.grpcCli.Invoke("admin/user/get_profile").
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
expected := domain.AdminUserShort{
|
expected := domain.AdminUserShort{
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
FullName: "surname name",
|
|
||||||
Email: "a@a.ru",
|
Email: "a@a.ru",
|
||||||
Role: "admin",
|
Role: "admin",
|
||||||
Roles: []int{1},
|
Roles: []int{1},
|
||||||
RoleNames: []string{"admin"},
|
|
||||||
Permissions: []string{},
|
Permissions: []string{},
|
||||||
}
|
}
|
||||||
s.Require().Equal(expected, response)
|
s.Require().Equal(expected, response)
|
||||||
@@ -110,27 +105,24 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
|
|||||||
id := InsertUser(s.db, entity.User{
|
id := InsertUser(s.db, entity.User{
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
FullName: "surname name",
|
|
||||||
Email: "a@b.ru",
|
Email: "a@b.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
})
|
})
|
||||||
|
|
||||||
err := s.apiCli.Post("admin/user/get_profile").
|
err := s.grpcCli.Invoke("admin/user/get_profile").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
var httpErr httpcli.ErrorResponse
|
st, ok := status.FromError(err)
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
s.Require().True(ok)
|
||||||
s.Require().Equal(http.StatusNotFound, httpErr.StatusCode)
|
s.Require().Equal(codes.NotFound, st.Code())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestGetProfileOauth() {
|
func (s *UserTestSuite) TestGetProfileSudir() {
|
||||||
id := InsertOauthUser(s.db, entity.OauthUser{
|
id := InsertSudirUser(s.db, entity.SudirUser{
|
||||||
OauthUserId: "oauthUser1",
|
SudirUserId: "sudirUser1",
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
FullName: "surname name",
|
|
||||||
Email: "a@b.ru",
|
Email: "a@b.ru",
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -144,20 +136,18 @@ func (s *UserTestSuite) TestGetProfileOauth() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
response := domain.AdminUserShort{}
|
response := domain.AdminUserShort{}
|
||||||
err := s.apiCli.
|
err := s.grpcCli.
|
||||||
Post("admin/user/get_profile").
|
Invoke("admin/user/get_profile").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
expected := domain.AdminUserShort{
|
expected := domain.AdminUserShort{
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
FullName: "surname name",
|
|
||||||
Email: "a@b.ru",
|
Email: "a@b.ru",
|
||||||
Role: "admin",
|
Role: "admin",
|
||||||
Roles: []int{1},
|
Roles: []int{1},
|
||||||
RoleNames: []string{"admin"},
|
|
||||||
Permissions: []string{},
|
Permissions: []string{},
|
||||||
}
|
}
|
||||||
s.Require().Equal(expected, response)
|
s.Require().Equal(expected, response)
|
||||||
@@ -166,189 +156,23 @@ func (s *UserTestSuite) TestGetProfileOauth() {
|
|||||||
func (s *UserTestSuite) TestGetUsers() {
|
func (s *UserTestSuite) TestGetUsers() {
|
||||||
InsertUser(s.db, entity.User{Email: "a1@a.ru"})
|
InsertUser(s.db, entity.User{Email: "a1@a.ru"})
|
||||||
InsertUser(s.db, entity.User{Email: "b1@a.ru"})
|
InsertUser(s.db, entity.User{Email: "b1@a.ru"})
|
||||||
userId1 := InsertUser(s.db, entity.User{Email: "a1@b.ru"})
|
InsertUser(s.db, entity.User{Email: "a1@b.ru"})
|
||||||
userId2 := InsertUser(s.db, entity.User{Email: "a1@c.ru"})
|
InsertUser(s.db, entity.User{Email: "a1@c.ru"})
|
||||||
userId3 := InsertUser(s.db, entity.User{Email: "a1@d.ru"})
|
|
||||||
|
|
||||||
roleId1 := InsertRole(s.db, entity.Role{Name: "test_role_1"})
|
|
||||||
roleId2 := InsertRole(s.db, entity.Role{Name: "test_role_2"})
|
|
||||||
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId1), UserId: int(userId1)})
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId1), UserId: int(userId2)})
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId1), UserId: int(userId3)})
|
|
||||||
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId1)})
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
|
|
||||||
|
|
||||||
email := "a1@"
|
|
||||||
|
|
||||||
response := domain.UsersResponse{}
|
response := domain.UsersResponse{}
|
||||||
err := s.apiCli.Post("admin/user/get_users").
|
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
JsonRequestBody(domain.UsersRequest{
|
||||||
Limit: 5,
|
Ids: []int64{3, 4, 5, 6},
|
||||||
Offset: 1,
|
Offset: 1,
|
||||||
Order: &domain.OrderParams{
|
Limit: 1,
|
||||||
Field: "email",
|
Email: "a1@",
|
||||||
Type: "asc",
|
|
||||||
},
|
|
||||||
Query: &domain.UserQuery{
|
|
||||||
Email: &email,
|
|
||||||
Roles: []int{int(roleId2)},
|
|
||||||
},
|
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
roles := []int{int(roleId1), int(roleId2)}
|
s.Require().Len(response.Items, 1) //nolint:mnd
|
||||||
|
s.Require().Equal(int64(5), response.Items[0].Id)
|
||||||
s.Require().Len(response.Items, 2)
|
|
||||||
s.Require().EqualValues("a1@b.ru", response.Items[0].Email)
|
|
||||||
s.Require().EqualValues(roles, response.Items[0].Roles)
|
|
||||||
s.Require().EqualValues("a1@c.ru", response.Items[1].Email)
|
|
||||||
s.Require().EqualValues(roles, response.Items[1].Roles)
|
|
||||||
|
|
||||||
email = "test@mail.ru"
|
|
||||||
err = s.apiCli.Post("admin/user/get_users").
|
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
|
||||||
Limit: 10,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "id",
|
|
||||||
Type: "asc",
|
|
||||||
},
|
|
||||||
Query: &domain.UserQuery{
|
|
||||||
Id: new(int(userId2)),
|
|
||||||
Email: &email,
|
|
||||||
},
|
|
||||||
}).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
s.Require().Empty(response.Items)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *UserTestSuite) TestAllGetUsers() {
|
|
||||||
InsertUser(s.db, entity.User{Email: "a1@a.ru"})
|
|
||||||
InsertUser(s.db, entity.User{Email: "b1@a.ru"})
|
|
||||||
userId1 := InsertUser(s.db, entity.User{Email: "a1@b.ru"})
|
|
||||||
userId2 := InsertUser(s.db, entity.User{Email: "a1@c.ru"})
|
|
||||||
userId3 := InsertUser(s.db, entity.User{Email: "a1@d.ru"})
|
|
||||||
|
|
||||||
roleId1 := InsertRole(s.db, entity.Role{Name: "test_role_1"})
|
|
||||||
roleId2 := InsertRole(s.db, entity.Role{Name: "test_role_2"})
|
|
||||||
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId1), UserId: int(userId1)})
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId1), UserId: int(userId2)})
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId1), UserId: int(userId3)})
|
|
||||||
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId1)})
|
|
||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
|
|
||||||
|
|
||||||
response := domain.UsersResponse{}
|
|
||||||
err := s.apiCli.Post("admin/user/get_all_users").
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 7)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
|
||||||
userId1 := InsertUser(s.db, entity.User{Email: "test1@a.ru"})
|
|
||||||
userId2 := InsertUser(s.db, entity.User{Email: "test2@a.ru"})
|
|
||||||
userId3 := InsertUser(s.db, entity.User{Email: "test3@a.ru"})
|
|
||||||
|
|
||||||
userTime1, err := time.Parse("2006-01-02T15:04:05Z", "2018-01-01T00:00:00Z")
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
userTime2, err := time.Parse("2006-01-02T15:04:05Z", "2020-01-01T00:00:00Z")
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
InsertTokenEntity(s.db, entity.Token{
|
|
||||||
Token: "test_token1",
|
|
||||||
UserId: userId1,
|
|
||||||
Status: entity.TokenStatusAllowed,
|
|
||||||
ExpiredAt: userTime1.Add(1 * time.Hour),
|
|
||||||
CreatedAt: userTime1,
|
|
||||||
UpdatedAt: userTime1,
|
|
||||||
})
|
|
||||||
|
|
||||||
InsertTokenEntity(s.db, entity.Token{
|
|
||||||
Token: "test_token2",
|
|
||||||
UserId: userId2,
|
|
||||||
Status: entity.TokenStatusAllowed,
|
|
||||||
ExpiredAt: userTime1.Add(25 * time.Hour),
|
|
||||||
CreatedAt: userTime1.Add(24 * time.Hour),
|
|
||||||
UpdatedAt: userTime1.Add(24 * time.Hour),
|
|
||||||
})
|
|
||||||
|
|
||||||
InsertTokenEntity(s.db, entity.Token{
|
|
||||||
Token: "test_token3",
|
|
||||||
UserId: userId3,
|
|
||||||
Status: entity.TokenStatusAllowed,
|
|
||||||
ExpiredAt: userTime2.Add(1 * time.Hour),
|
|
||||||
CreatedAt: userTime2,
|
|
||||||
UpdatedAt: userTime2,
|
|
||||||
})
|
|
||||||
|
|
||||||
response := domain.UsersResponse{}
|
|
||||||
err = s.apiCli.Post("admin/user/get_users").
|
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
|
||||||
Limit: 5,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "lastSessionCreatedAt",
|
|
||||||
Type: "desc",
|
|
||||||
},
|
|
||||||
Query: &domain.UserQuery{
|
|
||||||
LastSessionCreatedAt: &domain.DateFromToParams{
|
|
||||||
From: userTime1.Add(-48 * time.Hour),
|
|
||||||
To: userTime1.Add(48 * time.Hour),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 2)
|
|
||||||
s.Require().EqualValues(userId2, response.Items[0].Id)
|
|
||||||
s.Require().EqualValues(userId1, response.Items[1].Id)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *UserTestSuite) TestGetUsersSortByName() {
|
|
||||||
userIdViser1 := InsertUser(s.db, entity.User{Email: "a1@a.ru",
|
|
||||||
FirstName: "admin_viser", LastName: "admin_viser", FullName: "admin_viser admin_viser"})
|
|
||||||
userIdViser2 := InsertUser(s.db, entity.User{Email: "a1@b.ru",
|
|
||||||
FirstName: "admin_viser", LastName: "admin_viser2", FullName: "admin_viser2 admin_viser"})
|
|
||||||
userIdScripts := InsertUser(s.db, entity.User{Email: "a1@c.ru",
|
|
||||||
FirstName: "admin_scripts", LastName: "admin_scripts", FullName: "admin_scripts admin_scripts"})
|
|
||||||
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
|
|
||||||
|
|
||||||
response := domain.UsersResponse{}
|
|
||||||
err := s.apiCli.Post("admin/user/get_users").
|
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
|
||||||
Limit: 10,
|
|
||||||
Offset: 0,
|
|
||||||
Order: &domain.OrderParams{
|
|
||||||
Field: "userId",
|
|
||||||
Type: "asc",
|
|
||||||
},
|
|
||||||
Query: &domain.UserQuery{
|
|
||||||
UserId: []int{int(userIdViser1), int(userIdViser2), int(userIdScripts), int(userIdAL)},
|
|
||||||
},
|
|
||||||
}).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
s.Require().Len(response.Items, 4)
|
|
||||||
s.Require().EqualValues(userIdScripts, response.Items[0].Id)
|
|
||||||
s.Require().EqualValues(userIdViser1, response.Items[1].Id)
|
|
||||||
s.Require().EqualValues(userIdViser2, response.Items[2].Id)
|
|
||||||
s.Require().EqualValues(userIdAL, response.Items[3].Id)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestCreateUserHappyPath() {
|
func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||||
@@ -358,9 +182,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
|||||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||||
|
|
||||||
response := entity.User{}
|
response := entity.User{}
|
||||||
err := s.apiCli.
|
err := s.grpcCli.
|
||||||
Post("admin/user/create_user").
|
Invoke("admin/user/create_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||||
JsonRequestBody(domain.CreateUserRequest{
|
JsonRequestBody(domain.CreateUserRequest{
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
@@ -368,63 +192,32 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
|||||||
Password: "password",
|
Password: "password",
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
postCount := 0
|
postCount := 0
|
||||||
s.db.Must().SelectRow(&postCount, "select count(*) from users")
|
s.db.Must().SelectRow(&postCount, "select count(*) from users")
|
||||||
|
|
||||||
s.Require().Equal(preCount+1, postCount)
|
s.Require().Equal(preCount+1, postCount)
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
|
||||||
firstOauthId := "user_a"
|
|
||||||
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a2@a.ru"})
|
|
||||||
|
|
||||||
preCount := 0
|
|
||||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
|
||||||
|
|
||||||
response := entity.User{}
|
|
||||||
err := s.apiCli.
|
|
||||||
Post("admin/user/create_user").
|
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
|
||||||
JsonRequestBody(domain.CreateUserRequest{
|
|
||||||
FirstName: "name",
|
|
||||||
LastName: "surname",
|
|
||||||
Email: "a2@a.ru",
|
|
||||||
Password: "password",
|
|
||||||
}).
|
|
||||||
JsonResponseBody(&response).
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().NoError(err)
|
|
||||||
|
|
||||||
postCount := 0
|
|
||||||
s.db.Must().SelectRow(&postCount, "select count(*) from users")
|
|
||||||
|
|
||||||
s.Require().Equal(preCount+1, postCount)
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||||
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
||||||
|
|
||||||
err := s.apiCli.
|
err := s.grpcCli.
|
||||||
Post("admin/user/create_user").
|
Invoke("admin/user/create_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
JsonRequestBody(domain.CreateUserRequest{
|
JsonRequestBody(domain.CreateUserRequest{
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
Email: "exists@a.ru",
|
Email: "exists@a.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
}).
|
}).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
st, ok := status.FromError(err)
|
||||||
var httpErr httpcli.ErrorResponse
|
s.Require().True(ok)
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||||
@@ -436,11 +229,12 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
|||||||
Email: "update@a.ru",
|
Email: "update@a.ru",
|
||||||
}
|
}
|
||||||
response := domain.User{}
|
response := domain.User{}
|
||||||
err := s.httpCli.Post("admin/user/update_user").
|
err := s.grpcCli.
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
Invoke("admin/user/update_user").
|
||||||
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
expected := domain.UpdateUserRequest{
|
expected := domain.UpdateUserRequest{
|
||||||
Id: response.Id,
|
Id: response.Id,
|
||||||
@@ -449,24 +243,23 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
|||||||
Email: response.Email,
|
Email: response.Email,
|
||||||
}
|
}
|
||||||
s.Require().Equal(expected, req)
|
s.Require().Equal(expected, req)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
|
func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
|
||||||
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: "123", Email: "oauth@a.ru", FullName: "surname name patronymic"})
|
id := InsertSudirUser(s.db, entity.SudirUser{Email: "sudir@a.ru"})
|
||||||
req := domain.UpdateUserRequest{
|
req := domain.UpdateUserRequest{
|
||||||
Id: id,
|
Id: id,
|
||||||
FirstName: "nameUpd",
|
FirstName: "name",
|
||||||
LastName: "surnameUpd",
|
LastName: "surname",
|
||||||
Email: "oauth@a.ru",
|
Email: "sudir@a.ru",
|
||||||
}
|
}
|
||||||
response := domain.User{}
|
response := domain.User{}
|
||||||
err := s.httpCli.Post("admin/user/update_user").
|
err := s.grpcCli.
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
Invoke("admin/user/update_user").
|
||||||
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
expected := domain.UpdateUserRequest{
|
expected := domain.UpdateUserRequest{
|
||||||
Id: response.Id,
|
Id: response.Id,
|
||||||
@@ -475,9 +268,6 @@ func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
|
|||||||
Email: response.Email,
|
Email: response.Email,
|
||||||
}
|
}
|
||||||
s.Require().Equal(expected, req)
|
s.Require().Equal(expected, req)
|
||||||
s.Require().Equal("surnameUpd nameUpd", response.FullName)
|
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||||
@@ -489,40 +279,15 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
|||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
Email: "a_exists@a.ru",
|
Email: "a_exists@a.ru",
|
||||||
}
|
}
|
||||||
err := s.httpCli.Post("admin/user/update_user").
|
err := s.grpcCli.
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
Invoke("admin/user/update_user").
|
||||||
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
st, ok := status.FromError(err)
|
||||||
var httpErr httpcli.ErrorResponse
|
s.Require().True(ok)
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
|
||||||
firstOauthId := "user_a"
|
|
||||||
secondOauthId := "user_b"
|
|
||||||
|
|
||||||
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a_exists@a.ru"})
|
|
||||||
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: secondOauthId, Email: "b_exists@b.ru"})
|
|
||||||
req := domain.UpdateUserRequest{
|
|
||||||
Id: id,
|
|
||||||
FirstName: "name",
|
|
||||||
LastName: "surname",
|
|
||||||
Email: "a_exists@a.ru",
|
|
||||||
}
|
|
||||||
err := s.httpCli.Post("admin/user/update_user").
|
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
|
||||||
JsonRequestBody(req).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
|
||||||
|
|
||||||
var httpErr httpcli.ErrorResponse
|
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
|
||||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestDeleteUsers() {
|
func (s *UserTestSuite) TestDeleteUsers() {
|
||||||
@@ -532,17 +297,15 @@ func (s *UserTestSuite) TestDeleteUsers() {
|
|||||||
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
||||||
|
|
||||||
response := domain.DeleteResponse{}
|
response := domain.DeleteResponse{}
|
||||||
err := s.apiCli.
|
err := s.grpcCli.
|
||||||
Post("admin/user/delete_user").
|
Invoke("admin/user/delete_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||||
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
|
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
s.Require().Equal(2, response.Deleted)
|
s.Require().Equal(2, response.Deleted)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestBlockUser() {
|
func (s *UserTestSuite) TestBlockUser() {
|
||||||
@@ -563,22 +326,19 @@ func (s *UserTestSuite) TestBlockUser() {
|
|||||||
UpdatedAt: time.Now(),
|
UpdatedAt: time.Now(),
|
||||||
})
|
})
|
||||||
|
|
||||||
err := s.apiCli.Post("admin/user/block_user").
|
err := s.grpcCli.Invoke("admin/user/block_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
StatusCodeToError().
|
|
||||||
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
|
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
|
||||||
DoWithoutResponse(s.T().Context())
|
Do(context.Background())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id)
|
user, err := repository.NewUser(s.db).GetUserById(context.Background(), id)
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
s.Require().True(user.Blocked)
|
s.Require().True(user.Blocked)
|
||||||
|
|
||||||
t, err := repository.NewToken(s.db).Get(s.T().Context(), token)
|
t, err := repository.NewToken(s.db).Get(context.Background(), token)
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
s.EqualValues(entity.TokenStatusRevoked, t.Status)
|
s.EqualValues(entity.TokenStatusRevoked, t.Status)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestChangePasswordUser() {
|
func (s *UserTestSuite) TestChangePasswordUser() {
|
||||||
@@ -595,31 +355,20 @@ func (s *UserTestSuite) TestChangePasswordUser() {
|
|||||||
|
|
||||||
// check for err when invalid data
|
// check for err when invalid data
|
||||||
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
|
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
|
||||||
err := s.apiCli.Post("admin/user/change_password").
|
err := s.grpcCli.Invoke("admin/user/change_password").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||||
JsonRequestBody(invalidReq).
|
JsonRequestBody(invalidReq).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
err = apierrors.FromError(err)
|
||||||
var httpErr httpcli.ErrorResponse
|
s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword))
|
||||||
s.Require().ErrorAs(err, &httpErr)
|
|
||||||
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
|
||||||
|
|
||||||
var body struct {
|
|
||||||
ErrorCode int `json:"errorCode"`
|
|
||||||
ErrorMessage string `json:"errorMessage"`
|
|
||||||
}
|
|
||||||
s.Require().NoError(json.Unmarshal(httpErr.Body, &body))
|
|
||||||
s.Require().Equal(domain.ErrCodeInvalidPassword, body.ErrorCode)
|
|
||||||
|
|
||||||
// change password
|
// change password
|
||||||
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
|
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
|
||||||
err = s.apiCli.Post("admin/user/change_password").
|
err = s.grpcCli.Invoke("admin/user/change_password").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||||
JsonRequestBody(changePswReq).
|
JsonRequestBody(changePswReq).
|
||||||
StatusCodeToError().
|
Do(context.Background())
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
|
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
@@ -631,6 +380,4 @@ func (s *UserTestSuite) TestChangePasswordUser() {
|
|||||||
|
|
||||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
|
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
|
||||||
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
|
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
|
||||||
}
|
}
|
||||||
+2
-15
@@ -3,11 +3,9 @@ package transaction
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-admin-service/repository"
|
|
||||||
"isp-admin-service/service"
|
|
||||||
"isp-admin-service/service/session_worker"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/db"
|
"github.com/txix-open/isp-kit/db"
|
||||||
|
"msp-admin-service/repository"
|
||||||
|
"msp-admin-service/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Manager struct {
|
type Manager struct {
|
||||||
@@ -27,10 +25,6 @@ type userTx struct {
|
|||||||
repository.Token
|
repository.Token
|
||||||
}
|
}
|
||||||
|
|
||||||
type tokenTx struct {
|
|
||||||
repository.Token
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m Manager) UserTransaction(ctx context.Context, msgTx func(ctx context.Context, tx service.UserTransaction) error) error {
|
func (m Manager) UserTransaction(ctx context.Context, msgTx func(ctx context.Context, tx service.UserTransaction) error) error {
|
||||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||||
user := repository.NewUser(tx)
|
user := repository.NewUser(tx)
|
||||||
@@ -50,10 +44,3 @@ func (m Manager) AuthTransaction(ctx context.Context, msgTx func(ctx context.Con
|
|||||||
return msgTx(ctx, userTx{user, role, userRole, token})
|
return msgTx(ctx, userTx{user, role, userRole, token})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Manager) TokenTransaction(ctx context.Context, msgTx func(ctx context.Context, tx session_worker.TokenTransaction) error) error {
|
|
||||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
|
||||||
token := repository.NewToken(tx)
|
|
||||||
return msgTx(ctx, tokenTx{token})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
squirrel.test
|
|
||||||
-30
@@ -1,30 +0,0 @@
|
|||||||
language: go
|
|
||||||
|
|
||||||
go:
|
|
||||||
- 1.11.x
|
|
||||||
- 1.12.x
|
|
||||||
- 1.13.x
|
|
||||||
|
|
||||||
services:
|
|
||||||
- mysql
|
|
||||||
- postgresql
|
|
||||||
|
|
||||||
# Setting sudo access to false will let Travis CI use containers rather than
|
|
||||||
# VMs to run the tests. For more details see:
|
|
||||||
# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/
|
|
||||||
# - http://docs.travis-ci.com/user/workers/standard-infrastructure/
|
|
||||||
sudo: false
|
|
||||||
|
|
||||||
before_script:
|
|
||||||
- mysql -e 'CREATE DATABASE squirrel;'
|
|
||||||
- psql -c 'CREATE DATABASE squirrel;' -U postgres
|
|
||||||
|
|
||||||
script:
|
|
||||||
- go test
|
|
||||||
- cd integration
|
|
||||||
- go test -args -driver sqlite3
|
|
||||||
- go test -args -driver mysql -dataSource travis@/squirrel
|
|
||||||
- go test -args -driver postgres -dataSource 'postgres://postgres@localhost/squirrel?sslmode=disable'
|
|
||||||
|
|
||||||
notifications:
|
|
||||||
irc: "irc.freenode.net#masterminds"
|
|
||||||
-23
@@ -1,23 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Squirrel: The Masterminds
|
|
||||||
Copyright (c) 2014-2015, Lann Martin. Copyright (C) 2015-2016, Google. Copyright (C) 2015, Matt Farina and Matt Butcher.
|
|
||||||
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
-142
@@ -1,142 +0,0 @@
|
|||||||
[](https://masterminds.github.io/stability/maintenance.html)
|
|
||||||
### Squirrel is "complete".
|
|
||||||
Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here.
|
|
||||||
|
|
||||||
|
|
||||||
# Squirrel - fluent SQL generator for Go
|
|
||||||
|
|
||||||
```go
|
|
||||||
import "github.com/Masterminds/squirrel"
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
[](https://godoc.org/github.com/Masterminds/squirrel)
|
|
||||||
[](https://travis-ci.org/Masterminds/squirrel)
|
|
||||||
|
|
||||||
**Squirrel is not an ORM.** For an application of Squirrel, check out
|
|
||||||
[structable, a table-struct mapper](https://github.com/Masterminds/structable)
|
|
||||||
|
|
||||||
|
|
||||||
Squirrel helps you build SQL queries from composable parts:
|
|
||||||
|
|
||||||
```go
|
|
||||||
import sq "github.com/Masterminds/squirrel"
|
|
||||||
|
|
||||||
users := sq.Select("*").From("users").Join("emails USING (email_id)")
|
|
||||||
|
|
||||||
active := users.Where(sq.Eq{"deleted_at": nil})
|
|
||||||
|
|
||||||
sql, args, err := active.ToSql()
|
|
||||||
|
|
||||||
sql == "SELECT * FROM users JOIN emails USING (email_id) WHERE deleted_at IS NULL"
|
|
||||||
```
|
|
||||||
|
|
||||||
```go
|
|
||||||
sql, args, err := sq.
|
|
||||||
Insert("users").Columns("name", "age").
|
|
||||||
Values("moe", 13).Values("larry", sq.Expr("? + 5", 12)).
|
|
||||||
ToSql()
|
|
||||||
|
|
||||||
sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)"
|
|
||||||
```
|
|
||||||
|
|
||||||
Squirrel can also execute queries directly:
|
|
||||||
|
|
||||||
```go
|
|
||||||
stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}})
|
|
||||||
three_stooges := stooges.Limit(3)
|
|
||||||
rows, err := three_stooges.RunWith(db).Query()
|
|
||||||
|
|
||||||
// Behaves like:
|
|
||||||
rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3",
|
|
||||||
"moe", "larry", "curly", "shemp")
|
|
||||||
```
|
|
||||||
|
|
||||||
Squirrel makes conditional query building a breeze:
|
|
||||||
|
|
||||||
```go
|
|
||||||
if len(q) > 0 {
|
|
||||||
users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%"))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Squirrel wants to make your life easier:
|
|
||||||
|
|
||||||
```go
|
|
||||||
// StmtCache caches Prepared Stmts for you
|
|
||||||
dbCache := sq.NewStmtCache(db)
|
|
||||||
|
|
||||||
// StatementBuilder keeps your syntax neat
|
|
||||||
mydb := sq.StatementBuilder.RunWith(dbCache)
|
|
||||||
select_users := mydb.Select("*").From("users")
|
|
||||||
```
|
|
||||||
|
|
||||||
Squirrel loves PostgreSQL:
|
|
||||||
|
|
||||||
```go
|
|
||||||
psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
|
|
||||||
|
|
||||||
// You use question marks for placeholders...
|
|
||||||
sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql()
|
|
||||||
|
|
||||||
/// ...squirrel replaces them using PlaceholderFormat.
|
|
||||||
sql == "SELECT * FROM elephants WHERE name IN ($1,$2)"
|
|
||||||
|
|
||||||
|
|
||||||
/// You can retrieve id ...
|
|
||||||
query := sq.Insert("nodes").
|
|
||||||
Columns("uuid", "type", "data").
|
|
||||||
Values(node.Uuid, node.Type, node.Data).
|
|
||||||
Suffix("RETURNING \"id\"").
|
|
||||||
RunWith(m.db).
|
|
||||||
PlaceholderFormat(sq.Dollar)
|
|
||||||
|
|
||||||
query.QueryRow().Scan(&node.id)
|
|
||||||
```
|
|
||||||
|
|
||||||
You can escape question marks by inserting two question marks:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SELECT * FROM nodes WHERE meta->'format' ??| array[?,?]
|
|
||||||
```
|
|
||||||
|
|
||||||
will generate with the Dollar Placeholder:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2]
|
|
||||||
```
|
|
||||||
|
|
||||||
## FAQ
|
|
||||||
|
|
||||||
* **How can I build an IN query on composite keys / tuples, e.g. `WHERE (col1, col2) IN ((1,2),(3,4))`? ([#104](https://github.com/Masterminds/squirrel/issues/104))**
|
|
||||||
|
|
||||||
Squirrel does not explicitly support tuples, but you can get the same effect with e.g.:
|
|
||||||
|
|
||||||
```go
|
|
||||||
sq.Or{
|
|
||||||
sq.Eq{"col1": 1, "col2": 2},
|
|
||||||
sq.Eq{"col1": 3, "col2": 4}}
|
|
||||||
```
|
|
||||||
|
|
||||||
```sql
|
|
||||||
WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4)
|
|
||||||
```
|
|
||||||
|
|
||||||
(which should produce the same query plan as the tuple version)
|
|
||||||
|
|
||||||
* **Why doesn't `Eq{"mynumber": []uint8{1,2,3}}` turn into an `IN` query? ([#114](https://github.com/Masterminds/squirrel/issues/114))**
|
|
||||||
|
|
||||||
Values of type `[]byte` are handled specially by `database/sql`. In Go, [`byte` is just an alias of `uint8`](https://golang.org/pkg/builtin/#byte), so there is no way to distinguish `[]uint8` from `[]byte`.
|
|
||||||
|
|
||||||
* **Some features are poorly documented!**
|
|
||||||
|
|
||||||
This isn't a frequent complaints section!
|
|
||||||
|
|
||||||
* **Some features are poorly documented?**
|
|
||||||
|
|
||||||
Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries.
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
Squirrel is released under the
|
|
||||||
[MIT License](http://www.opensource.org/licenses/MIT).
|
|
||||||
-128
@@ -1,128 +0,0 @@
|
|||||||
package squirrel
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/lann/builder"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
builder.Register(CaseBuilder{}, caseData{})
|
|
||||||
}
|
|
||||||
|
|
||||||
// sqlizerBuffer is a helper that allows to write many Sqlizers one by one
|
|
||||||
// without constant checks for errors that may come from Sqlizer
|
|
||||||
type sqlizerBuffer struct {
|
|
||||||
bytes.Buffer
|
|
||||||
args []interface{}
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteSql converts Sqlizer to SQL strings and writes it to buffer
|
|
||||||
func (b *sqlizerBuffer) WriteSql(item Sqlizer) {
|
|
||||||
if b.err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var str string
|
|
||||||
var args []interface{}
|
|
||||||
str, args, b.err = nestedToSql(item)
|
|
||||||
|
|
||||||
if b.err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
b.WriteString(str)
|
|
||||||
b.WriteByte(' ')
|
|
||||||
b.args = append(b.args, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *sqlizerBuffer) ToSql() (string, []interface{}, error) {
|
|
||||||
return b.String(), b.args, b.err
|
|
||||||
}
|
|
||||||
|
|
||||||
// whenPart is a helper structure to describe SQLs "WHEN ... THEN ..." expression
|
|
||||||
type whenPart struct {
|
|
||||||
when Sqlizer
|
|
||||||
then Sqlizer
|
|
||||||
}
|
|
||||||
|
|
||||||
func newWhenPart(when interface{}, then interface{}) whenPart {
|
|
||||||
return whenPart{newPart(when), newPart(then)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// caseData holds all the data required to build a CASE SQL construct
|
|
||||||
type caseData struct {
|
|
||||||
What Sqlizer
|
|
||||||
WhenParts []whenPart
|
|
||||||
Else Sqlizer
|
|
||||||
}
|
|
||||||
|
|
||||||
// ToSql implements Sqlizer
|
|
||||||
func (d *caseData) ToSql() (sqlStr string, args []interface{}, err error) {
|
|
||||||
if len(d.WhenParts) == 0 {
|
|
||||||
err = errors.New("case expression must contain at lease one WHEN clause")
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sql := sqlizerBuffer{}
|
|
||||||
|
|
||||||
sql.WriteString("CASE ")
|
|
||||||
if d.What != nil {
|
|
||||||
sql.WriteSql(d.What)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, p := range d.WhenParts {
|
|
||||||
sql.WriteString("WHEN ")
|
|
||||||
sql.WriteSql(p.when)
|
|
||||||
sql.WriteString("THEN ")
|
|
||||||
sql.WriteSql(p.then)
|
|
||||||
}
|
|
||||||
|
|
||||||
if d.Else != nil {
|
|
||||||
sql.WriteString("ELSE ")
|
|
||||||
sql.WriteSql(d.Else)
|
|
||||||
}
|
|
||||||
|
|
||||||
sql.WriteString("END")
|
|
||||||
|
|
||||||
return sql.ToSql()
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaseBuilder builds SQL CASE construct which could be used as parts of queries.
|
|
||||||
type CaseBuilder builder.Builder
|
|
||||||
|
|
||||||
// ToSql builds the query into a SQL string and bound args.
|
|
||||||
func (b CaseBuilder) ToSql() (string, []interface{}, error) {
|
|
||||||
data := builder.GetStruct(b).(caseData)
|
|
||||||
return data.ToSql()
|
|
||||||
}
|
|
||||||
|
|
||||||
// MustSql builds the query into a SQL string and bound args.
|
|
||||||
// It panics if there are any errors.
|
|
||||||
func (b CaseBuilder) MustSql() (string, []interface{}) {
|
|
||||||
sql, args, err := b.ToSql()
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
return sql, args
|
|
||||||
}
|
|
||||||
|
|
||||||
// what sets optional value for CASE construct "CASE [value] ..."
|
|
||||||
func (b CaseBuilder) what(expr interface{}) CaseBuilder {
|
|
||||||
return builder.Set(b, "What", newPart(expr)).(CaseBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// When adds "WHEN ... THEN ..." part to CASE construct
|
|
||||||
func (b CaseBuilder) When(when interface{}, then interface{}) CaseBuilder {
|
|
||||||
// TODO: performance hint: replace slice of WhenPart with just slice of parts
|
|
||||||
// where even indices of the slice belong to "when"s and odd indices belong to "then"s
|
|
||||||
return builder.Append(b, "WhenParts", newWhenPart(when, then)).(CaseBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// What sets optional "ELSE ..." part for CASE construct
|
|
||||||
func (b CaseBuilder) Else(expr interface{}) CaseBuilder {
|
|
||||||
return builder.Set(b, "Else", newPart(expr)).(CaseBuilder)
|
|
||||||
}
|
|
||||||
-191
@@ -1,191 +0,0 @@
|
|||||||
package squirrel
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"database/sql"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/lann/builder"
|
|
||||||
)
|
|
||||||
|
|
||||||
type deleteData struct {
|
|
||||||
PlaceholderFormat PlaceholderFormat
|
|
||||||
RunWith BaseRunner
|
|
||||||
Prefixes []Sqlizer
|
|
||||||
From string
|
|
||||||
WhereParts []Sqlizer
|
|
||||||
OrderBys []string
|
|
||||||
Limit string
|
|
||||||
Offset string
|
|
||||||
Suffixes []Sqlizer
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *deleteData) Exec() (sql.Result, error) {
|
|
||||||
if d.RunWith == nil {
|
|
||||||
return nil, RunnerNotSet
|
|
||||||
}
|
|
||||||
return ExecWith(d.RunWith, d)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *deleteData) ToSql() (sqlStr string, args []interface{}, err error) {
|
|
||||||
if len(d.From) == 0 {
|
|
||||||
err = fmt.Errorf("delete statements must specify a From table")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sql := &bytes.Buffer{}
|
|
||||||
|
|
||||||
if len(d.Prefixes) > 0 {
|
|
||||||
args, err = appendToSql(d.Prefixes, sql, " ", args)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sql.WriteString(" ")
|
|
||||||
}
|
|
||||||
|
|
||||||
sql.WriteString("DELETE FROM ")
|
|
||||||
sql.WriteString(d.From)
|
|
||||||
|
|
||||||
if len(d.WhereParts) > 0 {
|
|
||||||
sql.WriteString(" WHERE ")
|
|
||||||
args, err = appendToSql(d.WhereParts, sql, " AND ", args)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(d.OrderBys) > 0 {
|
|
||||||
sql.WriteString(" ORDER BY ")
|
|
||||||
sql.WriteString(strings.Join(d.OrderBys, ", "))
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(d.Limit) > 0 {
|
|
||||||
sql.WriteString(" LIMIT ")
|
|
||||||
sql.WriteString(d.Limit)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(d.Offset) > 0 {
|
|
||||||
sql.WriteString(" OFFSET ")
|
|
||||||
sql.WriteString(d.Offset)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(d.Suffixes) > 0 {
|
|
||||||
sql.WriteString(" ")
|
|
||||||
args, err = appendToSql(d.Suffixes, sql, " ", args)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Builder
|
|
||||||
|
|
||||||
// DeleteBuilder builds SQL DELETE statements.
|
|
||||||
type DeleteBuilder builder.Builder
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
builder.Register(DeleteBuilder{}, deleteData{})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Format methods
|
|
||||||
|
|
||||||
// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the
|
|
||||||
// query.
|
|
||||||
func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder {
|
|
||||||
return builder.Set(b, "PlaceholderFormat", f).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Runner methods
|
|
||||||
|
|
||||||
// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec.
|
|
||||||
func (b DeleteBuilder) RunWith(runner BaseRunner) DeleteBuilder {
|
|
||||||
return setRunWith(b, runner).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exec builds and Execs the query with the Runner set by RunWith.
|
|
||||||
func (b DeleteBuilder) Exec() (sql.Result, error) {
|
|
||||||
data := builder.GetStruct(b).(deleteData)
|
|
||||||
return data.Exec()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SQL methods
|
|
||||||
|
|
||||||
// ToSql builds the query into a SQL string and bound args.
|
|
||||||
func (b DeleteBuilder) ToSql() (string, []interface{}, error) {
|
|
||||||
data := builder.GetStruct(b).(deleteData)
|
|
||||||
return data.ToSql()
|
|
||||||
}
|
|
||||||
|
|
||||||
// MustSql builds the query into a SQL string and bound args.
|
|
||||||
// It panics if there are any errors.
|
|
||||||
func (b DeleteBuilder) MustSql() (string, []interface{}) {
|
|
||||||
sql, args, err := b.ToSql()
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
return sql, args
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prefix adds an expression to the beginning of the query
|
|
||||||
func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteBuilder {
|
|
||||||
return b.PrefixExpr(Expr(sql, args...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrefixExpr adds an expression to the very beginning of the query
|
|
||||||
func (b DeleteBuilder) PrefixExpr(expr Sqlizer) DeleteBuilder {
|
|
||||||
return builder.Append(b, "Prefixes", expr).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// From sets the table to be deleted from.
|
|
||||||
func (b DeleteBuilder) From(from string) DeleteBuilder {
|
|
||||||
return builder.Set(b, "From", from).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Where adds WHERE expressions to the query.
|
|
||||||
//
|
|
||||||
// See SelectBuilder.Where for more information.
|
|
||||||
func (b DeleteBuilder) Where(pred interface{}, args ...interface{}) DeleteBuilder {
|
|
||||||
return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// OrderBy adds ORDER BY expressions to the query.
|
|
||||||
func (b DeleteBuilder) OrderBy(orderBys ...string) DeleteBuilder {
|
|
||||||
return builder.Extend(b, "OrderBys", orderBys).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Limit sets a LIMIT clause on the query.
|
|
||||||
func (b DeleteBuilder) Limit(limit uint64) DeleteBuilder {
|
|
||||||
return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Offset sets a OFFSET clause on the query.
|
|
||||||
func (b DeleteBuilder) Offset(offset uint64) DeleteBuilder {
|
|
||||||
return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Suffix adds an expression to the end of the query
|
|
||||||
func (b DeleteBuilder) Suffix(sql string, args ...interface{}) DeleteBuilder {
|
|
||||||
return b.SuffixExpr(Expr(sql, args...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// SuffixExpr adds an expression to the end of the query
|
|
||||||
func (b DeleteBuilder) SuffixExpr(expr Sqlizer) DeleteBuilder {
|
|
||||||
return builder.Append(b, "Suffixes", expr).(DeleteBuilder)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b DeleteBuilder) Query() (*sql.Rows, error) {
|
|
||||||
data := builder.GetStruct(b).(deleteData)
|
|
||||||
return data.Query()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *deleteData) Query() (*sql.Rows, error) {
|
|
||||||
if d.RunWith == nil {
|
|
||||||
return nil, RunnerNotSet
|
|
||||||
}
|
|
||||||
return QueryWith(d.RunWith, d)
|
|
||||||
}
|
|
||||||
Loaded 100 of 2829 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user