Compare commits

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

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
name: Create and publish a Docker image
on:
push:
tags:
- 'v*'
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
APP_NAME: ${{ github.event.repository.name }}
jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
attestations: write
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Get version from tag
id: version_reader
run: |
VERSION=${GITHUB_REF_NAME#v}
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: docker-container
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
id: push
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version_reader.outputs.version }}
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
labels: |
org.opencontainers.image.title=${{ env.IMAGE_NAME }}
org.opencontainers.image.version=${{ steps.version_reader.outputs.version }}
build-args: |
app_name=${{ env.APP_NAME }}
version=${{ steps.version_reader.outputs.version }}
- name: Generate artifact attestation
uses: actions/attest-build-provenance@v2
with:
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true
+2
View File
@@ -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
-9
View File
@@ -20,12 +20,7 @@ linters:
- wsl_v5 # расставление пробелов очень индивидуально - wsl_v5 # расставление пробелов очень индивидуально
- godoclint # ругается на // nolint, не удобно - godoclint # ругается на // nolint, не удобно
- prealloc # слишком аггресивный, в большинстве случаев не требуется - 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:
@@ -65,9 +60,6 @@ linters:
- unqueryvet - unqueryvet
- prealloc - prealloc
path: ".*_test\\.go$" path: ".*_test\\.go$"
- linters:
- goconst
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
paths: paths:
- third_party$ - third_party$
- builtin$ - builtin$
@@ -81,4 +73,3 @@ formatters:
- third_party$ - third_party$
- builtin$ - builtin$
- examples$ - examples$
+1 -1
View File
@@ -1 +1 @@
7.2.0 6.8.2
-18
View File
@@ -1,21 +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.2
* обновлены зависимости * обновлены зависимости
### v6.8.1 ### v6.8.1
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.27-alpine as builder FROM golang:1.26-alpine as builder
WORKDIR /build WORKDIR /build
ARG version ARG version
ENV version_env=$version ENV version_env=$version
+1 -1
View File
@@ -1,5 +1,5 @@
FROM dockerhub.mos.ru/mosos/arbat:15.5 as builder FROM dockerhub.mos.ru/mosos/arbat:15.5 as builder
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.27 git RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.24 git
WORKDIR /build WORKDIR /build
ARG version ARG version
ENV version_env=$version ENV version_env=$version
+1 -1
View File
@@ -1 +1 @@
# isp-admin-service1 # msp-admin-service
+18 -30
View File
@@ -4,48 +4,45 @@ import (
"context" "context"
"time" "time"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/service/delete_old_audit_worker" "msp-admin-service/service/delete_old_audit_worker"
"isp-admin-service/service/inactive_worker" "msp-admin-service/service/inactive_worker"
"isp-admin-service/service/session_worker" "msp-admin-service/service/session_worker"
"github.com/pkg/errors"
"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"
) )
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,8 @@ 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, newCfg, time.Minute)
oauthBaseUrl = newCfg.Oauth.Host
}
a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl
locator := NewLocator(a.logger, a.oauthCli, a.db)
config, err := locator.Config(ctx, newCfg, time.Minute)
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "locator config"))
}
a.server.Upgrade(config.Handler) a.server.Upgrade(config.Handler)
@@ -109,7 +97,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 +115,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 {
+21 -52
View File
@@ -4,24 +4,22 @@ import (
"context" "context"
"time" "time"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/controller" "msp-admin-service/controller"
"isp-admin-service/repository" "msp-admin-service/repository"
"isp-admin-service/routes" "msp-admin-service/routes"
"isp-admin-service/service" "msp-admin-service/service"
"isp-admin-service/service/delete_old_audit_worker" "msp-admin-service/service/delete_old_audit_worker"
"isp-admin-service/service/inactive_worker" "msp-admin-service/service/inactive_worker"
"isp-admin-service/service/secure" "msp-admin-service/service/secure"
"isp-admin-service/service/session_worker" "msp-admin-service/service/session_worker"
"isp-admin-service/transaction" "msp-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"
) )
@@ -32,20 +30,20 @@ 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
} }
@@ -54,8 +52,8 @@ func (l Locator) Config(
ctx context.Context, ctx context.Context,
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,13 +63,7 @@ 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)
@@ -88,7 +80,7 @@ func (l Locator) Config(
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 +88,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 +96,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,8 +108,6 @@ func (l Locator) Config(
Audit: auditController, Audit: auditController,
Role: roleController, Role: roleController,
Permissions: permissionController, Permissions: permissionController,
UiSettings: uiSettingsController,
Download: downloadController,
}, },
) )
@@ -162,13 +139,5 @@ func (l Locator) Config(
PollInterval: jobPollInterval, PollInterval: jobPollInterval,
Handle: expireSessionWorker, Handle: expireSessionWorker,
}}, }},
}, nil
}
func (l Locator) getOauthSettings(oauthAuth *conf.Oauth) (string, []conf.OauthClientConfig) {
if oauthAuth == nil {
return "", []conf.OauthClientConfig{}
} }
return oauthAuth.Host, oauthAuth.Clients
} }
-35
View File
@@ -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
View File
@@ -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
+19 -30
View File
@@ -1,4 +1,3 @@
//nolint:lll
package conf package conf
import ( import (
@@ -11,7 +10,7 @@ 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 = []any{"debug", "info", "error", "fatal"}
@@ -19,12 +18,13 @@ func init() {
} }
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:"Блокировка неактивных УЗ"`
@@ -32,41 +32,30 @@ type Remote struct {
} }
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 +69,6 @@ type BlockInactiveWorker struct {
} }
type Permission struct { type Permission struct {
Key string `schema:"Ключ прав"` Key string
Name string `schema:"Пользовательское название"` Name string
} }
+1 -2
View File
@@ -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) {
+18 -19
View File
@@ -2,12 +2,12 @@ package controller
import ( import (
"context" "context"
"net/http"
"isp-admin-service/domain" "msp-admin-service/domain"
"github.com/txix-open/isp-kit/errors" "github.com/pkg/errors"
"github.com/txix-open/isp-kit/http/apierrors" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
type AuditService interface { type AuditService interface {
@@ -27,16 +27,15 @@ 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.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)" // @Param body body domain.AuditPageRequest true "Тело запроса"
// @Success 200 {object} domain.AuditResponse // @Success 200 {object} domain.AuditResponse
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /log/all [POST] // @Router /log/all [POST]
func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) { func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) {
if req.Order == nil { if req.Order == nil {
@@ -50,38 +49,38 @@ func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.Au
} }
// 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 "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /log/events [POST] // @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 {object} map[string]interface{} "События успешно установлены" // @Success 200
// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @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
} }
+43 -47
View File
@@ -2,20 +2,21 @@ package controller
import ( import (
"context" "context"
"net/http"
"strconv" "strconv"
"isp-admin-service/auth" "msp-admin-service/domain"
"isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors" "github.com/pkg/errors"
"github.com/txix-open/isp-kit/http/apierrors" "github.com/txix-open/isp-kit/grpc"
"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"
) )
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, request *domain.LogoutRequest) error
} }
@@ -32,19 +33,18 @@ 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 {object} map[string]interface{} "Успешный выход" // @Success 200
// @Failure 400 {object} apierrors.Error "Невалидный токен" // @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /auth/logout [POST] // @Router /auth/logout [POST]
func (a Auth) Logout(ctx context.Context, r *http.Request) error { func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return err return err
} }
@@ -58,20 +58,19 @@ func (a Auth) Logout(ctx context.Context, r *http.Request) error {
} }
// LogoutWithReason // LogoutWithReason
//
// @Tags auth // @Tags auth
// @Summary Выход по бездействию из авторизованной сессии // @Summary Выход по бездействию из авторизованной сессии
// @Description Выход по бездействию из авторизованной сессии администрирования // @Description Выход по бездействию из авторизованной сессии администрирования
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.LogoutRequest true "Тело запроса" // @Param body body domain.LogoutRequest true "Тело запроса"
// @Success 200 {object} map[string]interface{} "Успешный выход" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Failure 400 {object} apierrors.Error "Невалидный токен" // @Success 200
// @Failure 500 {object} apierrors.Error // @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 500 {object} domain.GrpcError
// @Router /auth/logout_with_reason [POST] // @Router /auth/logout_with_reason [POST]
func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error { func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return err return err
} }
@@ -85,7 +84,6 @@ func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutR
} }
// Login // Login
//
// @Tags auth // @Tags auth
// @Summary Авторизация по логину и паролю // @Summary Авторизация по логину и паролю
// @Description Авторизация с получением токена администратора // @Description Авторизация с получением токена администратора
@@ -93,22 +91,21 @@ func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutR
// @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} apierrors.Error // @Failure 400 {object} domain.GrpcError
// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны" // @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию" // @Failure 500 {object} domain.GrpcError
// @Failure 500 {object} apierrors.Error
// @Router /auth/login [POST] // @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 +113,42 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
} }
} }
// LoginWithOauth // LoginWithSudir
//
// @Tags auth // @Tags auth
// @Summary Авторизация по авторизационному коду от OAuth // @Summary Авторизация по авторизационному коду от СУДИР
// @Description Авторизация с получением токена администратора. // @Description Авторизация с получением токена администратора
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.LoginOauthRequest true "Тело запроса" // @Param body body domain.LoginSudirRequest true "Тело запроса"
// @Success 200 {object} domain.LoginResponse // @Success 200 {object} domain.LoginResponse
// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере" // @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации"
// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента" // @Failure 412 {object} domain.GrpcError "Авторизация СУДИР не настроена на сервере"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /auth/login_with_oauth [POST] // @Router /auth/login_with_sudir [POST]
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) {
auth, err := a.authService.LoginWithOauth(ctx, request) auth, err := a.authService.LoginWithSudir(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
+7 -12
View File
@@ -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} domain.UIDesign // @Success 200 {object} conf.UIDesign
// @Failure 400 {object} apierrors.Error "Невалидный токен" // @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /user/get_design [POST] // @Router /user/get_design [POST]
func (c Customization) GetUIDesign() (domain.UIDesign, error) { func (c Customization) GetUIDesign() (conf.UIDesign, error) {
return c.uiCfg, nil return c.uiCfg, nil
} }
-102
View File
@@ -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, req domain.RoleAllRequest, 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, req domain.RoleAllRequest, w http.ResponseWriter) error {
err := c.service.DownloadRoles(ctx, req, w)
if err != nil {
return errors.WithMessage(err, "download roles")
}
return nil
}
+3 -5
View File
@@ -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,14 +21,12 @@ 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
// @Failure 500 {object} apierrors.Error
// @Router /user/get_permissions [POST] // @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)
+29 -33
View File
@@ -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,7 +28,6 @@ func NewRole(roleService roleService) Role {
} }
// All // All
//
// @Tags role // @Tags role
// @Summary Список ролей // @Summary Список ролей
// @Description Получить список ролей // @Description Получить список ролей
@@ -36,11 +35,11 @@ func NewRole(roleService roleService) Role {
// @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} apierrors.Error // @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /role/all [POST] // @Router /role/all [POST]
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) { func (u Role) All(ctx context.Context) ([]domain.Role, error) {
users, err := u.roleService.All(ctx, req) users, err := u.roleService.All(ctx)
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.Role // @Success 200 {object} domain.User
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует" // @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /role/create [POST] // @Router /role/create [POST]
func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) { func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
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,7 +78,6 @@ func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *h
} }
// UpdateRole // UpdateRole
//
// @Tags role // @Tags role
// @Summary Обновить роль // @Summary Обновить роль
// @Description Обновить данные существующую роль // @Description Обновить данные существующую роль
@@ -89,12 +86,12 @@ func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *h
// @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} apierrors.Error "Роль с указанным id не существует" // @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует"
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует" // @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /role/update [POST] // @Router /role/update [POST]
func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) { func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
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,7 +110,6 @@ func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *h
} }
// DeleteRole // DeleteRole
//
// @Tags role // @Tags role
// @Summary Удалить роль // @Summary Удалить роль
// @Description Удалить существующую роль // @Description Удалить существующую роль
@@ -122,11 +118,11 @@ func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *h
// @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} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /role/delete [POST] // @Router /role/delete [POST]
func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error { func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return err return err
} }
+5 -8
View File
@@ -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,7 +24,6 @@ func NewSecure(service SecureService) Secure {
} }
// Authenticate // Authenticate
//
// @Tags secure // @Tags secure
// @Summary Метод аутентификации токена // @Summary Метод аутентификации токена
// @Description Проверяет токен и возвращает идентификатор администратора // @Description Проверяет токен и возвращает идентификатор администратора
@@ -33,7 +31,7 @@ func NewSecure(service SecureService) Secure {
// @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} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @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)
@@ -62,7 +60,6 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
} }
// Authorize // Authorize
//
// @Tags secure // @Tags secure
// @Summary Метод авторизации для администратора // @Summary Метод авторизации для администратора
// @Description Проверяет наличие у администратора необходимого разрешения // @Description Проверяет наличие у администратора необходимого разрешения
@@ -70,7 +67,7 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
// @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} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @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)
+5 -7
View File
@@ -3,7 +3,7 @@ package controller
import ( import (
"context" "context"
"isp-admin-service/domain" "msp-admin-service/domain"
) )
type SessionService interface { type SessionService interface {
@@ -22,7 +22,6 @@ func NewSession(service SessionService) Session {
} }
// All // All
//
// @Tags session // @Tags session
// @Summary Получение списка сессий // @Summary Получение списка сессий
// @Accept json // @Accept json
@@ -30,8 +29,8 @@ func NewSession(service SessionService) Session {
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.SessionPageRequest true "Тело запроса" // @Param body body domain.SessionPageRequest true "Тело запроса"
// @Success 200 {object} domain.SessionResponse // @Success 200 {object} domain.SessionResponse
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /session/all [POST] // @Router /session/all [POST]
func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) { func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) {
if req.Order == nil { if req.Order == nil {
@@ -45,7 +44,6 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai
} }
// Revoke // Revoke
//
// @Tags session // @Tags session
// @Summary Отзыв сессии // @Summary Отзыв сессии
// @Accept json // @Accept json
@@ -53,8 +51,8 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai
// @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} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @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)
-49
View File
@@ -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
}
}
+47 -54
View File
@@ -2,13 +2,15 @@ package controller
import ( import (
"context" "context"
"net/http"
"github.com/txix-open/isp-kit/http/apierrors" "github.com/txix-open/isp-kit/grpc/apierrors"
"isp-admin-service/domain" "msp-admin-service/domain"
"github.com/txix-open/isp-kit/errors" "github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
type userService interface { type userService interface {
@@ -34,7 +36,6 @@ func NewUser(userService userService) User {
} }
// GetProfile // GetProfile
//
// @Tags user // @Tags user
// @Summary Получить профиль // @Summary Получить профиль
// @Description Получить данные профиля // @Description Получить данные профиля
@@ -42,12 +43,12 @@ func NewUser(userService userService) User {
// @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 401 {object} apierrors.Error "Невалидный токен" // @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 404 {object} apierrors.Error "Пользователя не существует" // @Failure 404 {object} domain.GrpcError "Пользователя не существует"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /user/get_profile [POST] // @Router /user/get_profile [POST]
func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) { func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -55,9 +56,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,7 +67,6 @@ func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUse
} }
// GetUsers // GetUsers
//
// @Tags user // @Tags user
// @Summary Список пользователей // @Summary Список пользователей
// @Description Получить список пользователей // @Description Получить список пользователей
@@ -75,8 +75,8 @@ func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUse
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.UsersPageRequest true "Тело запроса" // @Param body body domain.UsersPageRequest true "Тело запроса"
// @Success 200 {object} domain.UsersResponse // @Success 200 {object} domain.UsersResponse
// @Failure 400 {object} apierrors.Error // @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /user/get_users [POST] // @Router /user/get_users [POST]
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) { func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) {
if req.Order == nil { if req.Order == nil {
@@ -95,7 +95,6 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
} }
// GetAllUsers // GetAllUsers
//
// @Tags user // @Tags user
// @Summary Список пользователей // @Summary Список пользователей
// @Description Получить список пользователей // @Description Получить список пользователей
@@ -103,8 +102,8 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
// @Produce json // @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.UsersResponse // @Success 200 {object} domain.UsersResponse
// @Failure 400 {object} apierrors.Error // @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /user/get_all_users [POST] // @Router /user/get_all_users [POST]
func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) { func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
users, err := u.userService.GetAllUsers(ctx) users, err := u.userService.GetAllUsers(ctx)
@@ -116,7 +115,6 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
} }
// CreateUser // CreateUser
//
// @Tags user // @Tags user
// @Summary Создать пользователя // @Summary Создать пользователя
// @Description Создать пользователя // @Description Создать пользователя
@@ -125,12 +123,12 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
// @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} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует" // @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /user/create_user [POST] // @Router /user/create_user [POST]
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) { func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -138,7 +136,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,7 +145,6 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *h
} }
// UpdateUser // UpdateUser
//
// @Tags user // @Tags user
// @Summary Обновить пользователя // @Summary Обновить пользователя
// @Description Обновить данные существующего пользователя // @Description Обновить данные существующего пользователя
@@ -156,13 +153,13 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *h
// @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} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует" // @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует"
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует" // @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /user/update_user [POST] // @Router /user/update_user [POST]
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) { func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -170,11 +167,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,7 +180,6 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *h
} }
// DeleteUser // DeleteUser
//
// @Tags user // @Tags user
// @Summary Удалить пользователя // @Summary Удалить пользователя
// @Description Удалить существующего пользователя // @Description Удалить существующего пользователя
@@ -192,11 +188,11 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *h
// @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} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /user/delete_user [POST] // @Router /user/delete_user [POST]
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) { func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -210,7 +206,6 @@ func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesReques
} }
// Block // Block
//
// @Tags user // @Tags user
// @Summary Метод блокировки/разблокировки пользователя // @Summary Метод блокировки/разблокировки пользователя
// @Accept json // @Accept json
@@ -218,11 +213,11 @@ func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesReques
// @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} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @Router /user/block_user [POST] // @Router /user/block_user [POST]
func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error { func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return err return err
} }
@@ -235,22 +230,20 @@ 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} apierrors.Error "Невалидное тело запроса" // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} domain.GrpcError
// @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
@@ -258,11 +251,11 @@ func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain
// @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, req domain.ChangePasswordRequest, r *http.Request) error { func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error {
adminId, err := getAdminId(r) adminId, err := getAdminId(authData)
if err != nil { if err != nil {
return err return err
} }
@@ -270,7 +263,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:
-9
View File
@@ -1,9 +0,0 @@
package docs
import _ "embed"
// Embedded swagger files.
var (
//go:embed swagger.json
SwaggerJson []byte
)
-2401
View File
File diff suppressed because it is too large. Load diff
+1314
View File
File diff suppressed because it is too large. Load diff
+17 -17
View File
@@ -5,38 +5,38 @@ 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 AuditPageRequest struct {
LimitOffsetParams LimitOffestParams
Order *OrderParams // Параметры сортировки Order *OrderParams
Query *AuditQuery // Параметры выборки Query *AuditQuery
} }
type AuditQuery struct { type AuditQuery struct {
Id *int // Фильтр по идентификатору audit Id *int
UserId []int // Фильтр по идентификатору пользователей UserId []int
Message *string // Фильтр по сообщению Message *string
CreatedAt *DateFromToParams // Фильтр по дате 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
View File
@@ -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 {
+7
View File
@@ -0,0 +1,7 @@
package domain
type GrpcError struct {
ErrorMessage string `json:"errorMessage"`
ErrorCode string `json:"errorCode"`
Details []any `json:"details"`
}
+8 -9
View File
@@ -6,22 +6,21 @@ const (
) )
type LogoutRequest struct { type LogoutRequest struct {
Reason string // Причина выхода 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 // 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
} }
+7 -7
View File
@@ -7,17 +7,17 @@ const (
DefaultOrderType = "desc" DefaultOrderType = "desc"
) )
type LimitOffsetParams struct { type LimitOffestParams struct {
Limit uint64 `validate:"required"` // Максимальное количество записей Limit uint64 `validate:"required"`
Offset uint64 // Отступ для выборки Offset uint64
} }
type OrderParams struct { type OrderParams struct {
Field string // Поле сортировки Field string
Type string `validate:"oneof=asc desc ASC DESC"` // Порядок сортировки Type string `validate:"oneof=asc desc ASC DESC"`
} }
type DateFromToParams struct { type DateFromToParams struct {
From time.Time `validate:"required"` // Дата с From time.Time `validate:"required"`
To time.Time `validate:"required"` // Дата до To time.Time `validate:"required"`
} }
+2 -2
View File
@@ -1,6 +1,6 @@
package domain package domain
type Permission struct { type Permission struct {
Key string // Ключ прав Key string
Name string // Пользовательское название Name string
} }
+17 -24
View File
@@ -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
View File
@@ -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
} }
+16 -39
View File
@@ -4,57 +4,34 @@ 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 { type SessionPageRequest struct {
LimitOffsetParams LimitOffestParams
Order *OrderParams // Параметры сортировки Order *OrderParams
Query *SessionQuery // Параметры выборки Query *SessionQuery
} }
type SessionQuery struct { type SessionQuery struct {
Id *int // Фильтр по идентификатору сессии Id *int
UserId []int // Фильтр по идентификаторам пользователей UserId []int
Status []string // Фильтр по статусам Status []string
CreatedAt *DateFromToParams // Фильтр по дате создания CreatedAt *DateFromToParams
ExpiredAt *DateFromToParams // Фильтр по дате протухания ExpiredAt *DateFromToParams
} }
type SessionResponse struct { type SessionResponse struct {
TotalCount int // Количество сессий TotalCount int
Items []Session // Список сессий Items []Session
} }
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 ""
} }
-6
View File
@@ -1,6 +0,0 @@
package domain
type UIDesign struct {
Name string // Название ui
PrimaryColor string `example:"#ff4d4f"` // Цвет в HEX
}
-10
View File
@@ -1,10 +0,0 @@
package domain
type ClientNameRequest struct {
ClientName string `validate:"required"`
}
type UiOauthSetting struct {
LoginUrl string // URL для получения authCode для авторизации через OAuth
LogoutUrl string // URL для завершения сессии
}
+48 -49
View File
@@ -5,84 +5,83 @@ 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 // ФИО 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 UserQuery struct {
Id *int // Фильтр по идентификатору пользователя Id *int
UserId []int // Фильтр по идентификаторам пользователя UserId []int
Description *string // Фильтр по описанию Description *string
Email *string // Фильтр по электроннйо почты Email *string
Roles []int // Фильтр по ролям Roles []int
LastSessionCreatedAt *DateFromToParams // Фильтр по дате создания последней сессии LastSessionCreatedAt *DateFromToParams
} }
type UsersPageRequest struct { type UsersPageRequest struct {
LimitOffsetParams LimitOffestParams
RoleAllRequest
Order *OrderParams // Параметры сортировки Order *OrderParams
Query *UserQuery // Параметры выборки Query *UserQuery
} }
type AdminUserShort struct { type AdminUserShort struct {
FirstName string // Имя FirstName string
LastName string // Фамилия LastName string
FullName string // ФИО FullName string
Email string `validate:"required"` // Электронный адрес Email string `validate:"required"`
Role string // Название роли Role string
Roles []int // Список идентификаторов ролей Roles []int
RoleNames []string // Список названия ролей RoleNames []string
Permissions []string // Список прав Permissions []string
IdleTimeoutMs int // Время бездействия пользователя в мс 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"`
} }
-28
View File
@@ -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{"Действие", "Ключ в системе"}
}
-1
View File
@@ -16,7 +16,6 @@ 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
+6 -13
View File
@@ -4,26 +4,19 @@ import (
"fmt" "fmt"
) )
type ClientSetting struct {
AuthCode string
ClientId string
ClientSecret string
RedirectURI string
}
// nolint:tagliatelle,godoclint // nolint:tagliatelle,godoclint
type OauthAuthError struct { type SudirAuthError 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 // nolint:tagliatelle,errname,godoclint
type OauthUserResponse struct { type SudirUserResponse struct {
*OauthAuthError *SudirAuthError
Email string `json:"email"` Email string `json:"email"`
Groups []string `json:"groups"` Groups []string `json:"groups"`
@@ -34,8 +27,8 @@ type OauthUserResponse struct {
} }
// nolint:tagliatelle,errname,godoclint // nolint:tagliatelle,errname,godoclint
type OauthTokenResponse struct { type SudirTokenResponse struct {
*OauthAuthError *SudirAuthError
IdToken string `json:"id_token"` IdToken string `json:"id_token"`
AccessToken string `json:"access_token"` AccessToken string `json:"access_token"`
+3 -4
View File
@@ -3,9 +3,8 @@ 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
FullName string FullName string
@@ -19,9 +18,9 @@ type User struct {
LastSessionCreatedAt *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
+44 -46
View File
@@ -1,86 +1,84 @@
module isp-admin-service module msp-admin-service
go 1.27 go 1.26
require ( require (
github.com/Masterminds/squirrel v1.5.4 github.com/Masterminds/squirrel v1.5.4
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/iancoleman/strcase v0.3.0 github.com/iancoleman/strcase v0.3.0
github.com/stretchr/testify v1.12.1 github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.11.1
github.com/txix-open/bgjob v1.6.0 github.com/txix-open/bgjob v1.6.0
github.com/txix-open/isp-kit v1.76.0 github.com/txix-open/isp-kit v1.71.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.54.0
golang.org/x/sync v0.25.0 golang.org/x/sync v0.22.0
google.golang.org/grpc v1.82.1
) )
require ( require (
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.2.0 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // 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.15 // indirect
github.com/gabriel-vasile/mimetype v1.4.16 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/getsentry/sentry-go v0.50.0 // indirect github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/go-faker/faker/v4 v4.12.0 // indirect github.com/getsentry/sentry-go v0.47.0 // indirect
github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/logr v1.4.3 // 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.29.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.10.0 // 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.19.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.2 // 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.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/pressly/goose/v3 v3.30.1 // indirect github.com/pressly/goose/v3 v3.27.2 // indirect
github.com/prometheus/client_golang v1.25.0 // indirect github.com/prometheus/client_golang v1.23.2 // 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.69.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect github.com/prometheus/procfs v0.21.1 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect github.com/sethvargo/go-retry v0.3.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.1.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.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.47.0 // indirect go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/sdk v1.47.0 // indirect go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.47.0 // indirect go.opentelemetry.io/proto/otlp v1.10.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.28.0 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect golang.org/x/net v0.57.0 // indirect
golang.org/x/net v0.63.0 // indirect golang.org/x/sys v0.47.0 // indirect
golang.org/x/sys v0.50.0 // indirect golang.org/x/text v0.40.0 // indirect
golang.org/x/text v0.44.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect google.golang.org/protobuf v1.36.11 // 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
) )
+112 -110
View File
@@ -9,8 +9,8 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn
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.2.0 h1:4EFcvK1kD4jyj6YqNK6skK6w+y7FHHBR+XBCtxwu/6g=
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/buger/jsonparser v1.2.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -19,32 +19,36 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
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/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/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g= github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8= github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/getsentry/sentry-go v0.47.0 h1:AnSMSyrYA5qZCIN/2xpgAAwv63sVULV+vBq37ajouc8=
github.com/getsentry/sentry-go v0.47.0/go.mod h1:h+b4VHpKnK7aUXB5wc+KDnPgp9ZtfliRD4eV85FbiSA=
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-faker/faker/v4 v4.9.0 h1:a4HXLwueuTCtgF93VpUsl8Zd2nG1VH2SgNWDPVEBg5U=
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg= github.com/go-faker/faker/v4 v4.9.0/go.mod h1:u1dIRP5neLB6kTzgyVjdBOV5R1uP7BdxkcWk7tiKQXk=
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.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/logr v1.4.3/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.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
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.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
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 +56,26 @@ 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/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU= github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
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.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
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/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.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
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 +86,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.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= github.com/mailru/easyjson v0.9.2/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.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
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,35 +107,35 @@ 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 v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/ncruces/go-strftime v1.0.0/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/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/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= github.com/pressly/goose/v3 v3.27.2 h1:FjKNzcmMdGrQlSIu5alMSmakQtJFBgtw+A0bb1p/LC8=
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= github.com/pressly/goose/v3 v3.27.2/go.mod h1:qWW+/8dkVtJYjJrbIpwD5xxnEJTUKvxkQ9JKQp9LaIM=
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4= github.com/prometheus/common v0.69.0 h1:OA85nJQS/T/MaYh/Q2CcgDKSGWqNIgrBDvDH85CuiNk=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk= github.com/prometheus/common v0.69.0/go.mod h1:ZzL3f6u94qUxh9p+tJTrF+FvBS1XXbbRAZCQkytAL0Y=
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ= github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/rabbitmq/amqp091-go v1.12.0 h1:V0v14Iqfs+MwHWihJt/nGS5Ulu0vw572b2Co3mwunkI=
github.com/rabbitmq/amqp091-go v1.12.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/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
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=
@@ -143,22 +147,22 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
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.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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
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.6.0 h1:Vwj9cAsIhMrHPKRZVxfg6mHqE9LI/atDCq1aeihH3+I=
github.com/txix-open/bgjob v1.6.0/go.mod h1:aKbwpVclWmq82s7fchazp099yWjEpVKFkxT85i4hARM= github.com/txix-open/bgjob v1.6.0/go.mod h1:aKbwpVclWmq82s7fchazp099yWjEpVKFkxT85i4hARM=
github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo= github.com/txix-open/etp/v4 v4.1.1 h1:Yna+0mw/kQZP7Rl6QI4spCrO6qgO8ZhP8PjHlJj2lTU=
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM= github.com/txix-open/etp/v4 v4.1.1/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y= github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE= github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg= github.com/txix-open/isp-kit v1.71.1 h1:MNSuHy/HEvy7dKPQXkM+dgQpShDhcv1Sq1kLgep2LaA=
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M= github.com/txix-open/isp-kit v1.71.1/go.mod h1:j2sj86byoKllCs+DaRWwg56NgcL2omr/bUzmU7+AF74=
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=
@@ -170,58 +174,56 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
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= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 h1:MCcYL7J6Vt/X0kjqbMZkekCmwsurbQRbL69vkiye2lk=
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.69.0/go.mod h1:3jnStNwSufK+f5ktjL4EPcwtig4rtd81NS70lqHuXl8=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
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.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY= google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU=
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M= google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g= google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df h1:O3ig1i5WDDzsVzRp+cCdgelT9vXnlnOFdlEeFtL4HCc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
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=
@@ -230,11 +232,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
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.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA=
modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8=
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.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g= modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
+7 -6
View File
@@ -1,9 +1,9 @@
package main package main
import ( import (
"isp-admin-service/assembly" "msp-admin-service/assembly"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/routes" "msp-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/cluster"
@@ -12,7 +12,7 @@ import (
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 сервис управления администраторами
@@ -21,9 +21,10 @@ var version = "1.0.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(), cluster.GrpcTransport)
app := boot.App app := boot.App
logger := app.Logger() logger := app.Logger()
@@ -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;
+3 -3
View File
@@ -4,14 +4,14 @@ import (
"context" "context"
"time" "time"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"github.com/Masterminds/squirrel" "github.com/Masterminds/squirrel"
"github.com/iancoleman/strcase" "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"
) )
+2 -2
View File
@@ -4,12 +4,12 @@ import (
"context" "context"
"database/sql" "database/sql"
"isp-admin-service/entity" "msp-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"
) )
-69
View File
@@ -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
}
+7 -24
View File
@@ -4,14 +4,13 @@ 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 {
@@ -25,7 +24,6 @@ const (
updatedAtRolesColumn = "updated_at" updatedAtRolesColumn = "updated_at"
permissionsRolesColumn = "permissions" permissionsRolesColumn = "permissions"
externalGroupRolesColumn = "external_group" externalGroupRolesColumn = "external_group"
applicationGroupColumn = "application_group"
immutableRolesColumn = "immutable" immutableRolesColumn = "immutable"
exclusiveRolesColumn = "exclusive" exclusiveRolesColumn = "exclusive"
) )
@@ -38,7 +36,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()
@@ -68,7 +66,6 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err
updatedAtRolesColumn, updatedAtRolesColumn,
permissionsRolesColumn, permissionsRolesColumn,
externalGroupRolesColumn, externalGroupRolesColumn,
applicationGroupColumn,
immutableRolesColumn, immutableRolesColumn,
exclusiveRolesColumn, exclusiveRolesColumn,
). ).
@@ -103,7 +100,6 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
updatedAtRolesColumn, updatedAtRolesColumn,
permissionsRolesColumn, permissionsRolesColumn,
externalGroupRolesColumn, externalGroupRolesColumn,
applicationGroupColumn,
immutableRolesColumn, immutableRolesColumn,
exclusiveRolesColumn, exclusiveRolesColumn,
). ).
@@ -125,7 +121,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 +130,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 +157,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 {
+78
View File
@@ -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, "/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, "/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
}
+3 -3
View File
@@ -9,12 +9,12 @@ import (
"github.com/Masterminds/squirrel" "github.com/Masterminds/squirrel"
"github.com/iancoleman/strcase" "github.com/iancoleman/strcase"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"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"
) )
+21 -21
View File
@@ -6,14 +6,14 @@ import (
"strconv" "strconv"
"time" "time"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"github.com/Masterminds/squirrel" "github.com/Masterminds/squirrel"
"github.com/iancoleman/strcase" "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"
) )
@@ -25,7 +25,7 @@ const (
passwordUsersColumn = "password" passwordUsersColumn = "password"
createdAtUsersColumn = "created_at" createdAtUsersColumn = "created_at"
updatedAtUsersColumn = "updated_at" updatedAtUsersColumn = "updated_at"
oauthUserIdUsersColumn = "oauth_user_id" sudirUserIdUsersColumn = "sudir_user_id"
blockedUsersColumn = "blocked" blockedUsersColumn = "blocked"
descriptionUsersColumn = "description" descriptionUsersColumn = "description"
lastActiveAtUsersColumn = "last_active_at" lastActiveAtUsersColumn = "last_active_at"
@@ -45,7 +45,7 @@ func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, e
q, args, err := query.New(). q, args, err := query.New().
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn, Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn). fullNameUsersColumn).
From("users"). From("users").
Where(squirrel.Eq{"email": email}). Where(squirrel.Eq{"email": email}).
@@ -72,7 +72,7 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
q, args, err := query.New(). q, args, err := query.New().
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn, Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn). fullNameUsersColumn).
From("users"). From("users").
Where(squirrel.Eq{"id": identity}). Where(squirrel.Eq{"id": identity}).
@@ -94,17 +94,17 @@ 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) GetUserByEmailAndSudirId(ctx context.Context, email string, sudirUserId string) (*entity.User, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmailAndOauthId") ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
equalClause := squirrel.Eq{"email": email, "oauth_user_id": nil} equalClause := squirrel.Eq{"email": email, "sudir_user_id": nil}
if oauthUserId != "" { if sudirUserId != "" {
equalClause["oauth_user_id"] = oauthUserId equalClause["sudir_user_id"] = sudirUserId
} }
q, args, err := query.New(). q, args, err := query.New().
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn, Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn). fullNameUsersColumn).
From("users"). From("users").
Where(equalClause). Where(equalClause).
@@ -126,13 +126,13 @@ func (u User) GetUserByEmailAndOauthId(ctx context.Context, email string, oauthU
} }
} }
func (u User) UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error) { func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertByOauthUserId") ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertBySudirUserId")
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, full_name, email, created_at, updated_at, sudir_user_id)
values ($1, $2, $3, $4, $5, $6, $7) values ($1, $2, $3, $4, $5, $6, $7)
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, full_name = excluded.full_name,
@@ -145,7 +145,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.FullName, 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
@@ -162,7 +162,7 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]enti
q := query.New(). q := query.New().
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn, Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at"). fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
From("users"). From("users").
Offset(req.Offset). Offset(req.Offset).
@@ -193,7 +193,7 @@ func (u User) GetAllUsers(ctx context.Context) ([]entity.User, error) {
query, args, err := query.New(). query, args, err := query.New().
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn, Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at"). fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
From("users").ToSql() From("users").ToSql()
if err != nil { if err != nil {
@@ -214,7 +214,7 @@ func (u User) GetUsersByEmail(ctx context.Context, email string) ([]entity.User,
q, args, err := query.New(). q, args, err := query.New().
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn, Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn). fullNameUsersColumn).
From("users"). From("users").
Where(squirrel.Eq{"email": email}). Where(squirrel.Eq{"email": email}).
@@ -274,7 +274,7 @@ func (u User) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser)
descriptionUsersColumn: 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, full_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")
+2 -3
View File
@@ -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 {
+10 -96
View File
@@ -1,14 +1,12 @@
package routes package routes
import ( import (
"isp-admin-service/controller" "msp-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"
) )
type Controllers struct { type Controllers struct {
@@ -20,24 +18,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
} }
@@ -49,221 +39,145 @@ func endpointDescriptors(c Controllers) []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/auth/logout_with_reason",
Inner: true, Inner: true,
Handler: c.Auth.LogoutWithReason, Handler: c.Auth.LogoutWithReason,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_profile", Path: "admin/user/get_profile",
Inner: true, Inner: true,
Handler: c.User.GetProfile, Handler: c.User.GetProfile,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_design", Path: "admin/user/get_design",
Inner: true, Inner: true,
Handler: c.Customization.GetUIDesign, Handler: c.Customization.GetUIDesign,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_users", Path: "admin/user/get_users",
Inner: true, Inner: true,
Handler: c.User.GetUsers, Handler: c.User.GetUsers,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_all_users", Path: "admin/user/get_all_users",
Inner: true, Inner: true,
Handler: c.User.GetAllUsers, Handler: c.User.GetAllUsers,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/create_user", Path: "admin/user/create_user",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("user_create"), Extra: cluster.RequireAdminPermission("user_create"),
Handler: c.User.CreateUser, Handler: c.User.CreateUser,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/update_user", Path: "admin/user/update_user",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("user_update"), Extra: cluster.RequireAdminPermission("user_update"),
Handler: c.User.UpdateUser, Handler: c.User.UpdateUser,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/delete_user", Path: "admin/user/delete_user",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("user_delete"), Extra: cluster.RequireAdminPermission("user_delete"),
Handler: c.User.DeleteUser, Handler: c.User.DeleteUser,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/block_user", Path: "admin/user/block_user",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("user_block"), Extra: cluster.RequireAdminPermission("user_block"),
Handler: c.User.Block, Handler: c.User.Block,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_by_id", Path: "admin/user/get_by_id",
Inner: true, Inner: true,
Handler: c.User.GetById, Handler: c.User.GetById,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/change_password", Path: "admin/user/change_password",
Inner: true, Inner: true,
Handler: c.User.ChangePassword, Handler: c.User.ChangePassword,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/role/all", Path: "admin/role/all",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_view"), Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Role.All, Handler: c.Role.All,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_permissions", Path: "admin/user/get_permissions",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_view"), Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Permissions.GetPermissions, Handler: c.Permissions.GetPermissions,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/role/create", Path: "admin/role/create",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_add"), Extra: cluster.RequireAdminPermission("role_add"),
Handler: c.Role.CreateRole, Handler: c.Role.CreateRole,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/role/update", Path: "admin/role/update",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_update"), Extra: cluster.RequireAdminPermission("role_update"),
Handler: c.Role.UpdateRole, Handler: c.Role.UpdateRole,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/role/delete", Path: "admin/role/delete",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_delete"), Extra: cluster.RequireAdminPermission("role_delete"),
Handler: c.Role.DeleteRole, Handler: c.Role.DeleteRole,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/session/all", Path: "admin/session/all",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("session_view"), Extra: cluster.RequireAdminPermission("session_view"),
Handler: c.Session.All, Handler: c.Session.All,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/session/revoke", Path: "admin/session/revoke",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("session_revoke"), Extra: cluster.RequireAdminPermission("session_revoke"),
Handler: c.Session.Revoke, Handler: c.Session.Revoke,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/log/all", Path: "admin/log/all",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("security_log_view"), Extra: cluster.RequireAdminPermission("security_log_view"),
Handler: c.Audit.All, Handler: c.Audit.All,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/log/events", Path: "admin/log/events",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"), Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.Events, Handler: c.Audit.Events,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/log/set_events", Path: "admin/log/set_events",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"), Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.SetEvents, Handler: c.Audit.SetEvents,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/secure/authenticate", Path: "admin/secure/authenticate",
Inner: true, Inner: true,
Handler: c.Secure.Authenticate, Handler: c.Secure.Authenticate,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/secure/authorize", Path: "admin/secure/authorize",
Inner: true, Inner: true,
Handler: c.Secure.Authorize, 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
}
+4 -4
View File
@@ -4,11 +4,11 @@ import (
"context" "context"
"time" "time"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"github.com/txix-open/isp-kit/errors" "github.com/pkg/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"
) )
+30 -30
View File
@@ -5,10 +5,10 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"github.com/txix-open/isp-kit/errors" "github.com/pkg/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"
) )
@@ -30,7 +30,7 @@ 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 UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
} }
@@ -40,15 +40,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 +60,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 +70,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 +100,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 {
@@ -141,7 +141,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 +150,41 @@ 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, FullName: sudirUser.FullName,
Email: oauthUser.Email, Email: sudirUser.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")
} }
@@ -206,7 +206,7 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
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,
+1 -1
View File
@@ -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 (
+2 -2
View File
@@ -4,11 +4,11 @@ import (
"context" "context"
"time" "time"
"isp-admin-service/conf" "msp-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/bgjobx/handler"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
) )
-325
View File
@@ -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, req.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, req domain.RoleAllRequest, w http.ResponseWriter) error {
roles, err := s.roleService.All(ctx, req)
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")
}
+1 -1
View File
@@ -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 (
+3 -3
View File
@@ -4,12 +4,12 @@ import (
"context" "context"
"time" "time"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/entity" "msp-admin-service/entity"
"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/bgjobx/handler"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
) )
-99
View File
@@ -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
}
+5 -5
View File
@@ -3,20 +3,20 @@ 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
} }
+5 -23
View File
@@ -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")
} }
@@ -70,7 +59,6 @@ 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,
}) })
@@ -82,12 +70,10 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
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,
@@ -122,7 +108,6 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
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,
}) })
@@ -135,12 +120,10 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
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,
@@ -167,7 +150,6 @@ func (u Role) toDomain(role entity.Role) 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,
+3 -4
View File
@@ -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 -1
View File
@@ -3,9 +3,9 @@ package session_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 (
+2 -2
View File
@@ -4,11 +4,11 @@ import (
"context" "context"
"time" "time"
"isp-admin-service/entity" "msp-admin-service/entity"
"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/bgjobx/handler"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
) )
+79
View File
@@ -0,0 +1,79 @@
package service
import (
"context"
"msp-admin-service/conf"
"msp-admin-service/domain"
"msp-admin-service/entity"
"github.com/pkg/errors"
)
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,
FullName: user.Name,
Email: email,
}, nil
}
+3 -3
View File
@@ -6,10 +6,10 @@ import (
"encoding/hex" "encoding/hex"
"time" "time"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"github.com/txix-open/isp-kit/errors" "github.com/pkg/errors"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
) )
-80
View File
@@ -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
}
+9 -9
View File
@@ -8,10 +8,10 @@ import (
"strings" "strings"
"time" "time"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"github.com/txix-open/isp-kit/errors" "github.com/pkg/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"
) )
@@ -31,7 +31,7 @@ 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, req domain.UsersPageRequest) ([]entity.User, error)
GetAllUsers(ctx context.Context) ([]entity.User, error) GetAllUsers(ctx context.Context) ([]entity.User, error)
GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error) GetUserByEmailAndSudirId(ctx context.Context, email string, sudirUserId string) (*entity.User, error)
GetUsersByEmail(ctx context.Context, email 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)
@@ -207,7 +207,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.GetUserByEmailAndSudirId(ctx, req.Email, "")
switch { switch {
case errors.Is(err, domain.ErrNotFound): case errors.Is(err, domain.ErrNotFound):
break break
@@ -223,7 +223,7 @@ 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,
@@ -301,12 +301,12 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
for _, usr := range users { for _, usr := range users {
// check in internal user space // check in internal user space
if (user.OauthUserId == nil && usr.OauthUserId == nil) && (usr.Id != req.Id) { if (user.SudirUserId == nil && usr.SudirUserId == nil) && (usr.Id != req.Id) {
return domain.ErrAlreadyExists return domain.ErrAlreadyExists
} }
// check in oauth user space // check in sudir user space
if usr.OauthUserId != nil && user.OauthUserId != nil && (*user.OauthUserId != *usr.OauthUserId) { if usr.SudirUserId != nil && user.SudirUserId != nil && (*user.SudirUserId != *usr.SudirUserId) {
return domain.ErrAlreadyExists return domain.ErrAlreadyExists
} }
} }
+84 -80
View File
@@ -1,22 +1,25 @@
package tests_test package tests_test
import ( import (
"net/http" "context"
"testing" "testing"
"time" "time"
"isp-admin-service/assembly" "msp-admin-service/assembly"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"isp-admin-service/repository" "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/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"
) )
func TestAuditSuite(t *testing.T) { func TestAuditSuite(t *testing.T) {
@@ -29,13 +32,13 @@ type AuditSuite struct {
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{
@@ -68,26 +71,26 @@ func (s *AuditSuite) SetupTest() {
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(), remote, time.Minute)
s.Require().NoError(err)
s.insertAuditLogs()
server, cli := httpt.TestServer(s.test, cfg.Handler) t.insertAuditLogs()
s.httpCli = cli
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
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: "успешный вход",
@@ -99,16 +102,16 @@ func (s *AuditSuite) Test_Events_DefaultEvents() {
} }
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},
@@ -118,33 +121,33 @@ func (s *AuditSuite) Test_Events_SortEvents() {
{Event: entity.EventUserBlocked, 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, 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,
@@ -154,37 +157,38 @@ func (s *AuditSuite) Test_SetEvents_HappyPath() {
entity.EventUserChanged: true, entity.EventUserChanged: true,
entity.EventUserBlocked: 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() { func (t *AuditSuite) Test_All_Logs() {
request := domain.AuditPageRequest{ request := domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 3, Limit: 3,
Offset: 5, Offset: 5,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "user_id", Field: "user_id",
Type: "desc", Type: "desc",
@@ -192,17 +196,17 @@ func (s *AuditSuite) Test_All_Logs() {
} }
var response *domain.AuditResponse var response *domain.AuditResponse
err := s.httpCli. err := t.grpcCli.
Post("admin/log/all"). Invoke("admin/log/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) t.Require().NoError(err)
s.Require().Len(response.Items, 3) t.Require().Len(response.Items, 3)
s.Require().EqualValues(5, response.Items[0].UserId) t.Require().EqualValues(5, response.Items[0].UserId)
s.Require().EqualValues(4, response.Items[1].UserId) t.Require().EqualValues(4, response.Items[1].UserId)
s.Require().EqualValues(3, response.Items[2].UserId) t.Require().EqualValues(3, response.Items[2].UserId)
request.Query = &domain.AuditQuery{ request.Query = &domain.AuditQuery{
Message: new("Выход"), Message: new("Выход"),
@@ -210,25 +214,25 @@ func (s *AuditSuite) Test_All_Logs() {
request.Limit = 10 request.Limit = 10
request.Offset = 0 request.Offset = 0
err = s.httpCli. err = t.grpcCli.
Post("admin/log/all"). Invoke("admin/log/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) t.Require().NoError(err)
s.Require().Len(response.Items, 6) t.Require().Len(response.Items, 6)
s.Require().EqualValues(6, response.TotalCount) t.Require().EqualValues(6, response.TotalCount)
s.Require().EqualValues(10, response.Items[0].UserId) t.Require().EqualValues(10, response.Items[0].UserId)
s.Require().EqualValues(9, response.Items[1].UserId) t.Require().EqualValues(9, response.Items[1].UserId)
s.Require().EqualValues(8, response.Items[2].UserId) t.Require().EqualValues(8, response.Items[2].UserId)
s.Require().EqualValues(7, response.Items[3].UserId) t.Require().EqualValues(7, response.Items[3].UserId)
s.Require().EqualValues(6, response.Items[4].UserId) t.Require().EqualValues(6, response.Items[4].UserId)
s.Require().EqualValues(5, response.Items[5].UserId) t.Require().EqualValues(5, response.Items[5].UserId)
} }
func (s *AuditSuite) insertAuditLogs() { func (t *AuditSuite) insertAuditLogs() {
s.db.Must().Exec(`INSERT INTO audit (user_id, message, created_at, event) t.db.Must().Exec(`INSERT INTO audit (user_id, message, created_at, event)
VALUES (1, 'Успешный вход', NOW(), 'success_login'), VALUES (1, 'Успешный вход', NOW(), 'success_login'),
(2, 'Успешный вход', NOW(), 'success_login'), (2, 'Успешный вход', NOW(), 'success_login'),
(3, 'Неуспешный вход', NOW(), 'unsuccess_login'), (3, 'Неуспешный вход', NOW(), 'unsuccess_login'),
+70 -104
View File
@@ -1,6 +1,7 @@
package tests_test package tests_test
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -10,23 +11,25 @@ import (
"testing" "testing"
"time" "time"
"isp-admin-service/assembly" "msp-admin-service/assembly"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"isp-admin-service/repository" "msp-admin-service/repository"
"github.com/txix-open/isp-kit/errors" "github.com/pkg/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"
"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) {
@@ -39,50 +42,40 @@ type AuthTestSuite struct {
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/") sudirHost, _ := url.JoinPath(host, "/blitz/")
s.oauthCli.GlobalRequestConfig().BaseUrl = oauthHost
remote := conf.Remote{ remote := conf.Remote{
Oauth: &conf.Oauth{ SudirAuth: &conf.SudirAuth{
Host: host,
Clients: []conf.OauthClientConfig{
{
ClientName: s.oauthClientName,
ClientId: "admin", ClientId: "admin",
ClientSecret: "admin", ClientSecret: "admin",
Host: sudirHost,
RedirectURI: "http://localhost", RedirectURI: "http://localhost",
}, },
},
},
ExpireSec: 3600, ExpireSec: 3600,
AntiBruteforce: conf.AntiBruteforce{ AntiBruteforce: conf.AntiBruteforce{
MaxInFlightLoginRequests: 3, MaxInFlightLoginRequests: 3,
DelayLoginRequestInSec: 1, DelayLoginRequestInSec: 1,
}, },
} }
cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
Config(context.Background(), 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,13 +89,13 @@ 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)
@@ -112,18 +105,16 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
} }
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() time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
} }
@@ -137,18 +128,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() time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
} }
@@ -161,36 +150,33 @@ 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() 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, full_name 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) s.Require().Equal("surname name patronymic", user.FullName)
tokenInfo := SelectTokenEntityByToken(s.db, response.Token) tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
@@ -199,24 +185,6 @@ func (s *AuthTestSuite) TestOauthLoginHappyPath() {
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() 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() {
userId := InsertUser(s.db, entity.User{Email: "suslik@mail.ru"}) userId := InsertUser(s.db, entity.User{Email: "suslik@mail.ru"})
InsertTokenEntity(s.db, entity.Token{ InsertTokenEntity(s.db, entity.Token{
@@ -226,9 +194,9 @@ 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")
@@ -238,16 +206,18 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
} }
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.AllByRequest(context.Background(), domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 10, Limit: 10,
Offset: 0, Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "created_at", Field: "created_at",
Type: "desc", Type: "desc",
@@ -269,9 +239,9 @@ 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")
@@ -290,29 +260,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:
@@ -332,11 +298,11 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
time.Sleep(2 * time.Second) // wait for go SaveAuditAsync() 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,11 +312,11 @@ 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", Name: "surname name patronymic",
+14 -15
View File
@@ -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) {
@@ -25,7 +25,7 @@ type CustomizationTestSuite struct {
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 +40,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(), 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",
+9 -13
View File
@@ -1,10 +1,10 @@
package tests_test package tests_test
import ( import (
"isp-admin-service/entity" "msp-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"
) )
@@ -21,15 +21,15 @@ func InsertUser(db *dbt.TestDb, user entity.User) int64 {
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", "full_name", "email").
Values(user.OauthUserId, user.FirstName, user.LastName, user.FullName, user.Email). Values(user.SudirUserId, user.FirstName, user.LastName, user.FullName, 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"))
-277
View File
@@ -1,277 +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() {
InsertRole(s.db, entity.Role{
Name: "admin_1",
ApplicationGroup: "123",
Permissions: s.permissions,
})
InsertRole(s.db, entity.Role{
Name: "admin_2",
ApplicationGroup: "456",
Permissions: s.permissions,
})
applicationGroup := "123"
resp, err := s.httpCli.Post("role/download").
JsonRequestBody(domain.RoleAllRequest{
ApplicationGroup: &applicationGroup,
}).
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
}
moveIdx, ok := col["Действие"]
s.Require().True(ok)
keyIdx, ok := col["Ключ в системе"]
s.Require().True(ok)
nameIdx, ok := col["admin_1"]
s.Require().True(ok)
s.Require().Len(records, 2)
row := records[1]
s.Require().EqualValues("123", row[moveIdx])
s.Require().EqualValues("data_download", row[keyIdx])
s.Require().EqualValues("+", row[nameIdx])
}
+10 -9
View File
@@ -4,13 +4,13 @@ import (
"testing" "testing"
"time" "time"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/service/inactive_worker" "msp-admin-service/service/inactive_worker"
"isp-admin-service/assembly" "msp-admin-service/assembly"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/entity" "msp-admin-service/entity"
"isp-admin-service/repository" "msp-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"
@@ -27,17 +27,16 @@ func TestInactiveWorker(t *testing.T) {
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", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)})
InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()}) InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()})
config, err := assembly.NewLocator(test.Logger(), nil, db). config := assembly.NewLocator(test.Logger(), nil, db).
Config(t.Context(), conf.Remote{ Config(t.Context(), 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)
@@ -49,8 +48,10 @@ func TestInactiveWorker(t *testing.T) {
require.True(user.Blocked) require.True(user.Blocked)
list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{ list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 10, Limit: 10,
Offset: 0, Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "created_at", Field: "created_at",
Type: "desc", Type: "desc",
-173
View File
@@ -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 -27
View File
@@ -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) {
@@ -29,7 +30,7 @@ type SecureSuite struct {
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 +40,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(), 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 +60,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 +84,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 +108,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 +124,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 +164,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)
} }
+86 -83
View File
@@ -1,23 +1,25 @@
package tests_test package tests_test
import ( import (
"context"
"strconv" "strconv"
"testing" "testing"
"time" "time"
"isp-admin-service/assembly" "msp-admin-service/assembly"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"isp-admin-service/service/session_worker" "msp-admin-service/service/session_worker"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"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/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"
) )
func TestSessionSuite(t *testing.T) { func TestSessionSuite(t *testing.T) {
@@ -31,13 +33,13 @@ type SessionSuite struct {
test *test.Test test *test.Test
db *dbt.TestDb db *dbt.TestDb
config assembly.Config config assembly.Config
httpCli *httpcli.Client grpcCli *client.Client
} }
func (s *SessionSuite) SetupTest() { func (t *SessionSuite) 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{
@@ -70,26 +72,23 @@ func (s *SessionSuite) SetupTest() {
AuditTTl: conf.AuditTTlSetting{}, AuditTTl: conf.AuditTTlSetting{},
}, },
} }
config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). t.config = assembly.NewLocator(testInstance.Logger(), httpcli.New(), t.db).
Config(s.T().Context(), remote, 500*time.Millisecond) Config(context.Background(), remote, 500*time.Millisecond)
s.Require().NoError(err)
s.config = config server, apiCli := grpct.TestServer(testInstance, t.config.Handler)
t.grpcCli = apiCli
server, cli := httpt.TestServer(s.test, config.Handler)
s.httpCli = cli
testInstance.T().Cleanup(func() { testInstance.T().Cleanup(func() {
server.Close() server.Shutdown()
}) })
} }
//nolint:funlen //nolint:funlen
func (s *SessionSuite) Test_All_Session() { func (t *SessionSuite) Test_All_Session() {
userId := InsertUser(s.db, entity.User{Email: "test_1@aa.ru"}) userId := InsertUser(t.db, entity.User{Email: "test_1@aa.ru"})
timeNow := time.Now().UTC() timeNow := time.Now().UTC()
InsertTokenEntity(s.db, entity.Token{ InsertTokenEntity(t.db, entity.Token{
Token: "test_token_1", Token: "test_token_1",
UserId: userId, UserId: userId,
Status: entity.TokenStatusAllowed, Status: entity.TokenStatusAllowed,
@@ -97,7 +96,7 @@ func (s *SessionSuite) Test_All_Session() {
CreatedAt: timeNow.Add(-1 * time.Hour), CreatedAt: timeNow.Add(-1 * time.Hour),
UpdatedAt: timeNow, UpdatedAt: timeNow,
}) })
InsertTokenEntity(s.db, entity.Token{ InsertTokenEntity(t.db, entity.Token{
Token: "test_token_2", Token: "test_token_2",
UserId: userId, UserId: userId,
Status: entity.TokenStatusRevoked, Status: entity.TokenStatusRevoked,
@@ -105,7 +104,7 @@ func (s *SessionSuite) Test_All_Session() {
CreatedAt: timeNow.Add(-2 * time.Hour), CreatedAt: timeNow.Add(-2 * time.Hour),
UpdatedAt: timeNow, UpdatedAt: timeNow,
}) })
InsertTokenEntity(s.db, entity.Token{ InsertTokenEntity(t.db, entity.Token{
Token: "test_token_3", Token: "test_token_3",
UserId: userId, UserId: userId,
Status: entity.TokenStatusExpired, Status: entity.TokenStatusExpired,
@@ -116,22 +115,24 @@ func (s *SessionSuite) Test_All_Session() {
// Дефолт сортировка, лимит и оффсет // Дефолт сортировка, лимит и оффсет
request := domain.SessionPageRequest{ request := domain.SessionPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 5, Limit: 5,
Offset: 1, Offset: 1,
},
} }
var response *domain.SessionResponse var response *domain.SessionResponse
err := s.httpCli. err := t.grpcCli.
Post("admin/session/all"). Invoke("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) t.Require().NoError(err)
s.Require().Len(response.Items, 2) t.Require().Len(response.Items, 2)
s.Require().EqualValues(3, response.TotalCount) t.Require().EqualValues(3, response.TotalCount)
s.Require().EqualValues(2, response.Items[0].Id) t.Require().EqualValues(2, response.Items[0].Id)
s.Require().EqualValues(3, response.Items[1].Id) t.Require().EqualValues(3, response.Items[1].Id)
// Дефолт сортировка, поиск по expired_at // Дефолт сортировка, поиск по expired_at
request.Offset = 0 request.Offset = 0
@@ -141,17 +142,17 @@ func (s *SessionSuite) Test_All_Session() {
To: timeNow.Add(24 * time.Hour), To: timeNow.Add(24 * time.Hour),
}, },
} }
err = s.httpCli. err = t.grpcCli.
Post("admin/session/all"). Invoke("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) t.Require().NoError(err)
s.Require().Len(response.Items, 2) t.Require().Len(response.Items, 2)
s.Require().EqualValues(2, response.TotalCount) t.Require().EqualValues(2, response.TotalCount)
s.Require().EqualValues(1, response.Items[0].Id) t.Require().EqualValues(1, response.Items[0].Id)
s.Require().EqualValues(2, response.Items[1].Id) t.Require().EqualValues(2, response.Items[1].Id)
// Сортировка по статусу, пустой запрос // Сортировка по статусу, пустой запрос
request.Query = nil request.Query = nil
@@ -160,18 +161,18 @@ func (s *SessionSuite) Test_All_Session() {
Type: "asc", Type: "asc",
} }
err = s.httpCli. err = t.grpcCli.
Post("admin/session/all"). Invoke("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) t.Require().NoError(err)
s.Require().Len(response.Items, 3) t.Require().Len(response.Items, 3)
s.Require().EqualValues(3, response.TotalCount) t.Require().EqualValues(3, response.TotalCount)
s.Require().EqualValues(1, response.Items[0].Id) t.Require().EqualValues(1, response.Items[0].Id)
s.Require().EqualValues(3, response.Items[1].Id) t.Require().EqualValues(3, response.Items[1].Id)
s.Require().EqualValues(2, response.Items[2].Id) t.Require().EqualValues(2, response.Items[2].Id)
// Сортировка по статусу, поиск по userId & status // Сортировка по статусу, поиск по userId & status
resUserId := int(userId) resUserId := int(userId)
@@ -180,21 +181,21 @@ func (s *SessionSuite) Test_All_Session() {
Status: []string{entity.TokenStatusExpired}, Status: []string{entity.TokenStatusExpired},
} }
err = s.httpCli. err = t.grpcCli.
Post("admin/session/all"). Invoke("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) t.Require().NoError(err)
s.Require().Len(response.Items, 1) t.Require().Len(response.Items, 1)
s.Require().EqualValues(1, response.TotalCount) t.Require().EqualValues(1, response.TotalCount)
s.Require().EqualValues(3, response.Items[0].Id) t.Require().EqualValues(3, response.Items[0].Id)
// Сортировка по id, поиск по id // Сортировка по id, поиск по id
for i := range 20 { for i := range 20 {
userId = InsertUser(s.db, entity.User{Email: "test_11" + strconv.Itoa(i) + "@aa.ru"}) userId = InsertUser(t.db, entity.User{Email: "test_11" + strconv.Itoa(i) + "@aa.ru"})
InsertTokenEntity(s.db, entity.Token{ InsertTokenEntity(t.db, entity.Token{
Token: "test_token_1" + strconv.Itoa(i), Token: "test_token_1" + strconv.Itoa(i),
UserId: userId, UserId: userId,
Status: entity.TokenStatusAllowed, Status: entity.TokenStatusAllowed,
@@ -205,8 +206,10 @@ func (s *SessionSuite) Test_All_Session() {
} }
request = domain.SessionPageRequest{ request = domain.SessionPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 5, Limit: 5,
Offset: 0, Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "id", Field: "id",
Type: "desc", Type: "desc",
@@ -215,57 +218,57 @@ func (s *SessionSuite) Test_All_Session() {
Id: new(2), Id: new(2),
}, },
} }
err = s.httpCli. err = t.grpcCli.
Post("admin/session/all"). Invoke("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) t.Require().NoError(err)
s.Require().Len(response.Items, 5) t.Require().Len(response.Items, 5)
s.Require().EqualValues(6, response.TotalCount) t.Require().EqualValues(6, response.TotalCount)
s.Require().EqualValues(23, response.Items[0].Id) t.Require().EqualValues(23, response.Items[0].Id)
s.Require().EqualValues(22, response.Items[1].Id) t.Require().EqualValues(22, response.Items[1].Id)
s.Require().EqualValues(21, response.Items[2].Id) t.Require().EqualValues(21, response.Items[2].Id)
s.Require().EqualValues(20, response.Items[3].Id) t.Require().EqualValues(20, response.Items[3].Id)
s.Require().EqualValues(12, response.Items[4].Id) t.Require().EqualValues(12, response.Items[4].Id)
} }
func (s *SessionSuite) Test_Session_Expired_Worker() { func (t *SessionSuite) Test_Session_Expired_Worker() {
userId := InsertUser(s.db, entity.User{Email: "a@test"}) userId := InsertUser(t.db, entity.User{Email: "a@test"})
InsertTokenEntity(s.db, entity.Token{ InsertTokenEntity(t.db, entity.Token{
Token: "token_allowed", Token: "token_allowed",
UserId: userId, UserId: userId,
Status: entity.TokenStatusAllowed, Status: entity.TokenStatusAllowed,
ExpiredAt: time.Now().UTC().Add(24 * time.Hour)}) ExpiredAt: time.Now().UTC().Add(24 * time.Hour)})
InsertTokenEntity(s.db, entity.Token{ InsertTokenEntity(t.db, entity.Token{
Token: "token_expired", Token: "token_expired",
UserId: userId, UserId: userId,
Status: entity.TokenStatusAllowed, Status: entity.TokenStatusAllowed,
ExpiredAt: time.Now().UTC().Add(-2 * time.Hour)}) ExpiredAt: time.Now().UTC().Add(-2 * time.Hour)})
InsertTokenEntity(s.db, entity.Token{ InsertTokenEntity(t.db, entity.Token{
Token: "token_expired2", Token: "token_expired2",
UserId: userId, UserId: userId,
Status: entity.TokenStatusAllowed, Status: entity.TokenStatusAllowed,
ExpiredAt: time.Now().UTC().Add(-24 * time.Hour)}) ExpiredAt: time.Now().UTC().Add(-24 * time.Hour)})
bgjobCli := bgjobx.NewClient(s.db, s.test.Logger()) bgjobCli := bgjobx.NewClient(t.db, t.test.Logger())
err := session_worker.EnqueueSeedJob(s.T().Context(), bgjobCli) err := session_worker.EnqueueSeedJob(t.T().Context(), bgjobCli)
s.Require().NoError(err) t.Require().NoError(err)
err = bgjobCli.Upgrade(s.T().Context(), s.config.BgJobCfg) err = bgjobCli.Upgrade(t.T().Context(), t.config.BgJobCfg)
s.Require().NoError(err) t.Require().NoError(err)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
tokens := make([]entity.Token, 0) tokens := make([]entity.Token, 0)
s.db.Must().Select(&tokens, "SELECT * FROM tokens ORDER BY status ASC") t.db.Must().Select(&tokens, "SELECT * FROM tokens ORDER BY status ASC")
s.Require().EqualValues(entity.TokenStatusAllowed, tokens[0].Status) t.Require().EqualValues(entity.TokenStatusAllowed, tokens[0].Status)
s.Require().EqualValues(entity.TokenStatusExpired, tokens[1].Status) t.Require().EqualValues(entity.TokenStatusExpired, tokens[1].Status)
s.Require().EqualValues(entity.TokenStatusExpired, tokens[2].Status) t.Require().EqualValues(entity.TokenStatusExpired, tokens[2].Status)
} }
-106
View File
@@ -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)
}
+115 -124
View File
@@ -2,28 +2,30 @@ package tests_test
import ( import (
"context" "context"
"encoding/json"
"net/http"
"strconv" "strconv"
"testing" "testing"
"time" "time"
"github.com/txix-open/isp-kit/grpc/apierrors"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"isp-admin-service/assembly" "msp-admin-service/assembly"
"isp-admin-service/conf" "msp-admin-service/conf"
"isp-admin-service/domain" "msp-admin-service/domain"
"isp-admin-service/entity" "msp-admin-service/entity"
"isp-admin-service/repository" "msp-admin-service/repository"
"isp-admin-service/service" "msp-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"
) )
type tokenService interface { type tokenService interface {
@@ -40,7 +42,7 @@ type UserTestSuite struct {
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 +56,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(), 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)
@@ -88,10 +89,10 @@ 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",
@@ -115,19 +116,18 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
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", FullName: "surname name",
@@ -144,11 +144,11 @@ 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",
@@ -183,10 +183,12 @@ func (s *UserTestSuite) TestGetUsers() {
email := "a1@" 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.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 5, Limit: 5,
Offset: 1, Offset: 1,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "email", Field: "email",
Type: "asc", Type: "asc",
@@ -197,7 +199,7 @@ func (s *UserTestSuite) TestGetUsers() {
}, },
}). }).
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)} roles := []int{int(roleId1), int(roleId2)}
@@ -209,10 +211,12 @@ func (s *UserTestSuite) TestGetUsers() {
s.Require().EqualValues(roles, response.Items[1].Roles) s.Require().EqualValues(roles, response.Items[1].Roles)
email = "test@mail.ru" email = "test@mail.ru"
err = s.apiCli.Post("admin/user/get_users"). err = s.grpcCli.Invoke("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 10, Limit: 10,
Offset: 0, Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "id", Field: "id",
Type: "asc", Type: "asc",
@@ -223,7 +227,7 @@ func (s *UserTestSuite) TestGetUsers() {
}, },
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Empty(response.Items) s.Require().Empty(response.Items)
} }
@@ -246,10 +250,7 @@ func (s *UserTestSuite) TestAllGetUsers() {
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)}) InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
response := domain.UsersResponse{} response := domain.UsersResponse{}
err := s.apiCli.Post("admin/user/get_all_users"). err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(context.Background())
JsonResponseBody(&response).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 7) s.Require().Len(response.Items, 7)
@@ -294,10 +295,12 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
}) })
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.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 5, Limit: 5,
Offset: 0, Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "lastSessionCreatedAt", Field: "lastSessionCreatedAt",
Type: "desc", Type: "desc",
@@ -310,7 +313,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
}, },
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 2) s.Require().Len(response.Items, 2)
@@ -328,10 +331,12 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"}) userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
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.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 10, Limit: 10,
Offset: 0, Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "userId", Field: "userId",
Type: "asc", Type: "asc",
@@ -341,7 +346,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
}, },
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
DoWithoutResponse(s.T().Context()) Do(context.Background())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 4) s.Require().Len(response.Items, 4)
@@ -358,9 +363,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,7 +373,7 @@ 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
@@ -378,17 +383,17 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
} }
func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() { func (s *UserTestSuite) TestCreateUserWithSameEmailSudirHappyPath() {
firstOauthId := "user_a" firstSudirId := "user_a"
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a2@a.ru"}) admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a2@a.ru"})
preCount := 0 preCount := 0
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",
@@ -396,7 +401,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
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
@@ -409,22 +414,20 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
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 +439,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,
@@ -453,20 +457,21 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() 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{SudirUserId: "123", Email: "sudir@a.ru", FullName: "surname name patronymic"})
req := domain.UpdateUserRequest{ req := domain.UpdateUserRequest{
Id: id, Id: id,
FirstName: "nameUpd", FirstName: "nameUpd",
LastName: "surnameUpd", LastName: "surnameUpd",
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,
@@ -489,40 +494,38 @@ 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() { func (s *AuthTestSuite) TestUpdateUserWithSudirAlreadyExist() {
firstOauthId := "user_a" firstSudirId := "user_a"
secondOauthId := "user_b" secondSudirId := "user_b"
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a_exists@a.ru"}) admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a_exists@a.ru"})
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: secondOauthId, Email: "b_exists@b.ru"}) id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: secondSudirId, Email: "b_exists@b.ru"})
req := domain.UpdateUserRequest{ req := domain.UpdateUserRequest{
Id: id, Id: id,
FirstName: "name", FirstName: "name",
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 *UserTestSuite) TestDeleteUsers() { func (s *UserTestSuite) TestDeleteUsers() {
@@ -532,12 +535,12 @@ 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)
@@ -563,18 +566,17 @@ 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)
@@ -595,31 +597,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)
+3 -3
View File
@@ -3,9 +3,9 @@ package transaction
import ( import (
"context" "context"
"isp-admin-service/repository" "msp-admin-service/repository"
"isp-admin-service/service" "msp-admin-service/service"
"isp-admin-service/service/session_worker" "msp-admin-service/service/session_worker"
"github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db"
) )
-1
View File
@@ -1 +0,0 @@
squirrel.test
-30
View File
@@ -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
View File
@@ -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
View File
@@ -1,142 +0,0 @@
[![Stability: Maintenance](https://masterminds.github.io/stability/maintenance.svg)](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"
```
[![GoDoc](https://godoc.org/github.com/Masterminds/squirrel?status.png)](https://godoc.org/github.com/Masterminds/squirrel)
[![Build Status](https://api.travis-ci.org/Masterminds/squirrel.svg?branch=master)](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
View File
@@ -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
View File
@@ -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)
}
-69
View File
@@ -1,69 +0,0 @@
// +build go1.8
package squirrel
import (
"context"
"database/sql"
"github.com/lann/builder"
)
func (d *deleteData) ExecContext(ctx context.Context) (sql.Result, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
ctxRunner, ok := d.RunWith.(ExecerContext)
if !ok {
return nil, NoContextSupport
}
return ExecContextWith(ctx, ctxRunner, d)
}
func (d *deleteData) QueryContext(ctx context.Context) (*sql.Rows, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
ctxRunner, ok := d.RunWith.(QueryerContext)
if !ok {
return nil, NoContextSupport
}
return QueryContextWith(ctx, ctxRunner, d)
}
func (d *deleteData) QueryRowContext(ctx context.Context) RowScanner {
if d.RunWith == nil {
return &Row{err: RunnerNotSet}
}
queryRower, ok := d.RunWith.(QueryRowerContext)
if !ok {
if _, ok := d.RunWith.(QueryerContext); !ok {
return &Row{err: RunnerNotQueryRunner}
}
return &Row{err: NoContextSupport}
}
return QueryRowContextWith(ctx, queryRower, d)
}
// ExecContext builds and ExecContexts the query with the Runner set by RunWith.
func (b DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error) {
data := builder.GetStruct(b).(deleteData)
return data.ExecContext(ctx)
}
// QueryContext builds and QueryContexts the query with the Runner set by RunWith.
func (b DeleteBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) {
data := builder.GetStruct(b).(deleteData)
return data.QueryContext(ctx)
}
// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith.
func (b DeleteBuilder) QueryRowContext(ctx context.Context) RowScanner {
data := builder.GetStruct(b).(deleteData)
return data.QueryRowContext(ctx)
}
// ScanContext is a shortcut for QueryRowContext().Scan.
func (b DeleteBuilder) ScanContext(ctx context.Context, dest ...interface{}) error {
return b.QueryRowContext(ctx).Scan(dest...)
}
-419
View File
@@ -1,419 +0,0 @@
package squirrel
import (
"bytes"
"database/sql/driver"
"fmt"
"reflect"
"sort"
"strings"
)
const (
// Portable true/false literals.
sqlTrue = "(1=1)"
sqlFalse = "(1=0)"
)
type expr struct {
sql string
args []interface{}
}
// Expr builds an expression from a SQL fragment and arguments.
//
// Ex:
// Expr("FROM_UNIXTIME(?)", t)
func Expr(sql string, args ...interface{}) Sqlizer {
return expr{sql: sql, args: args}
}
func (e expr) ToSql() (sql string, args []interface{}, err error) {
simple := true
for _, arg := range e.args {
if _, ok := arg.(Sqlizer); ok {
simple = false
}
}
if simple {
return e.sql, e.args, nil
}
buf := &bytes.Buffer{}
ap := e.args
sp := e.sql
var isql string
var iargs []interface{}
for err == nil && len(ap) > 0 && len(sp) > 0 {
i := strings.Index(sp, "?")
if i < 0 {
// no more placeholders
break
}
if len(sp) > i+1 && sp[i+1:i+2] == "?" {
// escaped "??"; append it and step past
buf.WriteString(sp[:i+2])
sp = sp[i+2:]
continue
}
if as, ok := ap[0].(Sqlizer); ok {
// sqlizer argument; expand it and append the result
isql, iargs, err = as.ToSql()
buf.WriteString(sp[:i])
buf.WriteString(isql)
args = append(args, iargs...)
} else {
// normal argument; append it and the placeholder
buf.WriteString(sp[:i+1])
args = append(args, ap[0])
}
// step past the argument and placeholder
ap = ap[1:]
sp = sp[i+1:]
}
// append the remaining sql and arguments
buf.WriteString(sp)
return buf.String(), append(args, ap...), err
}
type concatExpr []interface{}
func (ce concatExpr) ToSql() (sql string, args []interface{}, err error) {
for _, part := range ce {
switch p := part.(type) {
case string:
sql += p
case Sqlizer:
pSql, pArgs, err := p.ToSql()
if err != nil {
return "", nil, err
}
sql += pSql
args = append(args, pArgs...)
default:
return "", nil, fmt.Errorf("%#v is not a string or Sqlizer", part)
}
}
return
}
// ConcatExpr builds an expression by concatenating strings and other expressions.
//
// Ex:
// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName)
// ConcatExpr("COALESCE(full_name,", name_expr, ")")
func ConcatExpr(parts ...interface{}) concatExpr {
return concatExpr(parts)
}
// aliasExpr helps to alias part of SQL query generated with underlying "expr"
type aliasExpr struct {
expr Sqlizer
alias string
}
// Alias allows to define alias for column in SelectBuilder. Useful when column is
// defined as complex expression like IF or CASE
// Ex:
// .Column(Alias(caseStmt, "case_column"))
func Alias(expr Sqlizer, alias string) aliasExpr {
return aliasExpr{expr, alias}
}
func (e aliasExpr) ToSql() (sql string, args []interface{}, err error) {
sql, args, err = e.expr.ToSql()
if err == nil {
sql = fmt.Sprintf("(%s) AS %s", sql, e.alias)
}
return
}
// Eq is syntactic sugar for use with Where/Having/Set methods.
type Eq map[string]interface{}
func (eq Eq) toSQL(useNotOpr bool) (sql string, args []interface{}, err error) {
if len(eq) == 0 {
// Empty Sql{} evaluates to true.
sql = sqlTrue
return
}
var (
exprs []string
equalOpr = "="
inOpr = "IN"
nullOpr = "IS"
inEmptyExpr = sqlFalse
)
if useNotOpr {
equalOpr = "<>"
inOpr = "NOT IN"
nullOpr = "IS NOT"
inEmptyExpr = sqlTrue
}
sortedKeys := getSortedKeys(eq)
for _, key := range sortedKeys {
var expr string
val := eq[key]
switch v := val.(type) {
case driver.Valuer:
if val, err = v.Value(); err != nil {
return
}
}
r := reflect.ValueOf(val)
if r.Kind() == reflect.Ptr {
if r.IsNil() {
val = nil
} else {
val = r.Elem().Interface()
}
}
if val == nil {
expr = fmt.Sprintf("%s %s NULL", key, nullOpr)
} else {
if isListType(val) {
valVal := reflect.ValueOf(val)
if valVal.Len() == 0 {
expr = inEmptyExpr
if args == nil {
args = []interface{}{}
}
} else {
for i := 0; i < valVal.Len(); i++ {
args = append(args, valVal.Index(i).Interface())
}
expr = fmt.Sprintf("%s %s (%s)", key, inOpr, Placeholders(valVal.Len()))
}
} else {
expr = fmt.Sprintf("%s %s ?", key, equalOpr)
args = append(args, val)
}
}
exprs = append(exprs, expr)
}
sql = strings.Join(exprs, " AND ")
return
}
func (eq Eq) ToSql() (sql string, args []interface{}, err error) {
return eq.toSQL(false)
}
// NotEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
// .Where(NotEq{"id": 1}) == "id <> 1"
type NotEq Eq
func (neq NotEq) ToSql() (sql string, args []interface{}, err error) {
return Eq(neq).toSQL(true)
}
// Like is syntactic sugar for use with LIKE conditions.
// Ex:
// .Where(Like{"name": "%irrel"})
type Like map[string]interface{}
func (lk Like) toSql(opr string) (sql string, args []interface{}, err error) {
var exprs []string
for key, val := range lk {
expr := ""
switch v := val.(type) {
case driver.Valuer:
if val, err = v.Value(); err != nil {
return
}
}
if val == nil {
err = fmt.Errorf("cannot use null with like operators")
return
} else {
if isListType(val) {
err = fmt.Errorf("cannot use array or slice with like operators")
return
} else {
expr = fmt.Sprintf("%s %s ?", key, opr)
args = append(args, val)
}
}
exprs = append(exprs, expr)
}
sql = strings.Join(exprs, " AND ")
return
}
func (lk Like) ToSql() (sql string, args []interface{}, err error) {
return lk.toSql("LIKE")
}
// NotLike is syntactic sugar for use with LIKE conditions.
// Ex:
// .Where(NotLike{"name": "%irrel"})
type NotLike Like
func (nlk NotLike) ToSql() (sql string, args []interface{}, err error) {
return Like(nlk).toSql("NOT LIKE")
}
// ILike is syntactic sugar for use with ILIKE conditions.
// Ex:
// .Where(ILike{"name": "sq%"})
type ILike Like
func (ilk ILike) ToSql() (sql string, args []interface{}, err error) {
return Like(ilk).toSql("ILIKE")
}
// NotILike is syntactic sugar for use with ILIKE conditions.
// Ex:
// .Where(NotILike{"name": "sq%"})
type NotILike Like
func (nilk NotILike) ToSql() (sql string, args []interface{}, err error) {
return Like(nilk).toSql("NOT ILIKE")
}
// Lt is syntactic sugar for use with Where/Having/Set methods.
// Ex:
// .Where(Lt{"id": 1})
type Lt map[string]interface{}
func (lt Lt) toSql(opposite, orEq bool) (sql string, args []interface{}, err error) {
var (
exprs []string
opr = "<"
)
if opposite {
opr = ">"
}
if orEq {
opr = fmt.Sprintf("%s%s", opr, "=")
}
sortedKeys := getSortedKeys(lt)
for _, key := range sortedKeys {
var expr string
val := lt[key]
switch v := val.(type) {
case driver.Valuer:
if val, err = v.Value(); err != nil {
return
}
}
if val == nil {
err = fmt.Errorf("cannot use null with less than or greater than operators")
return
}
if isListType(val) {
err = fmt.Errorf("cannot use array or slice with less than or greater than operators")
return
}
expr = fmt.Sprintf("%s %s ?", key, opr)
args = append(args, val)
exprs = append(exprs, expr)
}
sql = strings.Join(exprs, " AND ")
return
}
func (lt Lt) ToSql() (sql string, args []interface{}, err error) {
return lt.toSql(false, false)
}
// LtOrEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
// .Where(LtOrEq{"id": 1}) == "id <= 1"
type LtOrEq Lt
func (ltOrEq LtOrEq) ToSql() (sql string, args []interface{}, err error) {
return Lt(ltOrEq).toSql(false, true)
}
// Gt is syntactic sugar for use with Where/Having/Set methods.
// Ex:
// .Where(Gt{"id": 1}) == "id > 1"
type Gt Lt
func (gt Gt) ToSql() (sql string, args []interface{}, err error) {
return Lt(gt).toSql(true, false)
}
// GtOrEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
// .Where(GtOrEq{"id": 1}) == "id >= 1"
type GtOrEq Lt
func (gtOrEq GtOrEq) ToSql() (sql string, args []interface{}, err error) {
return Lt(gtOrEq).toSql(true, true)
}
type conj []Sqlizer
func (c conj) join(sep, defaultExpr string) (sql string, args []interface{}, err error) {
if len(c) == 0 {
return defaultExpr, []interface{}{}, nil
}
var sqlParts []string
for _, sqlizer := range c {
partSQL, partArgs, err := nestedToSql(sqlizer)
if err != nil {
return "", nil, err
}
if partSQL != "" {
sqlParts = append(sqlParts, partSQL)
args = append(args, partArgs...)
}
}
if len(sqlParts) > 0 {
sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep))
}
return
}
// And conjunction Sqlizers
type And conj
func (a And) ToSql() (string, []interface{}, error) {
return conj(a).join(" AND ", sqlTrue)
}
// Or conjunction Sqlizers
type Or conj
func (o Or) ToSql() (string, []interface{}, error) {
return conj(o).join(" OR ", sqlFalse)
}
func getSortedKeys(exp map[string]interface{}) []string {
sortedKeys := make([]string, 0, len(exp))
for k := range exp {
sortedKeys = append(sortedKeys, k)
}
sort.Strings(sortedKeys)
return sortedKeys
}
func isListType(val interface{}) bool {
if driver.IsValue(val) {
return false
}
valVal := reflect.ValueOf(val)
return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice
}
-298
View File
@@ -1,298 +0,0 @@
package squirrel
import (
"bytes"
"database/sql"
"errors"
"fmt"
"io"
"sort"
"strings"
"github.com/lann/builder"
)
type insertData struct {
PlaceholderFormat PlaceholderFormat
RunWith BaseRunner
Prefixes []Sqlizer
StatementKeyword string
Options []string
Into string
Columns []string
Values [][]interface{}
Suffixes []Sqlizer
Select *SelectBuilder
}
func (d *insertData) Exec() (sql.Result, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
return ExecWith(d.RunWith, d)
}
func (d *insertData) Query() (*sql.Rows, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
return QueryWith(d.RunWith, d)
}
func (d *insertData) QueryRow() RowScanner {
if d.RunWith == nil {
return &Row{err: RunnerNotSet}
}
queryRower, ok := d.RunWith.(QueryRower)
if !ok {
return &Row{err: RunnerNotQueryRunner}
}
return QueryRowWith(queryRower, d)
}
func (d *insertData) ToSql() (sqlStr string, args []interface{}, err error) {
if len(d.Into) == 0 {
err = errors.New("insert statements must specify a table")
return
}
if len(d.Values) == 0 && d.Select == nil {
err = errors.New("insert statements must have at least one set of values or select clause")
return
}
sql := &bytes.Buffer{}
if len(d.Prefixes) > 0 {
args, err = appendToSql(d.Prefixes, sql, " ", args)
if err != nil {
return
}
sql.WriteString(" ")
}
if d.StatementKeyword == "" {
sql.WriteString("INSERT ")
} else {
sql.WriteString(d.StatementKeyword)
sql.WriteString(" ")
}
if len(d.Options) > 0 {
sql.WriteString(strings.Join(d.Options, " "))
sql.WriteString(" ")
}
sql.WriteString("INTO ")
sql.WriteString(d.Into)
sql.WriteString(" ")
if len(d.Columns) > 0 {
sql.WriteString("(")
sql.WriteString(strings.Join(d.Columns, ","))
sql.WriteString(") ")
}
if d.Select != nil {
args, err = d.appendSelectToSQL(sql, args)
} else {
args, err = d.appendValuesToSQL(sql, args)
}
if err != nil {
return
}
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
}
func (d *insertData) appendValuesToSQL(w io.Writer, args []interface{}) ([]interface{}, error) {
if len(d.Values) == 0 {
return args, errors.New("values for insert statements are not set")
}
io.WriteString(w, "VALUES ")
valuesStrings := make([]string, len(d.Values))
for r, row := range d.Values {
valueStrings := make([]string, len(row))
for v, val := range row {
if vs, ok := val.(Sqlizer); ok {
vsql, vargs, err := vs.ToSql()
if err != nil {
return nil, err
}
valueStrings[v] = vsql
args = append(args, vargs...)
} else {
valueStrings[v] = "?"
args = append(args, val)
}
}
valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ","))
}
io.WriteString(w, strings.Join(valuesStrings, ","))
return args, nil
}
func (d *insertData) appendSelectToSQL(w io.Writer, args []interface{}) ([]interface{}, error) {
if d.Select == nil {
return args, errors.New("select clause for insert statements are not set")
}
selectClause, sArgs, err := d.Select.ToSql()
if err != nil {
return args, err
}
io.WriteString(w, selectClause)
args = append(args, sArgs...)
return args, nil
}
// Builder
// InsertBuilder builds SQL INSERT statements.
type InsertBuilder builder.Builder
func init() {
builder.Register(InsertBuilder{}, insertData{})
}
// Format methods
// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the
// query.
func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder {
return builder.Set(b, "PlaceholderFormat", f).(InsertBuilder)
}
// Runner methods
// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec.
func (b InsertBuilder) RunWith(runner BaseRunner) InsertBuilder {
return setRunWith(b, runner).(InsertBuilder)
}
// Exec builds and Execs the query with the Runner set by RunWith.
func (b InsertBuilder) Exec() (sql.Result, error) {
data := builder.GetStruct(b).(insertData)
return data.Exec()
}
// Query builds and Querys the query with the Runner set by RunWith.
func (b InsertBuilder) Query() (*sql.Rows, error) {
data := builder.GetStruct(b).(insertData)
return data.Query()
}
// QueryRow builds and QueryRows the query with the Runner set by RunWith.
func (b InsertBuilder) QueryRow() RowScanner {
data := builder.GetStruct(b).(insertData)
return data.QueryRow()
}
// Scan is a shortcut for QueryRow().Scan.
func (b InsertBuilder) Scan(dest ...interface{}) error {
return b.QueryRow().Scan(dest...)
}
// SQL methods
// ToSql builds the query into a SQL string and bound args.
func (b InsertBuilder) ToSql() (string, []interface{}, error) {
data := builder.GetStruct(b).(insertData)
return data.ToSql()
}
// MustSql builds the query into a SQL string and bound args.
// It panics if there are any errors.
func (b InsertBuilder) 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 InsertBuilder) Prefix(sql string, args ...interface{}) InsertBuilder {
return b.PrefixExpr(Expr(sql, args...))
}
// PrefixExpr adds an expression to the very beginning of the query
func (b InsertBuilder) PrefixExpr(expr Sqlizer) InsertBuilder {
return builder.Append(b, "Prefixes", expr).(InsertBuilder)
}
// Options adds keyword options before the INTO clause of the query.
func (b InsertBuilder) Options(options ...string) InsertBuilder {
return builder.Extend(b, "Options", options).(InsertBuilder)
}
// Into sets the INTO clause of the query.
func (b InsertBuilder) Into(from string) InsertBuilder {
return builder.Set(b, "Into", from).(InsertBuilder)
}
// Columns adds insert columns to the query.
func (b InsertBuilder) Columns(columns ...string) InsertBuilder {
return builder.Extend(b, "Columns", columns).(InsertBuilder)
}
// Values adds a single row's values to the query.
func (b InsertBuilder) Values(values ...interface{}) InsertBuilder {
return builder.Append(b, "Values", values).(InsertBuilder)
}
// Suffix adds an expression to the end of the query
func (b InsertBuilder) Suffix(sql string, args ...interface{}) InsertBuilder {
return b.SuffixExpr(Expr(sql, args...))
}
// SuffixExpr adds an expression to the end of the query
func (b InsertBuilder) SuffixExpr(expr Sqlizer) InsertBuilder {
return builder.Append(b, "Suffixes", expr).(InsertBuilder)
}
// SetMap set columns and values for insert builder from a map of column name and value
// note that it will reset all previous columns and values was set if any
func (b InsertBuilder) SetMap(clauses map[string]interface{}) InsertBuilder {
// Keep the columns in a consistent order by sorting the column key string.
cols := make([]string, 0, len(clauses))
for col := range clauses {
cols = append(cols, col)
}
sort.Strings(cols)
vals := make([]interface{}, 0, len(clauses))
for _, col := range cols {
vals = append(vals, clauses[col])
}
b = builder.Set(b, "Columns", cols).(InsertBuilder)
b = builder.Set(b, "Values", [][]interface{}{vals}).(InsertBuilder)
return b
}
// Select set Select clause for insert query
// If Values and Select are used, then Select has higher priority
func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder {
return builder.Set(b, "Select", &sb).(InsertBuilder)
}
func (b InsertBuilder) statementKeyword(keyword string) InsertBuilder {
return builder.Set(b, "StatementKeyword", keyword).(InsertBuilder)
}
-69
View File
@@ -1,69 +0,0 @@
// +build go1.8
package squirrel
import (
"context"
"database/sql"
"github.com/lann/builder"
)
func (d *insertData) ExecContext(ctx context.Context) (sql.Result, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
ctxRunner, ok := d.RunWith.(ExecerContext)
if !ok {
return nil, NoContextSupport
}
return ExecContextWith(ctx, ctxRunner, d)
}
func (d *insertData) QueryContext(ctx context.Context) (*sql.Rows, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
ctxRunner, ok := d.RunWith.(QueryerContext)
if !ok {
return nil, NoContextSupport
}
return QueryContextWith(ctx, ctxRunner, d)
}
func (d *insertData) QueryRowContext(ctx context.Context) RowScanner {
if d.RunWith == nil {
return &Row{err: RunnerNotSet}
}
queryRower, ok := d.RunWith.(QueryRowerContext)
if !ok {
if _, ok := d.RunWith.(QueryerContext); !ok {
return &Row{err: RunnerNotQueryRunner}
}
return &Row{err: NoContextSupport}
}
return QueryRowContextWith(ctx, queryRower, d)
}
// ExecContext builds and ExecContexts the query with the Runner set by RunWith.
func (b InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error) {
data := builder.GetStruct(b).(insertData)
return data.ExecContext(ctx)
}
// QueryContext builds and QueryContexts the query with the Runner set by RunWith.
func (b InsertBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) {
data := builder.GetStruct(b).(insertData)
return data.QueryContext(ctx)
}
// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith.
func (b InsertBuilder) QueryRowContext(ctx context.Context) RowScanner {
data := builder.GetStruct(b).(insertData)
return data.QueryRowContext(ctx)
}
// ScanContext is a shortcut for QueryRowContext().Scan.
func (b InsertBuilder) ScanContext(ctx context.Context, dest ...interface{}) error {
return b.QueryRowContext(ctx).Scan(dest...)
}
-63
View File
@@ -1,63 +0,0 @@
package squirrel
import (
"fmt"
"io"
)
type part struct {
pred interface{}
args []interface{}
}
func newPart(pred interface{}, args ...interface{}) Sqlizer {
return &part{pred, args}
}
func (p part) ToSql() (sql string, args []interface{}, err error) {
switch pred := p.pred.(type) {
case nil:
// no-op
case Sqlizer:
sql, args, err = nestedToSql(pred)
case string:
sql = pred
args = p.args
default:
err = fmt.Errorf("expected string or Sqlizer, not %T", pred)
}
return
}
func nestedToSql(s Sqlizer) (string, []interface{}, error) {
if raw, ok := s.(rawSqlizer); ok {
return raw.toSqlRaw()
} else {
return s.ToSql()
}
}
func appendToSql(parts []Sqlizer, w io.Writer, sep string, args []interface{}) ([]interface{}, error) {
for i, p := range parts {
partSql, partArgs, err := nestedToSql(p)
if err != nil {
return nil, err
} else if len(partSql) == 0 {
continue
}
if i > 0 {
_, err := io.WriteString(w, sep)
if err != nil {
return nil, err
}
}
_, err = io.WriteString(w, partSql)
if err != nil {
return nil, err
}
args = append(args, partArgs...)
}
return args, nil
}
-114
View File
@@ -1,114 +0,0 @@
package squirrel
import (
"bytes"
"fmt"
"strings"
)
// PlaceholderFormat is the interface that wraps the ReplacePlaceholders method.
//
// ReplacePlaceholders takes a SQL statement and replaces each question mark
// placeholder with a (possibly different) SQL placeholder.
type PlaceholderFormat interface {
ReplacePlaceholders(sql string) (string, error)
}
type placeholderDebugger interface {
debugPlaceholder() string
}
var (
// Question is a PlaceholderFormat instance that leaves placeholders as
// question marks.
Question = questionFormat{}
// Dollar is a PlaceholderFormat instance that replaces placeholders with
// dollar-prefixed positional placeholders (e.g. $1, $2, $3).
Dollar = dollarFormat{}
// Colon is a PlaceholderFormat instance that replaces placeholders with
// colon-prefixed positional placeholders (e.g. :1, :2, :3).
Colon = colonFormat{}
// AtP is a PlaceholderFormat instance that replaces placeholders with
// "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3).
AtP = atpFormat{}
)
type questionFormat struct{}
func (questionFormat) ReplacePlaceholders(sql string) (string, error) {
return sql, nil
}
func (questionFormat) debugPlaceholder() string {
return "?"
}
type dollarFormat struct{}
func (dollarFormat) ReplacePlaceholders(sql string) (string, error) {
return replacePositionalPlaceholders(sql, "$")
}
func (dollarFormat) debugPlaceholder() string {
return "$"
}
type colonFormat struct{}
func (colonFormat) ReplacePlaceholders(sql string) (string, error) {
return replacePositionalPlaceholders(sql, ":")
}
func (colonFormat) debugPlaceholder() string {
return ":"
}
type atpFormat struct{}
func (atpFormat) ReplacePlaceholders(sql string) (string, error) {
return replacePositionalPlaceholders(sql, "@p")
}
func (atpFormat) debugPlaceholder() string {
return "@p"
}
// Placeholders returns a string with count ? placeholders joined with commas.
func Placeholders(count int) string {
if count < 1 {
return ""
}
return strings.Repeat(",?", count)[1:]
}
func replacePositionalPlaceholders(sql, prefix string) (string, error) {
buf := &bytes.Buffer{}
i := 0
for {
p := strings.Index(sql, "?")
if p == -1 {
break
}
if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ?
buf.WriteString(sql[:p])
buf.WriteString("?")
if len(sql[p:]) == 1 {
break
}
sql = sql[p+2:]
} else {
i++
buf.WriteString(sql[:p])
fmt.Fprintf(buf, "%s%d", prefix, i)
sql = sql[p+1:]
}
}
buf.WriteString(sql)
return buf.String(), nil
}
-22
View File
@@ -1,22 +0,0 @@
package squirrel
// RowScanner is the interface that wraps the Scan method.
//
// Scan behaves like database/sql.Row.Scan.
type RowScanner interface {
Scan(...interface{}) error
}
// Row wraps database/sql.Row to let squirrel return new errors on Scan.
type Row struct {
RowScanner
err error
}
// Scan returns Row.err or calls RowScanner.Scan.
func (r *Row) Scan(dest ...interface{}) error {
if r.err != nil {
return r.err
}
return r.RowScanner.Scan(dest...)
}
-403
View File
@@ -1,403 +0,0 @@
package squirrel
import (
"bytes"
"database/sql"
"fmt"
"strings"
"github.com/lann/builder"
)
type selectData struct {
PlaceholderFormat PlaceholderFormat
RunWith BaseRunner
Prefixes []Sqlizer
Options []string
Columns []Sqlizer
From Sqlizer
Joins []Sqlizer
WhereParts []Sqlizer
GroupBys []string
HavingParts []Sqlizer
OrderByParts []Sqlizer
Limit string
Offset string
Suffixes []Sqlizer
}
func (d *selectData) Exec() (sql.Result, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
return ExecWith(d.RunWith, d)
}
func (d *selectData) Query() (*sql.Rows, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
return QueryWith(d.RunWith, d)
}
func (d *selectData) QueryRow() RowScanner {
if d.RunWith == nil {
return &Row{err: RunnerNotSet}
}
queryRower, ok := d.RunWith.(QueryRower)
if !ok {
return &Row{err: RunnerNotQueryRunner}
}
return QueryRowWith(queryRower, d)
}
func (d *selectData) ToSql() (sqlStr string, args []interface{}, err error) {
sqlStr, args, err = d.toSqlRaw()
if err != nil {
return
}
sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sqlStr)
return
}
func (d *selectData) toSqlRaw() (sqlStr string, args []interface{}, err error) {
if len(d.Columns) == 0 {
err = fmt.Errorf("select statements must have at least one result column")
return
}
sql := &bytes.Buffer{}
if len(d.Prefixes) > 0 {
args, err = appendToSql(d.Prefixes, sql, " ", args)
if err != nil {
return
}
sql.WriteString(" ")
}
sql.WriteString("SELECT ")
if len(d.Options) > 0 {
sql.WriteString(strings.Join(d.Options, " "))
sql.WriteString(" ")
}
if len(d.Columns) > 0 {
args, err = appendToSql(d.Columns, sql, ", ", args)
if err != nil {
return
}
}
if d.From != nil {
sql.WriteString(" FROM ")
args, err = appendToSql([]Sqlizer{d.From}, sql, "", args)
if err != nil {
return
}
}
if len(d.Joins) > 0 {
sql.WriteString(" ")
args, err = appendToSql(d.Joins, sql, " ", args)
if err != nil {
return
}
}
if len(d.WhereParts) > 0 {
sql.WriteString(" WHERE ")
args, err = appendToSql(d.WhereParts, sql, " AND ", args)
if err != nil {
return
}
}
if len(d.GroupBys) > 0 {
sql.WriteString(" GROUP BY ")
sql.WriteString(strings.Join(d.GroupBys, ", "))
}
if len(d.HavingParts) > 0 {
sql.WriteString(" HAVING ")
args, err = appendToSql(d.HavingParts, sql, " AND ", args)
if err != nil {
return
}
}
if len(d.OrderByParts) > 0 {
sql.WriteString(" ORDER BY ")
args, err = appendToSql(d.OrderByParts, sql, ", ", args)
if err != nil {
return
}
}
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 = sql.String()
return
}
// Builder
// SelectBuilder builds SQL SELECT statements.
type SelectBuilder builder.Builder
func init() {
builder.Register(SelectBuilder{}, selectData{})
}
// Format methods
// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the
// query.
func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder {
return builder.Set(b, "PlaceholderFormat", f).(SelectBuilder)
}
// Runner methods
// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec.
// For most cases runner will be a database connection.
//
// Internally we use this to mock out the database connection for testing.
func (b SelectBuilder) RunWith(runner BaseRunner) SelectBuilder {
return setRunWith(b, runner).(SelectBuilder)
}
// Exec builds and Execs the query with the Runner set by RunWith.
func (b SelectBuilder) Exec() (sql.Result, error) {
data := builder.GetStruct(b).(selectData)
return data.Exec()
}
// Query builds and Querys the query with the Runner set by RunWith.
func (b SelectBuilder) Query() (*sql.Rows, error) {
data := builder.GetStruct(b).(selectData)
return data.Query()
}
// QueryRow builds and QueryRows the query with the Runner set by RunWith.
func (b SelectBuilder) QueryRow() RowScanner {
data := builder.GetStruct(b).(selectData)
return data.QueryRow()
}
// Scan is a shortcut for QueryRow().Scan.
func (b SelectBuilder) Scan(dest ...interface{}) error {
return b.QueryRow().Scan(dest...)
}
// SQL methods
// ToSql builds the query into a SQL string and bound args.
func (b SelectBuilder) ToSql() (string, []interface{}, error) {
data := builder.GetStruct(b).(selectData)
return data.ToSql()
}
func (b SelectBuilder) toSqlRaw() (string, []interface{}, error) {
data := builder.GetStruct(b).(selectData)
return data.toSqlRaw()
}
// MustSql builds the query into a SQL string and bound args.
// It panics if there are any errors.
func (b SelectBuilder) 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 SelectBuilder) Prefix(sql string, args ...interface{}) SelectBuilder {
return b.PrefixExpr(Expr(sql, args...))
}
// PrefixExpr adds an expression to the very beginning of the query
func (b SelectBuilder) PrefixExpr(expr Sqlizer) SelectBuilder {
return builder.Append(b, "Prefixes", expr).(SelectBuilder)
}
// Distinct adds a DISTINCT clause to the query.
func (b SelectBuilder) Distinct() SelectBuilder {
return b.Options("DISTINCT")
}
// Options adds select option to the query
func (b SelectBuilder) Options(options ...string) SelectBuilder {
return builder.Extend(b, "Options", options).(SelectBuilder)
}
// Columns adds result columns to the query.
func (b SelectBuilder) Columns(columns ...string) SelectBuilder {
parts := make([]interface{}, 0, len(columns))
for _, str := range columns {
parts = append(parts, newPart(str))
}
return builder.Extend(b, "Columns", parts).(SelectBuilder)
}
// RemoveColumns remove all columns from query.
// Must add a new column with Column or Columns methods, otherwise
// return a error.
func (b SelectBuilder) RemoveColumns() SelectBuilder {
return builder.Delete(b, "Columns").(SelectBuilder)
}
// Column adds a result column to the query.
// Unlike Columns, Column accepts args which will be bound to placeholders in
// the columns string, for example:
// Column("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)
func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBuilder {
return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder)
}
// From sets the FROM clause of the query.
func (b SelectBuilder) From(from string) SelectBuilder {
return builder.Set(b, "From", newPart(from)).(SelectBuilder)
}
// FromSelect sets a subquery into the FROM clause of the query.
func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder {
// Prevent misnumbered parameters in nested selects (#183).
from = from.PlaceholderFormat(Question)
return builder.Set(b, "From", Alias(from, alias)).(SelectBuilder)
}
// JoinClause adds a join clause to the query.
func (b SelectBuilder) JoinClause(pred interface{}, args ...interface{}) SelectBuilder {
return builder.Append(b, "Joins", newPart(pred, args...)).(SelectBuilder)
}
// Join adds a JOIN clause to the query.
func (b SelectBuilder) Join(join string, rest ...interface{}) SelectBuilder {
return b.JoinClause("JOIN "+join, rest...)
}
// LeftJoin adds a LEFT JOIN clause to the query.
func (b SelectBuilder) LeftJoin(join string, rest ...interface{}) SelectBuilder {
return b.JoinClause("LEFT JOIN "+join, rest...)
}
// RightJoin adds a RIGHT JOIN clause to the query.
func (b SelectBuilder) RightJoin(join string, rest ...interface{}) SelectBuilder {
return b.JoinClause("RIGHT JOIN "+join, rest...)
}
// InnerJoin adds a INNER JOIN clause to the query.
func (b SelectBuilder) InnerJoin(join string, rest ...interface{}) SelectBuilder {
return b.JoinClause("INNER JOIN "+join, rest...)
}
// CrossJoin adds a CROSS JOIN clause to the query.
func (b SelectBuilder) CrossJoin(join string, rest ...interface{}) SelectBuilder {
return b.JoinClause("CROSS JOIN "+join, rest...)
}
// Where adds an expression to the WHERE clause of the query.
//
// Expressions are ANDed together in the generated SQL.
//
// Where accepts several types for its pred argument:
//
// nil OR "" - ignored.
//
// string - SQL expression.
// If the expression has SQL placeholders then a set of arguments must be passed
// as well, one for each placeholder.
//
// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is
// transformed into an expression like "<key> = ?", with the corresponding value
// bound to the placeholder. If the value is nil, the expression will be "<key>
// IS NULL". If the value is an array or slice, the expression will be "<key> IN
// (?,?,...)", with one placeholder for each item in the value. These expressions
// are ANDed together.
//
// Where will panic if pred isn't any of the above types.
func (b SelectBuilder) Where(pred interface{}, args ...interface{}) SelectBuilder {
if pred == nil || pred == "" {
return b
}
return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(SelectBuilder)
}
// GroupBy adds GROUP BY expressions to the query.
func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder {
return builder.Extend(b, "GroupBys", groupBys).(SelectBuilder)
}
// Having adds an expression to the HAVING clause of the query.
//
// See Where.
func (b SelectBuilder) Having(pred interface{}, rest ...interface{}) SelectBuilder {
return builder.Append(b, "HavingParts", newWherePart(pred, rest...)).(SelectBuilder)
}
// OrderByClause adds ORDER BY clause to the query.
func (b SelectBuilder) OrderByClause(pred interface{}, args ...interface{}) SelectBuilder {
return builder.Append(b, "OrderByParts", newPart(pred, args...)).(SelectBuilder)
}
// OrderBy adds ORDER BY expressions to the query.
func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder {
for _, orderBy := range orderBys {
b = b.OrderByClause(orderBy)
}
return b
}
// Limit sets a LIMIT clause on the query.
func (b SelectBuilder) Limit(limit uint64) SelectBuilder {
return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(SelectBuilder)
}
// Limit ALL allows to access all records with limit
func (b SelectBuilder) RemoveLimit() SelectBuilder {
return builder.Delete(b, "Limit").(SelectBuilder)
}
// Offset sets a OFFSET clause on the query.
func (b SelectBuilder) Offset(offset uint64) SelectBuilder {
return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(SelectBuilder)
}
// RemoveOffset removes OFFSET clause.
func (b SelectBuilder) RemoveOffset() SelectBuilder {
return builder.Delete(b, "Offset").(SelectBuilder)
}
// Suffix adds an expression to the end of the query
func (b SelectBuilder) Suffix(sql string, args ...interface{}) SelectBuilder {
return b.SuffixExpr(Expr(sql, args...))
}
// SuffixExpr adds an expression to the end of the query
func (b SelectBuilder) SuffixExpr(expr Sqlizer) SelectBuilder {
return builder.Append(b, "Suffixes", expr).(SelectBuilder)
}
Loaded 100 of 2821 files, more files were not shown because too many files have changed in this diff. Show more