Compare commits
No files matched your search
@@ -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
|
||||||
+3
-29
@@ -1,29 +1,3 @@
|
|||||||
docker-build:
|
include:
|
||||||
image: docker:latest
|
- project: '$CI_PROJECT_PATH'
|
||||||
stage: build
|
file: '/ci-isp-go-service.yml'
|
||||||
services:
|
|
||||||
- docker:dind
|
|
||||||
before_script:
|
|
||||||
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
|
|
||||||
script:
|
|
||||||
- set
|
|
||||||
- docker build -f Dockerfile.dit --force-rm --pull -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .
|
|
||||||
- |
|
|
||||||
if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
|
|
||||||
tag=""
|
|
||||||
echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = ':latest'"
|
|
||||||
#docker pull "$CI_REGISTRY_IMAGE${tag}"
|
|
||||||
#docker tag "$CI_REGISTRY_IMAGE${tag}" "$CI_REGISTRY_IMAGE:pre"
|
|
||||||
#docker rmi "$CI_REGISTRY_IMAGE${tag}"
|
|
||||||
#docker push "$CI_REGISTRY_IMAGE:pre"
|
|
||||||
#docker rmi -f "$CI_REGISTRY_IMAGE:pre"
|
|
||||||
docker tag "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" "$CI_REGISTRY_IMAGE${tag}"
|
|
||||||
docker rmi "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
|
|
||||||
docker push "$CI_REGISTRY_IMAGE${tag}"
|
|
||||||
docker rmi -f "$CI_REGISTRY_IMAGE${tag}"
|
|
||||||
else
|
|
||||||
tag=":$CI_COMMIT_BRANCH"
|
|
||||||
echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag"
|
|
||||||
fi
|
|
||||||
after_script:
|
|
||||||
- docker logout $CI_REGISTRY
|
|
||||||
+65
-65
@@ -1,69 +1,69 @@
|
|||||||
|
version: "2"
|
||||||
run:
|
run:
|
||||||
timeout: 2m
|
allow-parallel-runners: true
|
||||||
|
|
||||||
linters:
|
linters:
|
||||||
disable-all: true
|
default: all
|
||||||
|
disable:
|
||||||
|
- contextcheck # не имеет смысла
|
||||||
|
- depguard # не всегда имеет смысл
|
||||||
|
- dupword # не имеет смысла
|
||||||
|
- exhaustruct # не имеет смысла
|
||||||
|
- godot # не актуально для swagger
|
||||||
|
- godox # не позволяет оставлять todo
|
||||||
|
- musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур
|
||||||
|
- nlreturn # не всегда имеет смысл
|
||||||
|
- nolintlint # Goland все равно форматирует с отступом
|
||||||
|
- perfsprint # мнимая производительность в угоду читаемости
|
||||||
|
- tagalign # не всегда имеет смысл
|
||||||
|
- varnamelen # очень индивидуально (db)
|
||||||
|
- wsl # расставление пробелов очень индивидуально
|
||||||
|
- wsl_v5 # расставление пробелов очень индивидуально
|
||||||
|
settings:
|
||||||
|
cyclop:
|
||||||
|
max-complexity: 15 # по умолчанию 10 мало
|
||||||
|
funlen:
|
||||||
|
lines: 80
|
||||||
|
lll:
|
||||||
|
line-length: 150
|
||||||
|
revive:
|
||||||
|
rules:
|
||||||
|
- name: var-naming # отключаем Id -> ID
|
||||||
|
disabled: true
|
||||||
|
staticcheck:
|
||||||
|
checks: # отключаем Id -> ID
|
||||||
|
- -ST1000
|
||||||
|
- -ST1016
|
||||||
|
- -ST1020
|
||||||
|
- -ST1021
|
||||||
|
- -ST1022
|
||||||
|
testifylint:
|
||||||
|
disable:
|
||||||
|
- compares
|
||||||
|
- equal-values
|
||||||
|
exclusions:
|
||||||
|
generated: lax
|
||||||
|
presets:
|
||||||
|
- comments
|
||||||
|
- common-false-positives
|
||||||
|
- legacy
|
||||||
|
- std-error-handling
|
||||||
|
rules:
|
||||||
|
- linters:
|
||||||
|
- wrapcheck
|
||||||
|
path: controller # достаточное кол-во контекста на уровне контроллеров
|
||||||
|
- linters:
|
||||||
|
- wrapcheck
|
||||||
|
path: transaction # транзакции прозрачны
|
||||||
|
paths:
|
||||||
|
- third_party$
|
||||||
|
- builtin$
|
||||||
|
- examples$
|
||||||
|
formatters:
|
||||||
enable:
|
enable:
|
||||||
- asciicheck
|
|
||||||
- bodyclose
|
|
||||||
- deadcode
|
|
||||||
- dogsled
|
|
||||||
- errcheck
|
|
||||||
- funlen
|
|
||||||
- goconst
|
|
||||||
- gocritic
|
|
||||||
- gocyclo
|
|
||||||
- gofmt
|
- gofmt
|
||||||
- gomnd
|
exclusions:
|
||||||
- goprintffuncname
|
generated: lax
|
||||||
- gosimple
|
paths:
|
||||||
- govet
|
- third_party$
|
||||||
- nakedret
|
- builtin$
|
||||||
- nestif
|
- examples$
|
||||||
- nolintlint
|
|
||||||
- prealloc
|
|
||||||
- rowserrcheck
|
|
||||||
- staticcheck
|
|
||||||
- structcheck
|
|
||||||
- typecheck
|
|
||||||
- unconvert
|
|
||||||
- unparam
|
|
||||||
- unused
|
|
||||||
- varcheck
|
|
||||||
- gosec
|
|
||||||
- misspell
|
|
||||||
- whitespace
|
|
||||||
- exhaustive #смотрит на соответствие между элементами enum и swich кейсами
|
|
||||||
- exportloopref #for _,p := []int{1, 2, 3} { s.Bar(&p) /* If s stores the pointer, it will be bug.*/ }
|
|
||||||
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
|
|
||||||
linters-settings:
|
|
||||||
funlen:
|
|
||||||
lines: 80
|
|
||||||
statements: 40
|
|
||||||
prealloc:
|
|
||||||
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
|
|
||||||
# True by default.
|
|
||||||
simple: true
|
|
||||||
range-loops: true # Report preallocation suggestions on range loops, true by default
|
|
||||||
for-loops: true # Report preallocation suggestions on for loops, false by default
|
|
||||||
gocritic:
|
|
||||||
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
|
|
||||||
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
|
|
||||||
enabled-tags:
|
|
||||||
- diagnostic
|
|
||||||
- performance
|
|
||||||
disabled-checks:
|
|
||||||
- hugeParam
|
|
||||||
- rangeValCopy
|
|
||||||
- ifElseChain
|
|
||||||
exhaustive:
|
|
||||||
default-signifies-exhaustive: true
|
|
||||||
|
|
||||||
issues:
|
|
||||||
exclude-rules:
|
|
||||||
- path: _test\.go # to exclude all test files for linter errcheck
|
|
||||||
linters:
|
|
||||||
- errcheck
|
|
||||||
- linters:
|
|
||||||
- gosec
|
|
||||||
text: "G101:"
|
|
||||||
@@ -1,3 +1,51 @@
|
|||||||
|
### v6.0.0
|
||||||
|
* Удалены таблицы `domain` и `system`
|
||||||
|
* Удалены `deprecated` endpoint'ы
|
||||||
|
* Изменены контракты для `application` endpoint'ов
|
||||||
|
* Добавлены `admin` permission к endpoint'ам
|
||||||
|
### v5.7.3
|
||||||
|
* обновлены зависимости
|
||||||
|
### v5.7.2
|
||||||
|
* Обновлен isp-kit
|
||||||
|
### v5.7.1
|
||||||
|
* Методы `/access_list/get_by_id`, `/access_list/set_list` теперь возвращают `httpMethod`
|
||||||
|
### v5.7.0
|
||||||
|
* Обновлены зависимости
|
||||||
|
* Добавлено поле `http_method` в `access_list`
|
||||||
|
### v5.6.0
|
||||||
|
* Для endpoint'а `system/secure/authenticate` в ответ добавлено поле `appName` (название приложения)
|
||||||
|
* Обновлена версия `go` до `1.25`
|
||||||
|
* Обновлены зависимости
|
||||||
|
### v5.5.0
|
||||||
|
* Обновлены зависимости
|
||||||
|
### v5.4.0
|
||||||
|
* Добавлен новый endpoint: `/access_list/delete_list` для удаления методов из списка доступов у приложений
|
||||||
|
### v5.3.1
|
||||||
|
* добавлен `Dockerfile` и скрипт для сборки и публикации образа в `GitHub Contaier Registry`
|
||||||
|
* обновлены зависимости
|
||||||
|
### v5.3.0
|
||||||
|
* Добавлен новый endpoint: `/application/get_application_by_token`
|
||||||
|
### v5.2.1
|
||||||
|
* обновлены зависимости
|
||||||
|
### v5.2.0
|
||||||
|
* Обновлены зависимости
|
||||||
|
* Добавлены новые endpoint'ы: `/application/update_application`, `/application/create_application`, `/application_group/create`, `/application_group/update`, `/application_group/delete_list`, `/application_group/get_by_id_list`, `/application_group/get_all`
|
||||||
|
### v5.1.1
|
||||||
|
* обновлены зависимости
|
||||||
|
### v5.1.0
|
||||||
|
* все сервисы (группы приложений) перенесены в домен с id = 1
|
||||||
|
* при создании/изменении сервисов (групп приложений) будет использоваться только домен с id = 1
|
||||||
|
|
||||||
|
### v5.0.0
|
||||||
|
* изменен механизм инициализации токена панели администратора
|
||||||
|
* для механизма инициализации используется поле `baseline.initialAdminUiToken` в конфигурации
|
||||||
|
* если поле не заполнено, механизм не запускается
|
||||||
|
* иначе проверяется существование токена в базе, если токен уже создан, механизм не запускается
|
||||||
|
* иначе создаются все сущности и выпускается бессрочный токен, приложению выдается доступ к методу `admin/auth/login`
|
||||||
|
* механизм запускается при получении конфигурации
|
||||||
|
* при конкурентном запуске модуля, механизм запускается только на одном инстансе
|
||||||
|
* логи механизма маркируются полем "worker": "baseline"
|
||||||
|
* обновлена зависимости
|
||||||
### v4.0.0
|
### v4.0.0
|
||||||
* Удален `InstanceUuid`
|
* Удален `InstanceUuid`
|
||||||
* Удалена интеграция с Redis
|
* Удалена интеграция с Redis
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
FROM dockerhub.mos.ru/golang:1.19-alpine3.16 as builder
|
|
||||||
WORKDIR /build
|
|
||||||
ARG version
|
|
||||||
ENV version_env=$version
|
|
||||||
ARG app_name
|
|
||||||
ENV app_name_env=$app_name
|
|
||||||
COPY . .
|
|
||||||
ENV GOPROXY=https://repo-mirror.mos.ru/repository/go-public
|
|
||||||
RUN go build -ldflags="-X 'main.version=$version_env'" -o /main .
|
|
||||||
|
|
||||||
FROM dockerhub.mos.ru/alpine:3.16.0
|
|
||||||
WORKDIR /app
|
|
||||||
ARG app_name
|
|
||||||
ENV app_name_env=$app_name
|
|
||||||
COPY --from=builder main /app/$app_name_env
|
|
||||||
COPY /conf/config.yml /app/config.yml
|
|
||||||
COPY /conf/default_remote_config.json* /app/default_remote_config.json
|
|
||||||
COPY /migrations /app/migrations
|
|
||||||
ENTRYPOINT /app/$app_name_env
|
|
||||||
+25
-23
@@ -3,16 +3,18 @@ package assembly
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/integration-system/isp-kit/app"
|
"github.com/txix-open/isp-kit/rc"
|
||||||
"github.com/integration-system/isp-kit/bootstrap"
|
|
||||||
"github.com/integration-system/isp-kit/cluster"
|
|
||||||
"github.com/integration-system/isp-kit/dbrx"
|
|
||||||
"github.com/integration-system/isp-kit/dbx"
|
|
||||||
"github.com/integration-system/isp-kit/grpc"
|
|
||||||
"github.com/integration-system/isp-kit/log"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/conf"
|
"isp-system-service/conf"
|
||||||
"isp-system-service/migrations"
|
|
||||||
|
"github.com/txix-open/isp-kit/app"
|
||||||
|
"github.com/txix-open/isp-kit/bootstrap"
|
||||||
|
"github.com/txix-open/isp-kit/cluster"
|
||||||
|
"github.com/txix-open/isp-kit/dbrx"
|
||||||
|
"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/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Assembly struct {
|
type Assembly struct {
|
||||||
@@ -23,39 +25,39 @@ type Assembly struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||||
dbCli := dbrx.New(dbx.WithMigration(boot.MigrationsDir))
|
logger := boot.App.Logger()
|
||||||
|
dbCli := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, logger))
|
||||||
server := grpc.NewServer()
|
server := grpc.NewServer()
|
||||||
|
|
||||||
return &Assembly{
|
return &Assembly{
|
||||||
boot: boot,
|
boot: boot,
|
||||||
db: dbCli,
|
db: dbCli,
|
||||||
server: server,
|
server: server,
|
||||||
logger: boot.App.Logger(),
|
logger: logger,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
|
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
|
||||||
var (
|
newCfg, _, err := rc.Upgrade[conf.Remote](a.boot.RemoteConfig, remoteConfig)
|
||||||
newCfg conf.Remote
|
|
||||||
prevCfg conf.Remote
|
|
||||||
)
|
|
||||||
err := a.boot.RemoteConfig.Upgrade(remoteConfig, &newCfg, &prevCfg)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade remote config"))
|
a.boot.Fatal(errors.WithMessage(err, "upgrade remote config"))
|
||||||
}
|
}
|
||||||
|
|
||||||
migrations.Initialize.SetParams(a.boot.MigrationsDir, newCfg.Database.Schema)
|
|
||||||
|
|
||||||
a.logger.SetLevel(newCfg.LogLevel)
|
a.logger.SetLevel(newCfg.LogLevel)
|
||||||
|
|
||||||
err = a.db.Upgrade(ctx, newCfg.Database)
|
err = a.db.Upgrade(ctx, newCfg.Database)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"), log.Any("config", newCfg.Database))
|
a.boot.Fatal(errors.WithMessage(err, "upgrade db client"))
|
||||||
}
|
}
|
||||||
|
|
||||||
locator := NewLocator(a.db, a.logger)
|
locator := NewLocator(a.db, a.logger)
|
||||||
handler := locator.Handler(newCfg)
|
config := locator.Config(newCfg)
|
||||||
a.server.Upgrade(handler)
|
|
||||||
|
err = config.Baseline.Do(a.boot.App.Context())
|
||||||
|
if err != nil {
|
||||||
|
a.boot.Fatal(errors.WithMessage(err, "run baseline"))
|
||||||
|
}
|
||||||
|
|
||||||
|
a.server.Upgrade(config.Handler)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-18
@@ -1,17 +1,20 @@
|
|||||||
package assembly
|
package assembly
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/integration-system/isp-kit/db"
|
|
||||||
"github.com/integration-system/isp-kit/grpc/endpoint"
|
|
||||||
"github.com/integration-system/isp-kit/grpc/isp"
|
|
||||||
"github.com/integration-system/isp-kit/log"
|
|
||||||
"isp-system-service/conf"
|
"isp-system-service/conf"
|
||||||
"isp-system-service/controller"
|
"isp-system-service/controller"
|
||||||
"isp-system-service/repository"
|
"isp-system-service/repository"
|
||||||
"isp-system-service/routes"
|
"isp-system-service/routes"
|
||||||
"isp-system-service/service"
|
"isp-system-service/service"
|
||||||
|
"isp-system-service/service/baseline"
|
||||||
"isp-system-service/service/secure"
|
"isp-system-service/service/secure"
|
||||||
"isp-system-service/transaction"
|
"isp-system-service/transaction"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/db"
|
||||||
|
"github.com/txix-open/isp-kit/grpc"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/endpoint/grpclog"
|
||||||
|
"github.com/txix-open/isp-kit/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type DB interface {
|
type DB interface {
|
||||||
@@ -31,41 +34,51 @@ func NewLocator(db DB, logger log.Logger) Locator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
|
type Config struct {
|
||||||
|
Handler *grpc.Mux
|
||||||
|
Baseline baseline.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l Locator) Config(cfg conf.Remote) Config {
|
||||||
txManager := transaction.NewManager(l.db)
|
txManager := transaction.NewManager(l.db)
|
||||||
accessListRep := repository.NewAccessList(l.db)
|
accessListRep := repository.NewAccessList(l.db)
|
||||||
applicationRep := repository.NewApplication(l.db)
|
applicationRep := repository.NewApplication(l.db)
|
||||||
domainRep := repository.NewDomain(l.db)
|
appGroupRep := repository.NewAppGroup(l.db)
|
||||||
serviceRep := repository.NewService(l.db)
|
|
||||||
tokenRep := repository.NewToken(l.db)
|
tokenRep := repository.NewToken(l.db)
|
||||||
|
|
||||||
secureService := secure.NewService(tokenRep, accessListRep)
|
secureService := secure.NewService(tokenRep, accessListRep)
|
||||||
accessListService := service.NewAccessList(txManager, accessListRep, applicationRep)
|
accessListService := service.NewAccessList(txManager, accessListRep, applicationRep)
|
||||||
applicationService := service.NewApplication(txManager, applicationRep, domainRep, serviceRep, tokenRep)
|
applicationService := service.NewApplication(txManager, applicationRep, appGroupRep, tokenRep)
|
||||||
domainService := service.NewDomain(domainRep)
|
|
||||||
serviceService := service.NewService(domainRep, serviceRep)
|
|
||||||
|
|
||||||
jwtService := service.NewTokenSource()
|
jwtService := service.NewTokenSource()
|
||||||
tokenService := service.NewToken(jwtService, applicationService, txManager,
|
tokenService := service.NewToken(
|
||||||
applicationRep, domainRep, serviceRep, tokenRep,
|
jwtService,
|
||||||
|
applicationService,
|
||||||
|
txManager,
|
||||||
|
applicationRep,
|
||||||
|
tokenRep,
|
||||||
)
|
)
|
||||||
|
|
||||||
secureController := controller.NewSecure(secureService)
|
secureController := controller.NewSecure(secureService)
|
||||||
accessListController := controller.NewAccessList(accessListService)
|
accessListController := controller.NewAccessList(accessListService)
|
||||||
applicationController := controller.NewApplication(applicationService)
|
applicationController := controller.NewApplication(applicationService)
|
||||||
domainController := controller.NewDomain(domainService)
|
|
||||||
serviceController := controller.NewService(serviceService)
|
|
||||||
tokenController := controller.NewToken(tokenService)
|
tokenController := controller.NewToken(tokenService)
|
||||||
|
|
||||||
|
appGroupService := service.NewAppGroup(appGroupRep)
|
||||||
|
appGroupController := controller.NewAppGroup(appGroupService)
|
||||||
c := routes.Controllers{
|
c := routes.Controllers{
|
||||||
Secure: secureController,
|
Secure: secureController,
|
||||||
AccessList: accessListController,
|
AccessList: accessListController,
|
||||||
Domain: domainController,
|
|
||||||
Service: serviceController,
|
|
||||||
Application: applicationController,
|
Application: applicationController,
|
||||||
Token: tokenController,
|
Token: tokenController,
|
||||||
|
AppGroup: appGroupController,
|
||||||
}
|
}
|
||||||
mapper := endpoint.DefaultWrapper(l.logger, endpoint.BodyLogger(l.logger))
|
mapper := endpoint.DefaultWrapper(l.logger, grpclog.Log(l.logger, true))
|
||||||
server := routes.Handler(mapper, c)
|
server := routes.Handler(mapper, c)
|
||||||
return server
|
|
||||||
|
baselineService := baseline.NewService(cfg.Baseline, txManager, l.logger)
|
||||||
|
return Config{
|
||||||
|
Handler: server,
|
||||||
|
Baseline: baselineService,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,5 +7,8 @@
|
|||||||
"username": "{{ msp_pgsql_user }}",
|
"username": "{{ msp_pgsql_user }}",
|
||||||
"host": "{{ msp_pgsql_address }}",
|
"host": "{{ msp_pgsql_address }}",
|
||||||
"port": 5432
|
"port": 5432
|
||||||
|
},
|
||||||
|
"baseline": {
|
||||||
|
"initialAdminUiToken": "{{ isp_service_admin_token }}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+13
-7
@@ -3,20 +3,26 @@ package conf
|
|||||||
import (
|
import (
|
||||||
"reflect"
|
"reflect"
|
||||||
|
|
||||||
"github.com/integration-system/isp-kit/dbx"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
"github.com/integration-system/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
"github.com/integration-system/isp-kit/rc/schema"
|
"github.com/txix-open/isp-kit/rc/schema"
|
||||||
"github.com/integration-system/jsonschema"
|
"github.com/txix-open/jsonschema"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//nolint:gochecknoinits
|
||||||
func init() {
|
func init() {
|
||||||
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Type) {
|
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
|
||||||
t.Type = "string"
|
t.Type = "string"
|
||||||
t.Enum = []interface{}{"debug", "info", "error", "fatal"}
|
t.Enum = []any{"debug", "info", "error", "fatal"}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
type Remote struct {
|
type Remote struct {
|
||||||
Database dbx.Config `schema:"Настройка базы данных"`
|
Database dbx.Config `schema:"Настройка базы данных"`
|
||||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
Baseline Baseline
|
||||||
|
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Baseline struct {
|
||||||
|
InitialAdminUiToken string
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package conf_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"isp-system-service/conf"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/test/rct"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDefaultRemoteConfig(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
rct.Test(t, "default_remote_config.json", conf.Remote{})
|
||||||
|
}
|
||||||
+112
-36
@@ -2,17 +2,21 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AccessListService interface {
|
type AccessListService interface {
|
||||||
GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error)
|
GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error)
|
||||||
SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error)
|
SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error)
|
||||||
SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error)
|
SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error)
|
||||||
|
DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error
|
||||||
|
DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type AccessList struct {
|
type AccessList struct {
|
||||||
@@ -26,21 +30,27 @@ func NewAccessList(service AccessListService) AccessList {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetById godoc
|
// GetById godoc
|
||||||
// @Tags accessList
|
//
|
||||||
// @Summary Получить список доступности методов для приложения
|
// @Tags accessList
|
||||||
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
|
// @Summary Получить список доступности методов для приложения
|
||||||
// @Accept json
|
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.Identity false "идентификатор приложения"
|
// @Produce json
|
||||||
// @Success 200 {array} domain.MethodInfo "список доступности методов"
|
// @Param body body domain.Identity false "идентификатор приложения"
|
||||||
// @Failure 404 {object} domain.GrpcError
|
// @Success 200 {array} domain.MethodInfo "список доступности методов"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 404 {object} apierrors.Error
|
||||||
// @Router /access_list/get_by_id [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /access_list/get_by_id [POST]
|
||||||
func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.MethodInfo, error) {
|
func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.MethodInfo, error) {
|
||||||
result, err := c.service.GetById(ctx, req.Id)
|
result, err := c.service.GetById(ctx, req.Id)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
return nil, status.Errorf(codes.NotFound, "application not found")
|
return nil, apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with id %d not found", req.Id),
|
||||||
|
err,
|
||||||
|
)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, err
|
return nil, err
|
||||||
default:
|
default:
|
||||||
@@ -49,21 +59,27 @@ func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetOne godoc
|
// SetOne godoc
|
||||||
// @Tags accessList
|
//
|
||||||
// @Summary Настроить доступность метода для приложения
|
// @Tags accessList
|
||||||
// @Description Возвращает количество измененных строк
|
// @Summary Настроить доступность метода для приложения
|
||||||
// @Accept json
|
// @Description Возвращает количество измененных строк
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа"
|
// @Produce json
|
||||||
// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк"
|
// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа"
|
||||||
// @Failure 404 {object} domain.GrpcError
|
// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 404 {object} apierrors.Error
|
||||||
// @Router /access_list/set_one [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /access_list/set_one [POST]
|
||||||
func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
|
func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
|
||||||
result, err := c.service.SetOne(ctx, req)
|
result, err := c.service.SetOne(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
return nil, status.Errorf(codes.NotFound, "application not found")
|
return nil, apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with id %d not found", req.AppId),
|
||||||
|
err,
|
||||||
|
)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, err
|
return nil, err
|
||||||
default:
|
default:
|
||||||
@@ -72,24 +88,84 @@ func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneReque
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetList godoc
|
// SetList godoc
|
||||||
// @Tags accessList
|
//
|
||||||
// @Summary Настроить доступность списка методов для приложения
|
// @Tags accessList
|
||||||
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
|
// @Summary Настроить доступность списка методов для приложения
|
||||||
// @Accept json
|
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.AccessListSetListRequest false "объект настройки доступа"
|
// @Produce json
|
||||||
// @Success 200 {array} domain.MethodInfo "список доступности методов"
|
// @Param body body domain.AccessListSetListRequest false "объект настройки доступа"
|
||||||
// @Failure 404 {object} domain.GrpcError
|
// @Success 200 {array} domain.MethodInfo "список доступности методов"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 404 {object} apierrors.Error
|
||||||
// @Router /access_list/set_list [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /access_list/set_list [POST]
|
||||||
func (c AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
|
func (c AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
|
||||||
result, err := c.service.SetList(ctx, req)
|
result, err := c.service.SetList(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
return nil, status.Errorf(codes.NotFound, "application not found")
|
return nil, apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with id %d not found", req.AppId),
|
||||||
|
err,
|
||||||
|
)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, err
|
return nil, err
|
||||||
default:
|
default:
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteList godoc
|
||||||
|
//
|
||||||
|
// @Tags accessList
|
||||||
|
// @Summary Удалить список доступных методов для приложения
|
||||||
|
// @Description Удаляет заданный список методов для приложения
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.AccessListDeleteListRequest false "тело запроса"
|
||||||
|
// @Success 200 {object} any
|
||||||
|
// @Failure 404 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /access_list/delete_list [POST]
|
||||||
|
func (c AccessList) DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error {
|
||||||
|
err := c.service.DeleteList(ctx, req)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
|
return apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with id %d not found", req.AppId),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
default:
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteListWithMethods godoc
|
||||||
|
//
|
||||||
|
// @Tags accessList
|
||||||
|
// @Summary Удалить список доступных методов для приложения
|
||||||
|
// @Description Удаляет заданный список методов для приложения
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.AccessListDeleteV2ListRequest false "тело запроса"
|
||||||
|
// @Success 200 {object} any
|
||||||
|
// @Failure 404 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /access_list/delete_list_with_methods [POST]
|
||||||
|
func (c AccessList) DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error {
|
||||||
|
err := c.service.DeleteListWithMethods(ctx, req)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
|
return apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with id %d not found", req.AppId),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
default:
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"isp-system-service/domain"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AppGroupService interface {
|
||||||
|
Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error)
|
||||||
|
Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error)
|
||||||
|
DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error)
|
||||||
|
GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error)
|
||||||
|
GetAll(ctx context.Context) ([]domain.AppGroup, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type AppGroup struct {
|
||||||
|
service AppGroupService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAppGroup(service AppGroupService) AppGroup {
|
||||||
|
return AppGroup{
|
||||||
|
service: service,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create godoc
|
||||||
|
//
|
||||||
|
// @Tags application_group
|
||||||
|
// @Summary Создать группу приложений
|
||||||
|
// @Description Если группа приложений таким именем существует, возвращает ошибку
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.CreateAppGroupRequest true "Объект группы приложений"
|
||||||
|
// @Success 200 {object} domain.AppGroup
|
||||||
|
// @Failure 400 {object} apierrors.Error
|
||||||
|
// @Failure 409 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application_group/create [POST]
|
||||||
|
func (c AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) {
|
||||||
|
result, err := c.service.Create(ctx, req)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrAppGroupDuplicateName):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.AlreadyExists,
|
||||||
|
domain.ErrCodeAppGroupDuplicateName,
|
||||||
|
fmt.Sprintf("application group with name %s already exists", req.Name),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
default:
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update godoc
|
||||||
|
//
|
||||||
|
// @Tags application_group
|
||||||
|
// @Summary Обновить группу приложений
|
||||||
|
// @Description Если группа приложений таким именем существует или группы приложений с указанным id не существует, возвращает ошибку
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.UpdateAppGroupRequest true "Объект группы приложений"
|
||||||
|
// @Success 200 {object} domain.AppGroup
|
||||||
|
// @Failure 400 {object} apierrors.Error
|
||||||
|
// @Failure 404 {object} apierrors.Error
|
||||||
|
// @Failure 409 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application_group/update [POST]
|
||||||
|
func (c AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) {
|
||||||
|
result, err := c.service.Update(ctx, req)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrAppGroupDuplicateName):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.AlreadyExists,
|
||||||
|
domain.ErrCodeAppGroupDuplicateName,
|
||||||
|
fmt.Sprintf("application group with name %s already exists", req.Name),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
case errors.Is(err, domain.ErrAppGroupNotFound):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeAppGroupNotFound,
|
||||||
|
fmt.Sprintf("application group with id %d not found", req.Id),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
default:
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteList godoc
|
||||||
|
//
|
||||||
|
// @Tags application_group
|
||||||
|
// @Summary Удалить группы приложений
|
||||||
|
// @Description Удаляет группы приложений по списку их идентификаторов, возвращает количество удаленных групп приложений
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.IdListRequest true "список идентификаторов групп приложений"
|
||||||
|
// @Success 200 {object} domain.DeleteResponse
|
||||||
|
// @Failure 400 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application_group/delete_list [POST]
|
||||||
|
func (c AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) {
|
||||||
|
return c.service.DeleteList(ctx, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetByIdList godoc
|
||||||
|
//
|
||||||
|
// @Tags application_group
|
||||||
|
// @Summary Получить группы приложений по списку идентификаторов
|
||||||
|
// @Description Возвращает группы приложений с указанными идентификаторами
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.IdListRequest true "список идентификаторов групп приложений"
|
||||||
|
// @Success 200 {array} domain.AppGroup
|
||||||
|
// @Failure 400 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application_group/get_by_id_list [POST]
|
||||||
|
func (c AppGroup) GetByIdList(ctx context.Context, req domain.IdListRequest) ([]domain.AppGroup, error) {
|
||||||
|
return c.service.GetByIdList(ctx, req.IdList)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAll godoc
|
||||||
|
//
|
||||||
|
// @Tags application_group
|
||||||
|
// @Summary Получить группы приложений
|
||||||
|
// @Description Возвращает все группы приложений
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {array} domain.AppGroup
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application_group/get_all [POST]
|
||||||
|
func (c AppGroup) GetAll(ctx context.Context) ([]domain.AppGroup, error) {
|
||||||
|
return c.service.GetAll(ctx)
|
||||||
|
}
|
||||||
+246
-84
@@ -2,20 +2,27 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//nolint:interfacebloat
|
||||||
type ApplicationService interface {
|
type ApplicationService interface {
|
||||||
GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error)
|
GetById(ctx context.Context, appId int) (*domain.Application, error)
|
||||||
GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error)
|
GetByToken(ctx context.Context, token string) (*domain.GetApplicationByTokenResponse, error)
|
||||||
GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error)
|
GetByIdList(ctx context.Context, idList []int) ([]domain.Application, error)
|
||||||
SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error)
|
GetByAppGroup(ctx context.Context, appGroupId int) ([]domain.Application, error)
|
||||||
CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error)
|
CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, error)
|
||||||
Delete(ctx context.Context, idList []int) (int, error)
|
Delete(ctx context.Context, idList []int) (int, error)
|
||||||
|
NextId(ctx context.Context) (int, error)
|
||||||
|
GetAll(ctx context.Context) ([]domain.Application, error)
|
||||||
|
Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.Application, error)
|
||||||
|
Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Application struct {
|
type Application struct {
|
||||||
@@ -29,22 +36,58 @@ func NewApplication(service ApplicationService) Application {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetById godoc
|
// GetById godoc
|
||||||
// @Tags application
|
//
|
||||||
// @Summary Получить приложение по идентификатору
|
// @Tags application
|
||||||
// @Description Возвращает описание приложения по его идентификатору
|
// @Summary Получить приложение по идентификатору
|
||||||
// @Accept json
|
// @Description Возвращает описание приложения по его идентификатору
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.Identity true "Идентификатор приложения"
|
// @Produce json
|
||||||
// @Success 200 {object} domain.ApplicationWithTokens
|
// @Param body body domain.Identity true "Идентификатор приложения"
|
||||||
// @Failure 400 {object} domain.GrpcError
|
// @Success 200 {object} domain.Application
|
||||||
// @Failure 404 {object} domain.GrpcError
|
// @Failure 400 {object} apierrors.Error
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 404 {object} apierrors.Error
|
||||||
// @Router /application/get_application_by_id [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) {
|
// @Router /application/get_application_by_id [POST]
|
||||||
|
func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.Application, error) {
|
||||||
result, err := c.service.GetById(ctx, req.Id)
|
result, err := c.service.GetById(ctx, req.Id)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id)
|
return nil, apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with id %d not found", req.Id),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
case err != nil:
|
||||||
|
return nil, err
|
||||||
|
default:
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetByToken godoc
|
||||||
|
//
|
||||||
|
// @Tags application
|
||||||
|
// @Summary Получить идентификатор приложения и группы по токену
|
||||||
|
// @Description Возвращает идентификатор приложения и группы по токену
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.GetApplicationByTokenRequest true "Тело запроса"
|
||||||
|
// @Success 200 {object} domain.GetApplicationByTokenResponse
|
||||||
|
// @Failure 400 {object} apierrors.Error
|
||||||
|
// @Failure 404 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application/get_application_by_token [POST]
|
||||||
|
func (c Application) GetByToken(ctx context.Context, req domain.GetApplicationByTokenRequest) (*domain.GetApplicationByTokenResponse, error) {
|
||||||
|
result, err := c.service.GetByToken(ctx, req.Token)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with token '%s' not found", req.Token),
|
||||||
|
err,
|
||||||
|
)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, err
|
return nil, err
|
||||||
default:
|
default:
|
||||||
@@ -53,68 +96,73 @@ func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetByIdList godoc
|
// GetByIdList godoc
|
||||||
// @Tags application
|
//
|
||||||
// @Summary Получить список приложений
|
// @Tags application
|
||||||
// @Description Возвращает массив приложений с токенами по их идентификаторам
|
// @Summary Получить список приложений
|
||||||
// @Accept json
|
// @Description Возвращает массив приложений их идентификаторам
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body []integer false "Массив идентификаторов приложений"
|
// @Produce json
|
||||||
// @Success 200 {array} domain.ApplicationWithTokens
|
// @Param body body []integer false "Массив идентификаторов приложений"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Success 200 {array} domain.Application
|
||||||
// @Router /application/get_applications [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) {
|
// @Router /application/get_applications [POST]
|
||||||
|
func (c Application) GetByIdList(ctx context.Context, req []int) ([]domain.Application, error) {
|
||||||
return c.service.GetByIdList(ctx, req)
|
return c.service.GetByIdList(ctx, req)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetByServiceId godoc
|
// GetByAppGroup godoc
|
||||||
// @Tags application
|
//
|
||||||
// @Summary Получить список приложений по идентификатору сервиса
|
// @Tags application
|
||||||
// @Description Возвращает список приложений по запрошенному идентификатору сервиса
|
// @Summary Получить список приложений по идентификатору группы
|
||||||
// @Accept json
|
// @Description Возвращает список приложений по идентификатору группы
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.Identity true "Идентификатор сервиса"
|
// @Produce json
|
||||||
// @Success 200 {array} domain.ApplicationWithTokens
|
// @Param body body domain.Identity true "Тело запроса"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Success 200 {array} domain.Application
|
||||||
// @Router /application/get_applications_by_service_id [POST]
|
// @Failure 400 {object} apierrors.Error
|
||||||
func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) {
|
// @Failure 500 {object} apierrors.Error
|
||||||
return c.service.GetByServiceId(ctx, req.Id)
|
// @Router /application/get_by_app_group [POST]
|
||||||
}
|
func (c Application) GetByAppGroup(ctx context.Context, req domain.Identity) ([]domain.Application, error) {
|
||||||
|
return c.service.GetByAppGroup(ctx, req.Id)
|
||||||
// GetSystemTree godoc
|
|
||||||
// @Tags application
|
|
||||||
// @Summary Метод получения системного дерева
|
|
||||||
// @Description Возвращает описание взаимосвязей сервисов и приложений
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Success 200 {array} domain.DomainWithService
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /application/get_system_tree [POST]
|
|
||||||
func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithService, error) {
|
|
||||||
return c.service.SystemTree(ctx, domain.DefaultSystemId)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateUpdate godoc
|
// CreateUpdate godoc
|
||||||
// @Tags application
|
//
|
||||||
// @Summary Создать/обновить приложение
|
// @Tags application
|
||||||
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
|
// @Summary Создать/обновить приложение
|
||||||
// @Accept json
|
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
|
// @Produce json
|
||||||
// @Success 200 {object} domain.ApplicationWithTokens
|
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
|
||||||
// @Failure 400 {object} domain.GrpcError
|
// @Success 200 {object} domain.Application
|
||||||
// @Failure 404 {object} domain.GrpcError
|
// @Failure 400 {object} apierrors.Error
|
||||||
// @Failure 409 {object} domain.GrpcError
|
// @Failure 404 {object} apierrors.Error
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 409 {object} apierrors.Error
|
||||||
// @Router /application/create_update_application [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
|
// @Router /application/create_update_application [POST]
|
||||||
|
func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, error) {
|
||||||
result, err := c.service.CreateUpdate(ctx, req)
|
result, err := c.service.CreateUpdate(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrServiceNotFound):
|
case errors.Is(err, domain.ErrAppGroupNotFound):
|
||||||
return nil, status.Errorf(codes.InvalidArgument, "service with id %d not found", req.ServiceId)
|
return nil, apierrors.NewBusinessError(
|
||||||
|
domain.ErrCodeAppGroupNotFound,
|
||||||
|
fmt.Sprintf("service with id %d not found", req.ApplicationGroupId),
|
||||||
|
err,
|
||||||
|
)
|
||||||
case errors.Is(err, domain.ErrApplicationDuplicateName):
|
case errors.Is(err, domain.ErrApplicationDuplicateName):
|
||||||
return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name)
|
return nil, apierrors.New(
|
||||||
|
codes.AlreadyExists,
|
||||||
|
domain.ErrCodeApplicationDuplicateName,
|
||||||
|
fmt.Sprintf("application with name %s already exists", req.Name),
|
||||||
|
err,
|
||||||
|
)
|
||||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", req.Id)
|
return nil, apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with id %d not found", req.Id),
|
||||||
|
err,
|
||||||
|
)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, err
|
return nil, err
|
||||||
default:
|
default:
|
||||||
@@ -123,19 +171,21 @@ func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Delete godoc
|
// Delete godoc
|
||||||
// @Tags application
|
//
|
||||||
// @Summary Удалить приложения
|
// @Tags application
|
||||||
// @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений
|
// @Summary Удалить приложения
|
||||||
// @Accept json
|
// @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body []integer false "Массив идентификаторов приложений"
|
// @Produce json
|
||||||
// @Success 200 {object} domain.DeleteResponse
|
// @Param body body []integer false "Массив идентификаторов приложений"
|
||||||
// @Failure 400 {object} domain.GrpcError
|
// @Success 200 {object} domain.DeleteResponse
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 400 {object} apierrors.Error
|
||||||
// @Router /application/delete_applications [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application/delete_applications [POST]
|
||||||
func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
|
func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
|
||||||
if len(req) == 0 {
|
if len(req) == 0 {
|
||||||
return nil, status.Errorf(codes.InvalidArgument, "At least one id are required")
|
return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest,
|
||||||
|
"At least one id are required", errors.New("invalid id count"))
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := c.service.Delete(ctx, req)
|
result, err := c.service.Delete(ctx, req)
|
||||||
@@ -147,3 +197,115 @@ func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteRespo
|
|||||||
Deleted: result,
|
Deleted: result,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NextId godoc
|
||||||
|
//
|
||||||
|
// @Tags application
|
||||||
|
// @Summary Получить следующий идентификатор приложения
|
||||||
|
// @Description Возвращает следующий идентификатор приложения
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} integer
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application/next_id [POST]
|
||||||
|
func (c Application) NextId(ctx context.Context) (int, error) {
|
||||||
|
return c.service.NextId(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAll godoc
|
||||||
|
//
|
||||||
|
// @Tags application
|
||||||
|
// @Summary Получить список приложений
|
||||||
|
// @Description Возвращает список приложений
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {array} domain.Application
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application/get_all [POST]
|
||||||
|
func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) {
|
||||||
|
return c.service.GetAll(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create godoc
|
||||||
|
//
|
||||||
|
// @Tags application
|
||||||
|
// @Summary Создать приложение
|
||||||
|
// @Description Если приложение с такими идентификатором или связкой `applicationGroupId`-`name` существует, то возвращает ошибку
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.CreateApplicationRequest true "Объект приложения"
|
||||||
|
// @Success 200 {object} domain.Application
|
||||||
|
// @Failure 400 {object} apierrors.Error
|
||||||
|
// @Failure 409 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application/create_application [POST]
|
||||||
|
func (c Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.Application, error) {
|
||||||
|
result, err := c.service.Create(ctx, req)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrAppGroupNotFound):
|
||||||
|
return nil, apierrors.NewBusinessError(
|
||||||
|
domain.ErrCodeAppGroupNotFound,
|
||||||
|
fmt.Sprintf("application group with id %d not found", req.ApplicationGroupId),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
case errors.Is(err, domain.ErrApplicationDuplicateName):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.AlreadyExists,
|
||||||
|
domain.ErrCodeApplicationDuplicateName,
|
||||||
|
fmt.Sprintf("application with name %s already exists", req.Name),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
case errors.Is(err, domain.ErrApplicationDuplicateId):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.AlreadyExists,
|
||||||
|
domain.ErrCodeApplicationDuplicateId,
|
||||||
|
fmt.Sprintf("application with id %d already exists", req.Id),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
default:
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update godoc
|
||||||
|
//
|
||||||
|
// @Tags application
|
||||||
|
// @Summary Обновить приложение
|
||||||
|
// @Description Если приложение с связкой `applicationGroupId`-`name` существует или приложение не найдено, то возвращает ошибку
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.UpdateApplicationRequest true "Объект приложения"
|
||||||
|
// @Success 200 {object} domain.Application
|
||||||
|
// @Failure 400 {object} apierrors.Error
|
||||||
|
// @Failure 404 {object} apierrors.Error
|
||||||
|
// @Failure 409 {object} apierrors.Error
|
||||||
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /application/update_application [POST]
|
||||||
|
func (c Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error) {
|
||||||
|
result, err := c.service.Update(ctx, req)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.NotFound,
|
||||||
|
domain.ErrCodeApplicationNotFound,
|
||||||
|
fmt.Sprintf("application with id %d not found", req.OldId),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
case errors.Is(err, domain.ErrApplicationDuplicateName):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.AlreadyExists,
|
||||||
|
domain.ErrCodeApplicationDuplicateName,
|
||||||
|
fmt.Sprintf("application with name %s already exists", req.Name),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
case errors.Is(err, domain.ErrApplicationDuplicateId):
|
||||||
|
return nil, apierrors.New(
|
||||||
|
codes.AlreadyExists,
|
||||||
|
domain.ErrCodeApplicationDuplicateId,
|
||||||
|
fmt.Sprintf("application with id %d already exists", req.NewId),
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
default:
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
"isp-system-service/domain"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DomainService interface {
|
|
||||||
GetById(ctx context.Context, id int) (*domain.Domain, error)
|
|
||||||
GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error)
|
|
||||||
CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error)
|
|
||||||
Delete(ctx context.Context, idList []int) (int, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Domain struct {
|
|
||||||
service DomainService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDomain(service DomainService) Domain {
|
|
||||||
return Domain{
|
|
||||||
service: service,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetById godoc
|
|
||||||
// @Tags domain
|
|
||||||
// @Summary Получить домен по идентификатору
|
|
||||||
// @Description Возвращает описание домена по его идентификатору
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body domain.Identity true "Идентификатор домена"
|
|
||||||
// @Success 200 {object} domain.Domain
|
|
||||||
// @Failure 404 {object} domain.GrpcError
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /domain/get_domain_by_id [POST]
|
|
||||||
func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domain, error) {
|
|
||||||
result, err := c.service.GetById(ctx, req.Id)
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrDomainNotFound):
|
|
||||||
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
|
|
||||||
case err != nil:
|
|
||||||
return nil, err
|
|
||||||
default:
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetBySystemId godoc
|
|
||||||
// @Tags domain
|
|
||||||
// @Summary Получить домены по идентификатору системы
|
|
||||||
// @Description Возвращает список доменов по системному идентификатору
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body integer false "Идентификатор системы"
|
|
||||||
// @Success 200 {array} domain.Domain
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /domain/get_domains_by_system_id [POST]
|
|
||||||
func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) {
|
|
||||||
return c.service.GetBySystemId(ctx, domain.DefaultSystemId)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateUpdate godoc
|
|
||||||
// @Tags domain
|
|
||||||
// @Summary Создать/обновить домен
|
|
||||||
// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body domain.DomainCreateUpdateRequest true "Объект домена"
|
|
||||||
// @Success 200 {object} domain.Domain
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /domain/create_update_domain [POST]
|
|
||||||
func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest) (*domain.Domain, error) {
|
|
||||||
result, err := c.service.CreateUpdate(ctx, req, domain.DefaultSystemId)
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrSystemNotFound):
|
|
||||||
return nil, status.Errorf(codes.InvalidArgument, "system with id %d not found", domain.DefaultSystemId)
|
|
||||||
case errors.Is(err, domain.ErrDomainNotFound):
|
|
||||||
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
|
|
||||||
case errors.Is(err, domain.ErrDomainDuplicateName):
|
|
||||||
return nil, status.Errorf(codes.AlreadyExists, "domain with name %s already exists", req.Name)
|
|
||||||
case err != nil:
|
|
||||||
return nil, err
|
|
||||||
default:
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete godoc
|
|
||||||
// @Tags domain
|
|
||||||
// @Summary Удаление доменов
|
|
||||||
// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body []integer false "Массив идентификаторов доменов"
|
|
||||||
// @Success 200 {object} domain.DeleteResponse
|
|
||||||
// @Failure 400 {object} domain.GrpcError
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /domain/delete_domains [POST]
|
|
||||||
func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
|
|
||||||
if len(req) == 0 {
|
|
||||||
return nil, status.Errorf(codes.InvalidArgument, "at least one id are required")
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := c.service.Delete(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &domain.DeleteResponse{
|
|
||||||
Deleted: result,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
+24
-21
@@ -3,13 +3,14 @@ package controller
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type SecureService interface {
|
type SecureService interface {
|
||||||
Authenticate(ctx context.Context, token string) (*domain.AuthData, error)
|
Authenticate(ctx context.Context, token string) (*domain.AuthData, error)
|
||||||
Authorize(ctx context.Context, appId int, endpoint string) (bool, error)
|
Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Secure struct {
|
type Secure struct {
|
||||||
@@ -23,15 +24,16 @@ func NewSecure(service SecureService) Secure {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Authenticate godoc
|
// Authenticate godoc
|
||||||
// @Tags secure
|
//
|
||||||
// @Summary Метод аутентификации токена
|
// @Tags secure
|
||||||
// @Description Проверяет наличие токена в системе,
|
// @Summary Метод аутентификации токена
|
||||||
// @Accept json
|
// @Description Проверяет наличие токена в системе,
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.AuthenticateRequest true "Тело запроса"
|
// @Produce json
|
||||||
// @Success 200 {array} domain.AuthenticateResponse
|
// @Param body body domain.AuthenticateRequest true "Тело запроса"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Success 200 {array} domain.AuthenticateResponse
|
||||||
// @Router /secure/authenticate [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /secure/authenticate [POST]
|
||||||
func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest) (*domain.AuthenticateResponse, error) {
|
func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest) (*domain.AuthenticateResponse, error) {
|
||||||
result, err := c.service.Authenticate(ctx, req.Token)
|
result, err := c.service.Authenticate(ctx, req.Token)
|
||||||
switch {
|
switch {
|
||||||
@@ -56,17 +58,18 @@ func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Authorize godoc
|
// Authorize godoc
|
||||||
// @Tags secure
|
//
|
||||||
// @Summary Метод авторизации приложения
|
// @Tags secure
|
||||||
// @Description Проверяет доступ приложения к запрашиваемому ендпоинту
|
// @Summary Метод авторизации приложения
|
||||||
// @Accept json
|
// @Description Проверяет доступ приложения к запрашиваемому ендпоинту
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.AuthorizeRequest true "Тело запрос"
|
// @Produce json
|
||||||
// @Success 200 {array} domain.AuthorizeResponse
|
// @Param body body domain.AuthorizeRequest true "Тело запрос"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Success 200 {array} domain.AuthorizeResponse
|
||||||
// @Router /secure/authorize [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /secure/authorize [POST]
|
||||||
func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) {
|
func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) {
|
||||||
result, err := c.service.Authorize(ctx, req.ApplicationId, req.Endpoint)
|
result, err := c.service.Authorize(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrAccessListNotFound):
|
case errors.Is(err, domain.ErrAccessListNotFound):
|
||||||
return &domain.AuthorizeResponse{
|
return &domain.AuthorizeResponse{
|
||||||
|
|||||||
@@ -1,134 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
"isp-system-service/domain"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ServiceService interface {
|
|
||||||
GetById(ctx context.Context, id int) (*domain.Service, error)
|
|
||||||
GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error)
|
|
||||||
GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error)
|
|
||||||
CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error)
|
|
||||||
Delete(ctx context.Context, idList []int) (int, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Service struct {
|
|
||||||
service ServiceService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewService(service ServiceService) Service {
|
|
||||||
return Service{
|
|
||||||
service: service,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetById godoc
|
|
||||||
// @Tags service
|
|
||||||
// @Summary Получить сервис по идентификатору
|
|
||||||
// @Description Возвращает описание сервиса по его идентификатору
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body domain.Identity true "Идентификатор сервиса"
|
|
||||||
// @Success 200 {object} domain.Service
|
|
||||||
// @Failure 404 {object} domain.GrpcError
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /service/get_service_by_id [POST]
|
|
||||||
func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) {
|
|
||||||
result, err := c.service.GetById(ctx, req.Id)
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrServiceNotFound):
|
|
||||||
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
|
|
||||||
case err != nil:
|
|
||||||
return nil, err
|
|
||||||
default:
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get godoc
|
|
||||||
// @Tags service
|
|
||||||
// @Summary Получить список сервисов
|
|
||||||
// @Description Возвращает список сервисов по их идентификаторам
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body []integer false "Массив идентификаторов сервисов"
|
|
||||||
// @Success 200 {array} domain.Service
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /service/get_service [POST]
|
|
||||||
func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) {
|
|
||||||
return c.service.GetByIdList(ctx, req)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetByDomainId godoc
|
|
||||||
// @Tags service
|
|
||||||
// @Summary Получить список сервисов по идентификатору домена
|
|
||||||
// @Description Возвращает список сервисов по идентификатору домена
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body domain.Identity true "Идентификатор домена"
|
|
||||||
// @Success 200 {array} domain.Service
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /service/get_services_by_domain_id [POST]
|
|
||||||
func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.Service, error) {
|
|
||||||
return c.service.GetByDomainId(ctx, req.Id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateUpdate godoc
|
|
||||||
// @Tags service
|
|
||||||
// @Summary Создать/обновить сервис
|
|
||||||
// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса"
|
|
||||||
// @Success 200 {object} domain.Service
|
|
||||||
// @Failure 400 {object} domain.GrpcError
|
|
||||||
// @Failure 404 {object} domain.GrpcError
|
|
||||||
// @Failure 409 {object} domain.GrpcError
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /service/create_update_service [POST]
|
|
||||||
func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
|
|
||||||
result, err := c.service.CreateUpdate(ctx, req)
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrDomainNotFound):
|
|
||||||
return nil, status.Errorf(codes.InvalidArgument, "domain with id %d not found", req.DomainId)
|
|
||||||
case errors.Is(err, domain.ErrServiceNotFound):
|
|
||||||
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
|
|
||||||
case errors.Is(err, domain.ErrServiceDuplicateName):
|
|
||||||
return nil, status.Errorf(codes.AlreadyExists, "service with name %s already exists", req.Name)
|
|
||||||
case err != nil:
|
|
||||||
return nil, err
|
|
||||||
default:
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete godoc
|
|
||||||
// @Tags service
|
|
||||||
// @Summary Удалить сервисы
|
|
||||||
// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body []integer true "Массив идентификаторов сервисов"
|
|
||||||
// @Success 200 {object} domain.DeleteResponse
|
|
||||||
// @Failure 400 {object} domain.GrpcError
|
|
||||||
// @Failure 500 {object} domain.GrpcError
|
|
||||||
// @Router /service/delete_service [POST]
|
|
||||||
func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
|
|
||||||
if len(req) == 0 {
|
|
||||||
return nil, status.Error(codes.InvalidArgument, "at least one id are required")
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := c.service.Delete(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &domain.DeleteResponse{
|
|
||||||
Deleted: result,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
+54
-47
@@ -2,14 +2,16 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ITokenService interface {
|
type TokenService interface {
|
||||||
GetByAppId(ctx context.Context, appId int) ([]domain.Token, error)
|
GetByAppId(ctx context.Context, appId int) ([]domain.Token, error)
|
||||||
Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error)
|
Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error)
|
||||||
Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error)
|
Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error)
|
||||||
@@ -17,48 +19,51 @@ type ITokenService interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Token struct {
|
type Token struct {
|
||||||
service ITokenService
|
service TokenService
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewToken(service ITokenService) Token {
|
func NewToken(service TokenService) Token {
|
||||||
return Token{
|
return Token{
|
||||||
service: service,
|
service: service,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetByAppId godoc
|
// GetByAppId godoc
|
||||||
// @Tags token
|
//
|
||||||
// @Summary Получить токены по идентификатору приложения
|
// @Tags token
|
||||||
// @Description Возвращает список токенов, привязанных к приложению
|
// @Summary Получить токены по идентификатору приложения
|
||||||
// @Accept json
|
// @Description Возвращает список токенов, привязанных к приложению
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.Identity true "Идентификатор приложения"
|
// @Produce json
|
||||||
// @Success 200 {array} entity.Token
|
// @Param body body domain.Identity true "Идентификатор приложения"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Success 200 {array} entity.Token
|
||||||
// @Router /token/get_tokens_by_app_id [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /token/get_tokens_by_app_id [POST]
|
||||||
func (c Token) GetByAppId(ctx context.Context, req domain.Identity) ([]domain.Token, error) {
|
func (c Token) GetByAppId(ctx context.Context, req domain.Identity) ([]domain.Token, error) {
|
||||||
return c.service.GetByAppId(ctx, req.Id)
|
return c.service.GetByAppId(ctx, req.Id)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create godoc
|
// Create godoc
|
||||||
// @Tags token
|
//
|
||||||
// @Summary Создать токен
|
// @Tags token
|
||||||
// @Description Создает токен и привязывает его к приложению
|
// @Summary Создать токен
|
||||||
// @Accept json
|
// @Description Создает токен и привязывает его к приложению
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.TokenCreateRequest true "Объект создания токена"
|
// @Produce json
|
||||||
// @Success 200 {object} domain.ApplicationWithTokens
|
// @Param body body domain.TokenCreateRequest true "Объект создания токена"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Success 200 {object} domain.ApplicationWithTokens
|
||||||
// @Router /token/create_token [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /token/create_token [POST]
|
||||||
func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
|
func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
|
||||||
result, err := c.service.Create(ctx, req)
|
result, err := c.service.Create(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||||
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.AppId)
|
return nil, apierrors.New(
|
||||||
case errors.Is(err, domain.ErrServiceNotFound):
|
codes.NotFound,
|
||||||
return nil, status.Errorf(codes.NotFound, "service for app_id id %d not found", req.AppId)
|
domain.ErrCodeApplicationNotFound,
|
||||||
case errors.Is(err, domain.ErrDomainNotFound):
|
fmt.Sprintf("application with id %d not found", req.AppId),
|
||||||
return nil, status.Errorf(codes.NotFound, "domain for app_id %d not found", req.AppId)
|
err,
|
||||||
|
)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, err
|
return nil, err
|
||||||
default:
|
default:
|
||||||
@@ -67,29 +72,31 @@ func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Revoke godoc
|
// Revoke godoc
|
||||||
// @Tags token
|
//
|
||||||
// @Summary Отозвать токены
|
// @Tags token
|
||||||
// @Description Отвязывает токены от приложений и удаляет их
|
// @Summary Отозвать токены
|
||||||
// @Accept json
|
// @Description Отвязывает токены от приложений и удаляет их
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов"
|
// @Produce json
|
||||||
// @Success 200 {object} domain.ApplicationWithTokens
|
// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Success 200 {object} domain.ApplicationWithTokens
|
||||||
// @Router /token/revoke_tokens [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /token/revoke_tokens [POST]
|
||||||
func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
|
func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
|
||||||
return c.service.Revoke(ctx, req)
|
return c.service.Revoke(ctx, req)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RevokeForApp godoc
|
// RevokeForApp godoc
|
||||||
// @Tags token
|
//
|
||||||
// @Summary Отозвать токены для приложения
|
// @Tags token
|
||||||
// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения
|
// @Summary Отозвать токены для приложения
|
||||||
// @Accept json
|
// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения
|
||||||
// @Produce json
|
// @Accept json
|
||||||
// @Param body body domain.Identity true "Идентификатор приложения"
|
// @Produce json
|
||||||
// @Success 200 {object} domain.DeleteResponse
|
// @Param body body domain.Identity true "Идентификатор приложения"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Success 200 {object} domain.DeleteResponse
|
||||||
// @Router /token/revoke_tokens_for_app [POST]
|
// @Failure 500 {object} apierrors.Error
|
||||||
|
// @Router /token/revoke_tokens_for_app [POST]
|
||||||
func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) {
|
func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) {
|
||||||
return c.service.RevokeByAppId(ctx, req.Id)
|
return c.service.RevokeByAppId(ctx, req.Id)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package docs
|
||||||
|
|
||||||
|
import _ "embed"
|
||||||
|
|
||||||
|
// Embedded swagger files.
|
||||||
|
var (
|
||||||
|
//go:embed swagger.json
|
||||||
|
SwaggerJson []byte
|
||||||
|
)
|
||||||
+641
-511
File diff suppressed because it is too large.
Load diff
-1012
File diff suppressed because it is too large.
Load diff
+23
-6
@@ -1,9 +1,10 @@
|
|||||||
package domain
|
package domain
|
||||||
|
|
||||||
type AccessListSetOneRequest struct {
|
type AccessListSetOneRequest struct {
|
||||||
AppId int `valid:"required~Required"`
|
AppId int `validate:"required"`
|
||||||
Method string `valid:"required~Required"`
|
HttpMethod string
|
||||||
Value bool
|
Method string `validate:"required"`
|
||||||
|
Value bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type AccessListSetOneResponse struct {
|
type AccessListSetOneResponse struct {
|
||||||
@@ -11,12 +12,28 @@ type AccessListSetOneResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AccessListSetListRequest struct {
|
type AccessListSetListRequest struct {
|
||||||
AppId int `valid:"required~Required"`
|
AppId int `validate:"required"`
|
||||||
RemoveOld bool
|
RemoveOld bool
|
||||||
Methods []MethodInfo
|
Methods []MethodInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
type MethodInfo struct {
|
type MethodInfo struct {
|
||||||
Method string
|
HttpMethod string
|
||||||
Value bool
|
Method string
|
||||||
|
Value bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type AccessListDeleteListRequest struct {
|
||||||
|
AppId int `validate:"required"`
|
||||||
|
Methods []string `validate:"required,min=1"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AccessListDeleteV2ListRequest struct {
|
||||||
|
AppId int `validate:"required"`
|
||||||
|
Methods []Method `validate:"required,min=1"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Method struct {
|
||||||
|
HttpMethod string
|
||||||
|
Method string `validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type AppGroup struct {
|
||||||
|
Id int
|
||||||
|
Name string
|
||||||
|
Description string
|
||||||
|
CreatedAt time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateAppGroupRequest struct {
|
||||||
|
Name string `validate:"required"`
|
||||||
|
Description string
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateAppGroupRequest struct {
|
||||||
|
Id int `validate:"required"`
|
||||||
|
Name string `validate:"required"`
|
||||||
|
Description string
|
||||||
|
}
|
||||||
|
|
||||||
|
type IdListRequest struct {
|
||||||
|
IdList []int `validate:"required,min=1"`
|
||||||
|
}
|
||||||
+38
-17
@@ -4,22 +4,27 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ApplicationSystemType = "SYSTEM"
|
||||||
|
ApplicationMobileType = "MOBILE"
|
||||||
|
)
|
||||||
|
|
||||||
type Application struct {
|
type Application struct {
|
||||||
Id int
|
Id int
|
||||||
Name string
|
Name string
|
||||||
Description string
|
Description string
|
||||||
ServiceId int
|
ApplicationGroupId int
|
||||||
Type string
|
Type string
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
UpdatedAt time.Time
|
UpdatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type ApplicationCreateUpdateRequest struct {
|
type ApplicationCreateUpdateRequest struct {
|
||||||
Id int
|
Id int
|
||||||
Name string `valid:"required~Required"`
|
Name string `validate:"required"`
|
||||||
Description string
|
Description string
|
||||||
ServiceId int `valid:"required~Required"`
|
ApplicationGroupId int `validate:"required"`
|
||||||
Type string `valid:"required~Required,in(SYSTEM|MOBILE)"`
|
Type string `validate:"required,oneof=SYSTEM MOBILE"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ApplicationWithTokens struct {
|
type ApplicationWithTokens struct {
|
||||||
@@ -27,10 +32,26 @@ type ApplicationWithTokens struct {
|
|||||||
Tokens []Token
|
Tokens []Token
|
||||||
}
|
}
|
||||||
|
|
||||||
type ApplicationSimple struct {
|
type CreateApplicationRequest struct {
|
||||||
Id int
|
Id int `validate:"required"`
|
||||||
Name string
|
Name string `validate:"required"`
|
||||||
|
Description string
|
||||||
|
ApplicationGroupId int `validate:"required"`
|
||||||
|
Type string `validate:"required,oneof=SYSTEM MOBILE"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateApplicationRequest struct {
|
||||||
|
OldId int `validate:"required"`
|
||||||
|
NewId int `validate:"required"`
|
||||||
|
Name string `validate:"required"`
|
||||||
Description string
|
Description string
|
||||||
Type string
|
}
|
||||||
Tokens []Token
|
|
||||||
|
type GetApplicationByTokenRequest struct {
|
||||||
|
Token string `validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetApplicationByTokenResponse struct {
|
||||||
|
ApplicationId int
|
||||||
|
ApplicationGroupId int
|
||||||
}
|
}
|
||||||
+1
-1
@@ -2,7 +2,7 @@ package domain
|
|||||||
|
|
||||||
type (
|
type (
|
||||||
Identity struct {
|
Identity struct {
|
||||||
Id int `valid:"required~Required"`
|
Id int `validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
DeleteResponse struct {
|
DeleteResponse struct {
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DomainCreateUpdateRequest struct {
|
|
||||||
Id int
|
|
||||||
Name string `valid:"required~Required"`
|
|
||||||
Description string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Domain struct {
|
|
||||||
Id int
|
|
||||||
Name string
|
|
||||||
Description string
|
|
||||||
SystemId int
|
|
||||||
CreatedAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
type DomainWithService struct {
|
|
||||||
Id int
|
|
||||||
Name string
|
|
||||||
Description string
|
|
||||||
Services []*ServiceWithApps
|
|
||||||
}
|
|
||||||
+15
-8
@@ -1,20 +1,27 @@
|
|||||||
package domain
|
package domain
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/pkg/errors"
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ErrCodeInvalidRequest = 600
|
||||||
|
|
||||||
|
ErrCodeApplicationNotFound = 602
|
||||||
|
ErrCodeApplicationDuplicateName = 603
|
||||||
|
ErrCodeApplicationDuplicateId = 604
|
||||||
|
|
||||||
|
ErrCodeAppGroupNotFound = 605
|
||||||
|
ErrCodeAppGroupDuplicateName = 606
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrDomainNotFound = errors.New("domain not found")
|
ErrAppGroupNotFound = errors.New("application group not found")
|
||||||
ErrDomainDuplicateName = errors.New("domain name already exist")
|
ErrAppGroupDuplicateName = errors.New("application group name already exist")
|
||||||
|
|
||||||
ErrServiceNotFound = errors.New("service not found")
|
|
||||||
ErrServiceDuplicateName = errors.New("service name already exist")
|
|
||||||
|
|
||||||
ErrSystemNotFound = errors.New("system not found")
|
|
||||||
|
|
||||||
ErrApplicationNotFound = errors.New("application not found")
|
ErrApplicationNotFound = errors.New("application not found")
|
||||||
ErrApplicationDuplicateName = errors.New("application name already exist")
|
ErrApplicationDuplicateName = errors.New("application name already exist")
|
||||||
|
ErrApplicationDuplicateId = errors.New("application id already exist")
|
||||||
|
|
||||||
ErrTokenNotFound = errors.New("token not found")
|
ErrTokenNotFound = errors.New("token not found")
|
||||||
ErrTokenExpired = errors.New("token is expired")
|
ErrTokenExpired = errors.New("token is expired")
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
type GrpcError struct {
|
|
||||||
ErrorMessage string `json:"errorMessage"`
|
|
||||||
ErrorCode string `json:"errorCode"`
|
|
||||||
Details []interface{} `json:"details"`
|
|
||||||
}
|
|
||||||
+5
-6
@@ -1,7 +1,7 @@
|
|||||||
package domain
|
package domain
|
||||||
|
|
||||||
type AuthenticateRequest struct {
|
type AuthenticateRequest struct {
|
||||||
Token string `valid:"required~Required"`
|
Token string `validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuthenticateResponse struct {
|
type AuthenticateResponse struct {
|
||||||
@@ -11,15 +11,14 @@ type AuthenticateResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AuthData struct {
|
type AuthData struct {
|
||||||
SystemId int
|
AppName string
|
||||||
DomainId int
|
|
||||||
ServiceId int
|
|
||||||
ApplicationId int
|
ApplicationId int
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuthorizeRequest struct {
|
type AuthorizeRequest struct {
|
||||||
ApplicationId int `valid:"required~Required"`
|
ApplicationId int `validate:"required"`
|
||||||
Endpoint string `valid:"required~Required"`
|
HttpMethod string
|
||||||
|
Endpoint string `validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuthorizeResponse struct {
|
type AuthorizeResponse struct {
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Service struct {
|
|
||||||
Id int
|
|
||||||
Name string
|
|
||||||
Description string
|
|
||||||
DomainId int
|
|
||||||
CreatedAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
type ServiceCreateUpdateRequest struct {
|
|
||||||
Id int
|
|
||||||
Name string `valid:"required~Required"`
|
|
||||||
Description string
|
|
||||||
DomainId int `valid:"required~Required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ServiceWithApps struct {
|
|
||||||
Id int
|
|
||||||
Name string
|
|
||||||
Description string
|
|
||||||
Apps []*ApplicationSimple
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
const (
|
|
||||||
DefaultSystemId = 1
|
|
||||||
)
|
|
||||||
+3
-3
@@ -12,11 +12,11 @@ type Token struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type TokenRevokeRequest struct {
|
type TokenRevokeRequest struct {
|
||||||
AppId int `valid:"required~Required"`
|
AppId int `validate:"required"`
|
||||||
Tokens []string
|
Tokens []string
|
||||||
}
|
}
|
||||||
|
|
||||||
type TokenCreateRequest struct {
|
type TokenCreateRequest struct {
|
||||||
AppId int `valid:"required~Required"`
|
AppId int `validate:"required"`
|
||||||
ExpireTimeMs int `valid:"required~Required"`
|
ExpireTimeMs int `validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
package entity
|
package entity
|
||||||
|
|
||||||
type AccessList struct {
|
type AccessList struct {
|
||||||
AppId int
|
AppId int
|
||||||
Method string
|
HttpMethod string
|
||||||
Value bool
|
Method string
|
||||||
|
Value bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Method struct {
|
||||||
|
HttpMethod string
|
||||||
|
Method string
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
package entity
|
package entity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"database/sql"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Domain struct {
|
type AppGroup struct {
|
||||||
Id int
|
Id int
|
||||||
Name string
|
Name string
|
||||||
Description *string
|
Description sql.NullString
|
||||||
SystemId int
|
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
UpdatedAt time.Time
|
UpdatedAt time.Time
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,16 @@
|
|||||||
package entity
|
package entity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"database/sql"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Application struct {
|
type Application struct {
|
||||||
Id int
|
Id int
|
||||||
Name string
|
Name string
|
||||||
Description *string
|
Description sql.NullString
|
||||||
ServiceId int
|
ApplicationGroupId int
|
||||||
Type string
|
Type string
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
UpdatedAt time.Time
|
UpdatedAt time.Time
|
||||||
}
|
}
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package entity
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Service struct {
|
|
||||||
Id int
|
|
||||||
Name string
|
|
||||||
Description *string
|
|
||||||
DomainId int
|
|
||||||
CreatedAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
|
||||||
+1
-3
@@ -12,9 +12,7 @@ type Token struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AuthData struct {
|
type AuthData struct {
|
||||||
SystemId int
|
AppName string
|
||||||
DomainId int
|
|
||||||
ServiceId int
|
|
||||||
AppId int
|
AppId int
|
||||||
ExpireTime int
|
ExpireTime int
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
|
|||||||
@@ -1,86 +1,81 @@
|
|||||||
module isp-system-service
|
module isp-system-service
|
||||||
|
|
||||||
go 1.17
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Masterminds/squirrel v1.5.3
|
github.com/Masterminds/squirrel v1.5.4
|
||||||
github.com/integration-system/isp-kit v1.10.4
|
github.com/jackc/pgx/v5 v5.10.0
|
||||||
github.com/integration-system/isp-lib/v2 v2.10.0
|
github.com/stretchr/testify v1.11.1
|
||||||
github.com/integration-system/jsonschema v1.0.1
|
github.com/txix-open/isp-kit v1.74.0
|
||||||
github.com/pkg/errors v0.9.1
|
github.com/txix-open/jsonschema v1.3.0
|
||||||
github.com/pressly/goose v2.7.0+incompatible
|
google.golang.org/grpc v1.83.0
|
||||||
github.com/stretchr/testify v1.8.0
|
|
||||||
google.golang.org/grpc v1.48.0
|
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/BurntSushi/toml v1.1.0 // indirect
|
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
|
||||||
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
|
|
||||||
github.com/beorn7/perks v1.0.1 // indirect
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
github.com/buger/jsonparser v1.6.0 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||||
github.com/fsnotify/fsnotify v1.5.4 // indirect
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
github.com/coder/websocket v1.8.15 // indirect
|
||||||
github.com/go-openapi/jsonreference v0.20.0 // indirect
|
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||||
github.com/go-openapi/spec v0.20.5 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||||
github.com/go-openapi/swag v0.21.1 // indirect
|
github.com/getsentry/sentry-go v0.48.0 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.0 // indirect
|
github.com/go-faker/faker/v4 v4.10.1 // indirect
|
||||||
github.com/golang/protobuf v1.5.2 // indirect
|
github.com/go-logr/logr v1.4.4 // indirect
|
||||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
github.com/go-logr/stdr v1.2.2 // indirect
|
||||||
github.com/iancoleman/strcase v0.2.0 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/integration-system/bellows v1.0.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/integration-system/isp-etp-go/v2 v2.1.3 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
|
||||||
github.com/jackc/pgconn v1.12.1 // indirect
|
github.com/iancoleman/strcase v0.3.0 // indirect
|
||||||
github.com/jackc/pgio v1.0.0 // indirect
|
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgproto3/v2 v2.3.0 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
github.com/jackc/pgtype v1.11.0 // indirect
|
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||||
github.com/jackc/pgx/v4 v4.16.1 // indirect
|
|
||||||
github.com/jmoiron/sqlx v1.3.5 // indirect
|
|
||||||
github.com/josharian/intern v1.0.0 // indirect
|
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/klauspost/compress v1.15.8 // indirect
|
github.com/klauspost/compress v1.19.1 // 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.2.1 // indirect
|
github.com/leodido/go-urn v1.5.0 // indirect
|
||||||
github.com/magiconair/properties v1.8.6 // indirect
|
github.com/mailru/easyjson v0.9.2 // indirect
|
||||||
github.com/mailru/easyjson v0.7.7 // indirect
|
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // 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/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
github.com/pelletier/go-toml v1.9.5 // indirect
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.0.2 // indirect
|
github.com/pressly/goose/v3 v3.27.3 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/prometheus/client_golang v1.24.1 // indirect
|
||||||
github.com/prometheus/client_golang v1.12.2 // indirect
|
github.com/prometheus/client_model v0.6.2 // indirect
|
||||||
github.com/prometheus/client_model v0.2.0 // indirect
|
github.com/prometheus/common v0.70.1 // indirect
|
||||||
github.com/prometheus/common v0.36.0 // indirect
|
github.com/prometheus/procfs v0.21.1 // indirect
|
||||||
github.com/prometheus/procfs v0.7.3 // indirect
|
github.com/sethvargo/go-retry v0.4.0 // indirect
|
||||||
github.com/spf13/afero v1.8.2 // indirect
|
github.com/txix-open/bellows v1.2.0 // indirect
|
||||||
github.com/spf13/cast v1.5.0 // indirect
|
github.com/txix-open/etp/v4 v4.1.3 // indirect
|
||||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
|
||||||
github.com/spf13/pflag v1.0.5 // indirect
|
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||||
github.com/spf13/viper v1.12.0 // indirect
|
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||||
github.com/subosito/gotenv v1.4.0 // indirect
|
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||||
github.com/swaggo/swag v1.7.0 // indirect
|
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||||
go.uber.org/atomic v1.9.0 // indirect
|
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||||
go.uber.org/multierr v1.8.0 // indirect
|
go.opentelemetry.io/otel v1.44.0 // indirect
|
||||||
go.uber.org/zap v1.21.0 // indirect
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
|
||||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 // indirect
|
||||||
golang.org/x/net v0.0.0-20220708220712-1185a9018129 // indirect
|
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||||
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
|
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
|
||||||
golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e // indirect
|
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||||
golang.org/x/text v0.3.7 // indirect
|
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||||
golang.org/x/tools v0.1.10 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
google.golang.org/genproto v0.0.0-20220713161829-9c7dac0a6568 // indirect
|
go.uber.org/zap v1.28.0 // indirect
|
||||||
google.golang.org/protobuf v1.28.0 // indirect
|
golang.org/x/crypto v0.54.0 // indirect
|
||||||
gopkg.in/ini.v1 v1.66.6 // indirect
|
golang.org/x/net v0.57.0 // indirect
|
||||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
|
golang.org/x/sync v0.22.0 // indirect
|
||||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
|
golang.org/x/text v0.40.0 // indirect
|
||||||
|
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 // indirect
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.11 // 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
|
||||||
nhooyr.io/websocket v1.8.7 // indirect
|
|
||||||
)
|
)
|
||||||
@@ -1,30 +1,31 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/integration-system/isp-kit/bootstrap"
|
|
||||||
"github.com/integration-system/isp-kit/shutdown"
|
|
||||||
"isp-system-service/assembly"
|
"isp-system-service/assembly"
|
||||||
"isp-system-service/conf"
|
"isp-system-service/conf"
|
||||||
"isp-system-service/routes"
|
"isp-system-service/routes"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/bootstrap"
|
||||||
|
"github.com/txix-open/isp-kit/cluster"
|
||||||
|
"github.com/txix-open/isp-kit/shutdown"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
)
|
)
|
||||||
|
|
||||||
// @title isp-system-service
|
// @title isp-system-service
|
||||||
// @version 1.0.0
|
// @version 1.0.0
|
||||||
// @description Сервис управления реестром внешних приложений и токенами аутентификации
|
// @description Сервис управления реестром внешних приложений и токенами аутентификации
|
||||||
|
|
||||||
// @license.name GNU GPL v3.0
|
// @license.name GNU GPL v3.0
|
||||||
|
|
||||||
// @host localhost:9000
|
// @host localhost:9000
|
||||||
// @BasePath /api/system
|
// @BasePath /api/system
|
||||||
|
|
||||||
//go:generate swag init --parseDependency
|
//go:generate swag init -pd -ot json -eot json
|
||||||
//go:generate rm -f docs/swagger.json
|
|
||||||
func main() {
|
func main() {
|
||||||
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors())
|
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport)
|
||||||
app := boot.App
|
app := boot.App
|
||||||
logger := app.Logger()
|
logger := app.Logger()
|
||||||
|
|
||||||
@@ -43,7 +44,6 @@ func main() {
|
|||||||
|
|
||||||
err = app.Run()
|
err = app.Run()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
app.Shutdown()
|
boot.Fatal(err)
|
||||||
logger.Fatal(app.Context(), err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
package migrations
|
|
||||||
|
|
||||||
import (
|
|
||||||
"database/sql"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io/ioutil"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"github.com/pressly/goose"
|
|
||||||
"isp-system-service/domain"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
insertDomain = "INSERT INTO %s.domain (id, name, description, system_id) VALUES (%d, '%s', '%s', %d) RETURNING id;"
|
|
||||||
insertService = "INSERT INTO %s.service (id, name, description, domain_id) VALUES (%d, '%s', '%s', %d) RETURNING id;"
|
|
||||||
insertApp = "INSERT INTO %s.application (id, name, description, service_id, type) VALUES (%d, '%s', '%s', %d, '%s') RETURNING id;"
|
|
||||||
insertToken = "INSERT INTO %s.token (token, app_id, expire_time) VALUES ('%s', %d, %d);"
|
|
||||||
|
|
||||||
setSeqQuery = "SELECT setval('%s.%s_id_seq' :: regclass, %d);"
|
|
||||||
|
|
||||||
initFile = "init.json"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
goose.AddMigration(Initialize.Up, Initialize.Down)
|
|
||||||
}
|
|
||||||
|
|
||||||
var Initialize = &initializeMigration{}
|
|
||||||
|
|
||||||
type initializeMigration struct {
|
|
||||||
migrationDir string
|
|
||||||
schema string
|
|
||||||
}
|
|
||||||
|
|
||||||
type identity struct {
|
|
||||||
domainId int
|
|
||||||
appId int
|
|
||||||
serviceId int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *initializeMigration) SetParams(migrationDir string, schema string) {
|
|
||||||
i.migrationDir = migrationDir
|
|
||||||
i.schema = schema
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *initializeMigration) Up(tx *sql.Tx) error {
|
|
||||||
path := filepath.Join(i.migrationDir, initFile)
|
|
||||||
bytes, err := ioutil.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "read file")
|
|
||||||
}
|
|
||||||
|
|
||||||
list := make([]domain.DomainWithService, 0)
|
|
||||||
err = json.Unmarshal(bytes, &list)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "json unmarshal")
|
|
||||||
}
|
|
||||||
|
|
||||||
lastDomainId := 0
|
|
||||||
lastServiceId := 0
|
|
||||||
lastAppId := 0
|
|
||||||
for _, domainInfo := range list {
|
|
||||||
last, err := i.insert(tx, domainInfo)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "")
|
|
||||||
}
|
|
||||||
if last.domainId > lastDomainId {
|
|
||||||
lastDomainId = last.domainId
|
|
||||||
}
|
|
||||||
if last.serviceId > lastServiceId {
|
|
||||||
lastServiceId = last.serviceId
|
|
||||||
}
|
|
||||||
if last.appId > lastAppId {
|
|
||||||
lastAppId = last.appId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
err = i.setSeq(tx, "domain", lastDomainId)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "set domain")
|
|
||||||
}
|
|
||||||
|
|
||||||
err = i.setSeq(tx, "service", lastServiceId)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "set service")
|
|
||||||
}
|
|
||||||
|
|
||||||
err = i.setSeq(tx, "application", lastAppId)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "set application")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *initializeMigration) Down(tx *sql.Tx) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *initializeMigration) insert(tx *sql.Tx, domainInfo domain.DomainWithService) (*identity, error) {
|
|
||||||
domainId, err := i.insertNode(tx, insertDomain, true, i.schema, domainInfo.Id, domainInfo.Name, domainInfo.Description, 1)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "insert domain")
|
|
||||||
}
|
|
||||||
|
|
||||||
serviceId := 0
|
|
||||||
appId := 0
|
|
||||||
for _, service := range domainInfo.Services {
|
|
||||||
serviceId, err = i.insertNode(tx, insertService, true, i.schema, service.Id, service.Name, service.Description, domainId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "insert service")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, app := range service.Apps {
|
|
||||||
appId, err = i.insertNode(tx, insertApp, true, i.schema, app.Id, app.Name, app.Description, serviceId, app.Type)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "insert application")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, t := range app.Tokens {
|
|
||||||
_, err = i.insertNode(tx, insertToken, false, i.schema, t.Token, appId, t.ExpireTime)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "insert token")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &identity{
|
|
||||||
domainId: domainId,
|
|
||||||
appId: appId,
|
|
||||||
serviceId: serviceId,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *initializeMigration) insertNode(tx *sql.Tx, query string, scan bool, args ...interface{}) (int, error) {
|
|
||||||
var id int
|
|
||||||
query = fmt.Sprintf(query, args...)
|
|
||||||
row := tx.QueryRow(query)
|
|
||||||
if scan {
|
|
||||||
err := row.Scan(&id)
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessage(err, "row scan")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return id, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *initializeMigration) setSeq(tx *sql.Tx, table string, value int) error {
|
|
||||||
q := fmt.Sprintf(setSeqQuery, i.schema, table, value)
|
|
||||||
_, err := tx.Exec(q)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "exec db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
-- +goose Up
|
|
||||||
insert into access_list (app_id, method, value)
|
|
||||||
values (1, 'admin/auth/login', true)
|
|
||||||
on conflict (app_id, method) do update set value = true;
|
|
||||||
|
|
||||||
-- +goose Down
|
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- +goose Up
|
||||||
|
update service set domain_id = 1, updated_at = now();
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
-- +goose Up
|
||||||
|
ALTER TABLE application ALTER COLUMN id DROP DEFAULT;
|
||||||
|
|
||||||
|
DROP SEQUENCE application_id_seq;
|
||||||
|
|
||||||
|
ALTER TABLE service RENAME TO application_group;
|
||||||
|
|
||||||
|
ALTER TABLE application
|
||||||
|
RENAME COLUMN service_id TO application_group_id;
|
||||||
|
|
||||||
|
ALTER INDEX uq_name_service_id
|
||||||
|
RENAME TO uq_name_application_group_id;
|
||||||
|
|
||||||
|
ALTER TABLE application
|
||||||
|
RENAME CONSTRAINT "fk_service_id__domain_id" TO "fk_application_group_id";
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
ALTER TABLE application
|
||||||
|
RENAME CONSTRAINT "fk_application_group_id" TO "fk_service_id__domain_id";
|
||||||
|
|
||||||
|
ALTER INDEX uq_name_application_group_id
|
||||||
|
RENAME TO uq_name_service_id;
|
||||||
|
|
||||||
|
ALTER TABLE application
|
||||||
|
RENAME COLUMN application_group_id TO service_id;
|
||||||
|
|
||||||
|
ALTER TABLE application_group RENAME TO service;
|
||||||
|
|
||||||
|
CREATE SEQUENCE application_id_seq;
|
||||||
|
|
||||||
|
SELECT setval(
|
||||||
|
'application_id_seq', COALESCE(
|
||||||
|
(
|
||||||
|
SELECT MAX(id)
|
||||||
|
FROM isp_system_service.application
|
||||||
|
), 1
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE application
|
||||||
|
ALTER COLUMN id
|
||||||
|
SET DEFAULT nextval('application_id_seq');
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
-- +goose Up
|
||||||
|
CREATE TABLE access_list_new
|
||||||
|
(
|
||||||
|
app_id INT,
|
||||||
|
http_method VARCHAR(255) NOT NULL DEFAULT '',
|
||||||
|
method VARCHAR(255),
|
||||||
|
value BOOLEAN NOT NULL,
|
||||||
|
PRIMARY KEY (app_id, http_method, method),
|
||||||
|
CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO access_list_new (app_id, method, value)
|
||||||
|
SELECT app_id, method, value
|
||||||
|
FROM access_list
|
||||||
|
WHERE value = true;
|
||||||
|
|
||||||
|
DROP TABLE access_list;
|
||||||
|
ALTER TABLE access_list_new RENAME TO access_list;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
CREATE TABLE access_list_old
|
||||||
|
(
|
||||||
|
app_id INT,
|
||||||
|
method VARCHAR(255),
|
||||||
|
value BOOLEAN NOT NULL,
|
||||||
|
PRIMARY KEY (app_id, method),
|
||||||
|
CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO access_list_old (app_id, method, value)
|
||||||
|
SELECT app_id, method, value
|
||||||
|
FROM access_list
|
||||||
|
WHERE value = true;
|
||||||
|
|
||||||
|
DROP TABLE access_list;
|
||||||
|
ALTER TABLE access_list_old RENAME TO access_list;
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
-- +goose Up
|
||||||
|
ALTER TABLE application_group
|
||||||
|
DROP CONSTRAINT fk_domain_id__domain_id;
|
||||||
|
ALTER TABLE application_group
|
||||||
|
DROP CONSTRAINT uq_name_domain_name;
|
||||||
|
|
||||||
|
ALTER TABLE application_group
|
||||||
|
DROP COLUMN domain_id;
|
||||||
|
|
||||||
|
ALTER TABLE application_group
|
||||||
|
ADD CONSTRAINT uq_application_group_name UNIQUE ("name");
|
||||||
|
|
||||||
|
ALTER TABLE domain
|
||||||
|
DROP CONSTRAINT fk_system_id__system_id;
|
||||||
|
|
||||||
|
ALTER TABLE domain
|
||||||
|
DROP CONSTRAINT uq_name_system_id;
|
||||||
|
|
||||||
|
DROP TABLE domain;
|
||||||
|
DROP TABLE system;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
CREATE TABLE system (
|
||||||
|
id SERIAL4 NOT NULL PRIMARY KEY,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
|
||||||
|
updated_at TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
|
||||||
|
CONSTRAINT UQ_name UNIQUE (name)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE domain (
|
||||||
|
id SERIAL4 NOT NULL PRIMARY KEY,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
system_id INTEGER NOT NULL,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
|
||||||
|
updated_at TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
|
||||||
|
CONSTRAINT FK_system_id__system_id
|
||||||
|
FOREIGN KEY (system_id)
|
||||||
|
REFERENCES system (id)
|
||||||
|
ON DELETE CASCADE
|
||||||
|
ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT UQ_name_system_id UNIQUE (name, system_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Восстанавливаем root system/domain.
|
||||||
|
INSERT INTO system (id, name)
|
||||||
|
VALUES (1, 'rootSystem');
|
||||||
|
|
||||||
|
SELECT setval(
|
||||||
|
'system_id_seq',
|
||||||
|
GREATEST((SELECT COALESCE(MAX(id), 1) FROM system), 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO domain (id, name, system_id)
|
||||||
|
VALUES (1, 'root', 1);
|
||||||
|
|
||||||
|
SELECT setval(
|
||||||
|
'domain_id_seq',
|
||||||
|
GREATEST((SELECT COALESCE(MAX(id), 1) FROM domain), 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE application_group
|
||||||
|
DROP CONSTRAINT uq_application_group_name;
|
||||||
|
|
||||||
|
ALTER TABLE application_group
|
||||||
|
ADD COLUMN domain_id INTEGER DEFAULT 1;
|
||||||
|
|
||||||
|
ALTER TABLE application_group
|
||||||
|
ALTER COLUMN domain_id SET NOT NULL;
|
||||||
|
|
||||||
|
ALTER TABLE application_group
|
||||||
|
ADD CONSTRAINT FK_domain_id__domain_id
|
||||||
|
FOREIGN KEY (domain_id)
|
||||||
|
REFERENCES domain (id)
|
||||||
|
ON DELETE CASCADE
|
||||||
|
ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
ALTER TABLE application_group
|
||||||
|
ADD CONSTRAINT UQ_name_domain_name
|
||||||
|
UNIQUE (name, domain_id);
|
||||||
|
|
||||||
|
CREATE TRIGGER modify_system
|
||||||
|
BEFORE UPDATE OR INSERT ON system
|
||||||
|
FOR EACH ROW EXECUTE PROCEDURE update_created_modified_column_date();
|
||||||
|
|
||||||
|
CREATE TRIGGER modify_domain
|
||||||
|
BEFORE UPDATE OR INSERT ON domain
|
||||||
|
FOR EACH ROW EXECUTE PROCEDURE update_created_modified_column_date();
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"name": "rootDomain",
|
|
||||||
"description": "",
|
|
||||||
"services": [
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"name": "rootService",
|
|
||||||
"description": "",
|
|
||||||
"apps": [
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"name": "admin",
|
|
||||||
"description": "",
|
|
||||||
"type": "SYSTEM",
|
|
||||||
"tokens": [
|
|
||||||
{
|
|
||||||
"token": "{{ isp_service_admin_token }}",
|
|
||||||
"expireTime": -1
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
+69
-40
@@ -4,12 +4,14 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
|
||||||
"github.com/integration-system/isp-kit/db"
|
|
||||||
"github.com/integration-system/isp-kit/db/query"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/Masterminds/squirrel"
|
||||||
|
"github.com/txix-open/isp-kit/db"
|
||||||
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AccessList struct {
|
type AccessList struct {
|
||||||
@@ -22,30 +24,38 @@ func NewAccessList(db db.DB) AccessList {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error) {
|
func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, httpMethod string, method string) (*entity.AccessList, error) {
|
||||||
q := `
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppIdAndMethod")
|
||||||
SELECT app_id, method, value
|
|
||||||
FROM access_list
|
|
||||||
WHERE app_id = $1 AND method = $2
|
|
||||||
`
|
|
||||||
result := entity.AccessList{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, appId, method)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, domain.ErrAccessListNotFound
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessagef(err, "select db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
q := `
|
||||||
|
SELECT app_id, http_method, method, value
|
||||||
|
FROM access_list
|
||||||
|
WHERE app_id = $1
|
||||||
|
AND method = $2
|
||||||
|
AND http_method IN ($3, '')
|
||||||
|
ORDER BY (http_method = $3) DESC
|
||||||
|
LIMIT 1;
|
||||||
|
`
|
||||||
|
result := entity.AccessList{}
|
||||||
|
err := r.db.SelectRow(ctx, &result, q, appId, method, httpMethod)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
return nil, domain.ErrAccessListNotFound
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
default:
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
|
func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppId")
|
||||||
|
|
||||||
q := `
|
q := `
|
||||||
SELECT app_id, method, value
|
SELECT app_id, http_method, method, value
|
||||||
FROM access_list
|
FROM access_list
|
||||||
WHERE app_id = $1
|
WHERE app_id = $1
|
||||||
`
|
`
|
||||||
result := make([]entity.AccessList, 0)
|
result := make([]entity.AccessList, 0)
|
||||||
err := r.db.Select(ctx, &result, q, appId)
|
err := r.db.Select(ctx, &result, q, appId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -56,8 +66,10 @@ func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]enti
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []int) ([]entity.AccessList, error) {
|
func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []int) ([]entity.AccessList, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppIdList")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select("app_id", "method", "value").
|
Select("app_id", "http_method", "method", "value").
|
||||||
From("access_list").
|
From("access_list").
|
||||||
Where(squirrel.Eq{"app_id": appIdList}).
|
Where(squirrel.Eq{"app_id": appIdList}).
|
||||||
ToSql()
|
ToSql()
|
||||||
@@ -68,18 +80,20 @@ func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []in
|
|||||||
result := make([]entity.AccessList, 0)
|
result := make([]entity.AccessList, 0)
|
||||||
err = r.db.Select(ctx, &result, q, args...)
|
err = r.db.Select(ctx, &result, q, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select db")
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error {
|
func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.InsertArrayAccessList")
|
||||||
|
|
||||||
qBuilder := query.New().
|
qBuilder := query.New().
|
||||||
Insert("access_list").
|
Insert("access_list").
|
||||||
Columns("app_id", "method", "value")
|
Columns("app_id", "http_method", "method", "value")
|
||||||
for _, e := range entity {
|
for _, e := range entity {
|
||||||
qBuilder = qBuilder.Values(e.AppId, e.Method, e.Value)
|
qBuilder = qBuilder.Values(e.AppId, e.HttpMethod, e.Method, e.Value)
|
||||||
}
|
}
|
||||||
q, args, err := qBuilder.ToSql()
|
q, args, err := qBuilder.ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -88,24 +102,26 @@ func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.A
|
|||||||
|
|
||||||
_, err = r.db.Exec(ctx, q, args...)
|
_, err = r.db.Exec(ctx, q, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "exec db")
|
return errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) {
|
func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.UpsertAccessList")
|
||||||
|
|
||||||
q := `
|
q := `
|
||||||
INSERT INTO access_list
|
INSERT INTO access_list
|
||||||
(app_id, method, value)
|
(app_id, http_method, method, value)
|
||||||
VALUES ($1, $2, $3)
|
VALUES ($1, $2, $3, $4)
|
||||||
ON CONFLICT (app_id, method)
|
ON CONFLICT (app_id, http_method, method)
|
||||||
DO UPDATE
|
DO UPDATE
|
||||||
SET (value) = (SELECT EXCLUDED.value)
|
SET (value) = (SELECT EXCLUDED.value)
|
||||||
`
|
`
|
||||||
result, err := r.db.Exec(ctx, q, e.AppId, e.Method, e.Value)
|
result, err := r.db.Exec(ctx, q, e.AppId, e.HttpMethod, e.Method, e.Value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, errors.WithMessage(err, "exec db")
|
return 0, errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
rowsAffected, err := result.RowsAffected()
|
rowsAffected, err := result.RowsAffected()
|
||||||
@@ -116,14 +132,25 @@ func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (
|
|||||||
return int(rowsAffected), nil
|
return int(rowsAffected), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []string) error {
|
func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.DeleteAccessList")
|
||||||
|
|
||||||
|
methodsClause := make(squirrel.Or, 0, len(methods))
|
||||||
|
for _, method := range methods {
|
||||||
|
methodsClause = append(methodsClause, squirrel.And{
|
||||||
|
squirrel.Eq{"method": method.Method},
|
||||||
|
squirrel.Eq{"http_method": method.HttpMethod},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Delete("access_list").
|
Delete("access_list").
|
||||||
Where(squirrel.Eq{
|
Where(squirrel.And{
|
||||||
"app_id": appId,
|
squirrel.Eq{
|
||||||
"method": methods,
|
"app_id": appId,
|
||||||
|
},
|
||||||
|
methodsClause,
|
||||||
}).
|
}).
|
||||||
Suffix("RETURNING app_id, method, value").
|
|
||||||
ToSql()
|
ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "build query")
|
return errors.WithMessage(err, "build query")
|
||||||
@@ -138,15 +165,17 @@ func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []s
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r AccessList) DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
|
func (r AccessList) DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.DeleteAccessListByAppId")
|
||||||
|
|
||||||
q := `
|
q := `
|
||||||
DELETE FROM access_list
|
DELETE FROM access_list
|
||||||
WHERE app_id = $1
|
WHERE app_id = $1
|
||||||
RETURNING app_id, method, value
|
RETURNING app_id, http_method, method, value
|
||||||
`
|
`
|
||||||
result := make([]entity.AccessList, 0)
|
result := make([]entity.AccessList, 0)
|
||||||
err := r.db.Select(ctx, &result, q, appId)
|
err := r.db.Select(ctx, &result, q, appId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select db")
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
|
||||||
|
"isp-system-service/domain"
|
||||||
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/Masterminds/squirrel"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"github.com/txix-open/isp-kit/db"
|
||||||
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
applicationGroupUniqueNameConstraint = "uq_application_group_name"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AppGroup struct {
|
||||||
|
db db.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAppGroup(db db.DB) AppGroup {
|
||||||
|
return AppGroup{
|
||||||
|
db: db,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r AppGroup) GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupById")
|
||||||
|
|
||||||
|
q := `
|
||||||
|
SELECT id, name, description, created_at, updated_at
|
||||||
|
FROM application_group
|
||||||
|
WHERE id = $1
|
||||||
|
`
|
||||||
|
result := entity.AppGroup{}
|
||||||
|
err := r.db.SelectRow(ctx, &result, q, id)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
return nil, domain.ErrAppGroupNotFound
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
default:
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByIdList")
|
||||||
|
|
||||||
|
q, arg, err := query.New().
|
||||||
|
Select("id", "name", "description", "created_at", "updated_at").
|
||||||
|
From("application_group").
|
||||||
|
Where(squirrel.Eq{"id": idList}).
|
||||||
|
OrderBy("created_at DESC").
|
||||||
|
ToSql()
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "build query")
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make([]entity.AppGroup, 0)
|
||||||
|
err = r.db.Select(ctx, &result, q, arg...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r AppGroup) GetAppGroupByName(ctx context.Context, name string) (*entity.AppGroup, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByName")
|
||||||
|
|
||||||
|
q := `
|
||||||
|
SELECT id, name, description, created_at, updated_at
|
||||||
|
FROM application_group
|
||||||
|
WHERE name = $1
|
||||||
|
`
|
||||||
|
result := entity.AppGroup{}
|
||||||
|
err := r.db.SelectRow(ctx, &result, q, name)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
return nil, domain.ErrAppGroupNotFound
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
default:
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.CreateAppGroup")
|
||||||
|
|
||||||
|
q := `
|
||||||
|
INSERT INTO application_group
|
||||||
|
(name, description)
|
||||||
|
VALUES ($1, $2)
|
||||||
|
ON CONFLICT (name) DO NOTHING
|
||||||
|
RETURNING id, name, description, created_at, updated_at
|
||||||
|
`
|
||||||
|
result := entity.AppGroup{}
|
||||||
|
err := r.db.SelectRow(ctx, &result, q, name, desc)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
return nil, domain.ErrAppGroupDuplicateName
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
default:
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.UpdateAppGroup")
|
||||||
|
|
||||||
|
q := `
|
||||||
|
UPDATE application_group
|
||||||
|
SET name = $1, description = $2
|
||||||
|
WHERE id = $3
|
||||||
|
RETURNING id, name, description, created_at, updated_at
|
||||||
|
`
|
||||||
|
result := entity.AppGroup{}
|
||||||
|
err := r.db.SelectRow(ctx, &result, q, name, description, id)
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &pgErr) && pgErr.ConstraintName == applicationGroupUniqueNameConstraint:
|
||||||
|
return nil, domain.ErrAppGroupDuplicateName
|
||||||
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
return nil, domain.ErrAppGroupNotFound
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
default:
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.DeleteAppGroup")
|
||||||
|
|
||||||
|
q, args, err := query.New().
|
||||||
|
Delete("application_group").
|
||||||
|
Where(squirrel.Eq{"id": idList}).
|
||||||
|
ToSql()
|
||||||
|
if err != nil {
|
||||||
|
return 0, errors.WithMessagef(err, "build query")
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := r.db.Exec(ctx, q, args...)
|
||||||
|
if err != nil {
|
||||||
|
return 0, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return 0, errors.WithMessagef(err, "get rows affected")
|
||||||
|
}
|
||||||
|
|
||||||
|
return int(rowsAffected), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r AppGroup) GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAllAppGroups")
|
||||||
|
|
||||||
|
q, arg, err := query.New().
|
||||||
|
Select("id", "name", "description", "created_at", "updated_at").
|
||||||
|
From("application_group").
|
||||||
|
OrderBy("created_at DESC").
|
||||||
|
ToSql()
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "build query")
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make([]entity.AppGroup, 0)
|
||||||
|
err = r.db.Select(ctx, &result, q, arg...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
+156
-50
@@ -4,12 +4,21 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
|
||||||
"github.com/integration-system/isp-kit/db"
|
|
||||||
"github.com/integration-system/isp-kit/db/query"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/Masterminds/squirrel"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"github.com/txix-open/isp-kit/db"
|
||||||
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
applicationPkConstraintName = "application_pkey"
|
||||||
|
applicationUniqueNameConstraintName = "uq_name_application_group_id"
|
||||||
|
applicationFkAppGroupConstraintName = "fk_application_group_id"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Application struct {
|
type Application struct {
|
||||||
@@ -23,26 +32,30 @@ func NewApplication(db db.DB) Application {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Application, error) {
|
func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Application, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationById")
|
||||||
|
|
||||||
q := `
|
q := `
|
||||||
SELECT id, name, description, service_id, type, created_at, updated_at
|
SELECT id, name, description, application_group_id, type, created_at, updated_at
|
||||||
FROM application
|
FROM application
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
`
|
`
|
||||||
result := entity.Application{}
|
result := entity.Application{}
|
||||||
err := r.db.SelectRow(ctx, &result, q, id)
|
err := r.db.SelectRow(ctx, &result, q, id)
|
||||||
if err != nil {
|
switch {
|
||||||
if err == sql.ErrNoRows {
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
return nil, domain.ErrApplicationNotFound
|
return nil, domain.ErrApplicationNotFound
|
||||||
}
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
default:
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) {
|
func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByIdList")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select("id", "name", "description", "service_id", "type", "created_at", "updated_at").
|
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
|
||||||
From("application").
|
From("application").
|
||||||
Where(squirrel.Eq{"id": idList}).
|
Where(squirrel.Eq{"id": idList}).
|
||||||
OrderBy("created_at DESC").
|
OrderBy("created_at DESC").
|
||||||
@@ -54,85 +67,109 @@ func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) (
|
|||||||
result := make([]entity.Application, 0)
|
result := make([]entity.Application, 0)
|
||||||
err = r.db.Select(ctx, &result, q, args...)
|
err = r.db.Select(ctx, &result, q, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select db")
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Application) GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error) {
|
func (r Application) GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByAppGroupIdList")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select("id", "name", "description", "service_id", "type", "created_at", "updated_at").
|
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
|
||||||
From("application").
|
From("application").
|
||||||
Where(squirrel.Eq{"service_id": serviceIdList}).
|
Where(squirrel.Eq{"application_group_id": appGroupIdList}).
|
||||||
OrderBy("created_at DESC").
|
OrderBy("created_at DESC").
|
||||||
ToSql()
|
ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "build query")
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
result := make([]entity.Application, 0)
|
result := make([]entity.Application, 0)
|
||||||
err = r.db.Select(ctx, &result, q, args...)
|
err = r.db.Select(ctx, &result, q, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select db")
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Application) GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error) {
|
func (r Application) CreateApplication(
|
||||||
q := `
|
ctx context.Context,
|
||||||
SELECT id, name, description, service_id, type, created_at, updated_at
|
id int,
|
||||||
FROM application
|
name string,
|
||||||
WHERE name = $1 AND service_id = $2
|
desc string,
|
||||||
`
|
appGroupId int,
|
||||||
result := entity.Application{}
|
appType string,
|
||||||
err := r.db.SelectRow(ctx, &result, q, name, serviceId)
|
) (*entity.Application, error) {
|
||||||
if err != nil {
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.CreateApplication")
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessagef(err, "select row db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Application) CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (
|
|
||||||
*entity.Application, error) {
|
|
||||||
q := `
|
q := `
|
||||||
INSERT INTO application
|
INSERT INTO application
|
||||||
(name, description, service_id, type)
|
(id, name, description, application_group_id, type)
|
||||||
VALUES ($1, $2, $3, $4)
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
RETURNING id, name, description, service_id, type, created_at, updated_at
|
RETURNING id, name, description, application_group_id, type, created_at, updated_at
|
||||||
`
|
`
|
||||||
result := entity.Application{}
|
result := entity.Application{}
|
||||||
err := r.db.SelectRow(ctx, &result, q, name, desc, serviceId, appType)
|
err := r.db.SelectRow(ctx, &result, q, id, name, desc, appGroupId, appType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select row db")
|
return nil, r.handleCreateError(err, q)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &result, nil
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Application) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) {
|
func (r Application) UpdateApplication(
|
||||||
|
ctx context.Context,
|
||||||
|
id int,
|
||||||
|
name string,
|
||||||
|
description string,
|
||||||
|
) (*entity.Application, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.UpdateApplication")
|
||||||
|
|
||||||
q := `
|
q := `
|
||||||
UPDATE application
|
UPDATE application
|
||||||
SET name = $2,
|
SET name = $2,
|
||||||
description = $3
|
description = $3
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
RETURNING id, name, description, service_id, type, created_at, updated_at
|
RETURNING id, name, description, application_group_id, type, created_at, updated_at
|
||||||
`
|
`
|
||||||
result := entity.Application{}
|
result := entity.Application{}
|
||||||
err := r.db.SelectRow(ctx, &result, q, id, name, description)
|
err := r.db.SelectRow(ctx, &result, q, id, name, description)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select row db")
|
return nil, r.handleUpdateError(err, q)
|
||||||
}
|
}
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Application) UpdateApplicationWithNewId(
|
||||||
|
ctx context.Context,
|
||||||
|
oldId int,
|
||||||
|
newId int,
|
||||||
|
name string,
|
||||||
|
description string,
|
||||||
|
) (*entity.Application, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.UpdateApplicationWithNewId")
|
||||||
|
|
||||||
|
q := `
|
||||||
|
UPDATE application
|
||||||
|
SET id = $2,
|
||||||
|
name = $3,
|
||||||
|
description = $4
|
||||||
|
WHERE id = $1
|
||||||
|
RETURNING id, name, description, application_group_id, type, created_at, updated_at
|
||||||
|
`
|
||||||
|
result := entity.Application{}
|
||||||
|
err := r.db.SelectRow(ctx, &result, q, oldId, newId, name, description)
|
||||||
|
if err != nil {
|
||||||
|
return nil, r.handleUpdateError(err, q)
|
||||||
|
}
|
||||||
return &result, nil
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) {
|
func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.DeleteApplicationByIdList")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Delete("application").
|
Delete("application").
|
||||||
Where(squirrel.Eq{"id": idList}).
|
Where(squirrel.Eq{"id": idList}).
|
||||||
@@ -153,3 +190,72 @@ func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int
|
|||||||
|
|
||||||
return int(rowsAffected), nil
|
return int(rowsAffected), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r Application) NextApplicationId(ctx context.Context) (int, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.NextApplicationId")
|
||||||
|
|
||||||
|
q := `SELECT COALESCE(MAX(id)+1, 1) FROM application;`
|
||||||
|
nextAppId := 0
|
||||||
|
err := r.db.SelectRow(ctx, &nextAppId, q)
|
||||||
|
if err != nil {
|
||||||
|
return -1, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
return nextAppId, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Application) GetAllApplications(ctx context.Context) ([]entity.Application, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetAllApplications")
|
||||||
|
|
||||||
|
q, args, err := query.New().
|
||||||
|
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
|
||||||
|
From("application").
|
||||||
|
OrderBy("created_at DESC").
|
||||||
|
ToSql()
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make([]entity.Application, 0)
|
||||||
|
err = r.db.Select(ctx, &result, q, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Application) handleCreateError(err error, q string) error {
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if !errors.As(err, &pgErr) {
|
||||||
|
return errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
switch pgErr.ConstraintName {
|
||||||
|
case applicationPkConstraintName:
|
||||||
|
return domain.ErrApplicationDuplicateId
|
||||||
|
case applicationUniqueNameConstraintName:
|
||||||
|
return domain.ErrApplicationDuplicateName
|
||||||
|
case applicationFkAppGroupConstraintName:
|
||||||
|
return domain.ErrAppGroupNotFound
|
||||||
|
}
|
||||||
|
return errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Application) handleUpdateError(err error, q string) error {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return domain.ErrApplicationNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if !errors.As(err, &pgErr) {
|
||||||
|
return errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch pgErr.ConstraintName {
|
||||||
|
case applicationPkConstraintName:
|
||||||
|
return domain.ErrApplicationDuplicateId
|
||||||
|
case applicationUniqueNameConstraintName:
|
||||||
|
return domain.ErrApplicationDuplicateName
|
||||||
|
default:
|
||||||
|
return errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"database/sql"
|
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
|
||||||
"github.com/integration-system/isp-kit/db"
|
|
||||||
"github.com/integration-system/isp-kit/db/query"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
|
||||||
"isp-system-service/entity"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Domain struct {
|
|
||||||
db db.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDomain(db db.DB) Domain {
|
|
||||||
return Domain{
|
|
||||||
db: db,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Domain) GetDomainById(ctx context.Context, id int) (*entity.Domain, error) {
|
|
||||||
q := `
|
|
||||||
SELECT id, name, description, system_id, created_at, updated_at
|
|
||||||
FROM domain
|
|
||||||
WHERE id = $1
|
|
||||||
`
|
|
||||||
result := entity.Domain{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, id)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, domain.ErrDomainNotFound
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.Domain, error) {
|
|
||||||
q, args, err := query.New().
|
|
||||||
Select("id", "name", "description", "system_id", "created_at", "updated_at").
|
|
||||||
From("domain").
|
|
||||||
Where(squirrel.Eq{"id": idList}).
|
|
||||||
ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]entity.Domain, 0)
|
|
||||||
err = r.db.Select(ctx, &result, q, args...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "select db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Domain) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) {
|
|
||||||
q := `
|
|
||||||
SELECT id, name, description, system_id, created_at, updated_at
|
|
||||||
FROM domain
|
|
||||||
WHERE system_id = $1
|
|
||||||
ORDER BY created_at DESC
|
|
||||||
`
|
|
||||||
result := make([]entity.Domain, 0)
|
|
||||||
err := r.db.Select(ctx, &result, q, systemId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "select db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Domain) GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) {
|
|
||||||
q := `
|
|
||||||
SELECT id, name, description, system_id, created_at, updated_at
|
|
||||||
FROM domain
|
|
||||||
WHERE name = $1 AND system_id = $2
|
|
||||||
`
|
|
||||||
result := entity.Domain{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, name, systemId)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, domain.ErrDomainNotFound
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Domain) CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) {
|
|
||||||
q := `
|
|
||||||
INSERT INTO domain
|
|
||||||
(name, description, system_id)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, name, description, system_id, created_at, updated_at
|
|
||||||
`
|
|
||||||
result := entity.Domain{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, name, desc, systemId)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, domain.ErrDomainNotFound
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Domain) UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) {
|
|
||||||
q := `
|
|
||||||
UPDATE domain
|
|
||||||
SET name = $1, description = $2
|
|
||||||
WHERE id = $3
|
|
||||||
RETURNING id, name, description, system_id, created_at, updated_at
|
|
||||||
`
|
|
||||||
result := entity.Domain{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, name, description, id)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, domain.ErrDomainNotFound
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
|
||||||
}
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) {
|
|
||||||
q, args, err := query.New().
|
|
||||||
Delete("domain").
|
|
||||||
Where(squirrel.Eq{"id": idList}).
|
|
||||||
ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessagef(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := r.db.Exec(ctx, q, args...)
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessagef(err, "exec db")
|
|
||||||
}
|
|
||||||
|
|
||||||
rowsAffected, err := result.RowsAffected()
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessagef(err, "get rows affected")
|
|
||||||
}
|
|
||||||
|
|
||||||
return int(rowsAffected), nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"hash/fnv"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/db"
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
prefix = "msp-service-template"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Locker struct {
|
||||||
|
db db.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLocker(db db.DB) Locker {
|
||||||
|
return Locker{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l Locker) TryLock(ctx context.Context, key string) (bool, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Locker.TryLock")
|
||||||
|
|
||||||
|
hash := fnv.New32a()
|
||||||
|
_, err := hash.Write([]byte(prefix + key))
|
||||||
|
if err != nil {
|
||||||
|
return false, errors.WithMessage(err, "generate hash")
|
||||||
|
}
|
||||||
|
sum := hash.Sum32()
|
||||||
|
|
||||||
|
acquired := false
|
||||||
|
err = l.db.SelectRow(ctx, &acquired, "SELECT pg_try_advisory_xact_lock($1)", sum)
|
||||||
|
if err != nil {
|
||||||
|
return false, errors.WithMessage(err, "pg try acquire advisory lock")
|
||||||
|
}
|
||||||
|
return acquired, nil
|
||||||
|
}
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"database/sql"
|
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
|
||||||
"github.com/integration-system/isp-kit/db"
|
|
||||||
"github.com/integration-system/isp-kit/db/query"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
|
||||||
"isp-system-service/entity"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Service struct {
|
|
||||||
db db.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewService(db db.DB) Service {
|
|
||||||
return Service{
|
|
||||||
db: db,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Service) GetServiceById(ctx context.Context, id int) (*entity.Service, error) {
|
|
||||||
q := `
|
|
||||||
SELECT id, name, description, domain_id, created_at, updated_at
|
|
||||||
FROM service
|
|
||||||
WHERE id = $1
|
|
||||||
`
|
|
||||||
result := entity.Service{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, id)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, domain.ErrServiceNotFound
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Service) GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error) {
|
|
||||||
q, arg, err := query.New().
|
|
||||||
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
|
|
||||||
From("service").
|
|
||||||
Where(squirrel.Eq{"id": idList}).
|
|
||||||
OrderBy("created_at DESC").
|
|
||||||
ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]entity.Service, 0)
|
|
||||||
err = r.db.Select(ctx, &result, q, arg...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "select db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Service) GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) {
|
|
||||||
q, arg, err := query.New().
|
|
||||||
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
|
|
||||||
From("service").
|
|
||||||
Where(squirrel.Eq{"domain_id": domainIdList}).
|
|
||||||
OrderBy("created_at DESC").
|
|
||||||
ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]entity.Service, 0)
|
|
||||||
err = r.db.Select(ctx, &result, q, arg...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "select db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Service) GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error) {
|
|
||||||
q := `
|
|
||||||
SELECT id, name, description, domain_id, created_at, updated_at
|
|
||||||
FROM service
|
|
||||||
WHERE name = $1 AND domain_id = $2
|
|
||||||
`
|
|
||||||
result := entity.Service{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, name, domainId)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, domain.ErrServiceNotFound
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessage(err, "select db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Service) CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error) {
|
|
||||||
q := `
|
|
||||||
INSERT INTO service
|
|
||||||
(name, description, domain_id)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, name, description, domain_id, created_at, updated_at
|
|
||||||
`
|
|
||||||
result := entity.Service{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, name, desc, domainId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Service) UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error) {
|
|
||||||
q := `
|
|
||||||
UPDATE service
|
|
||||||
SET name = $1, description = $2
|
|
||||||
WHERE id = $3
|
|
||||||
RETURNING id, name, description, domain_id, created_at, updated_at
|
|
||||||
`
|
|
||||||
result := entity.Service{}
|
|
||||||
err := r.db.SelectRow(ctx, &result, q, name, description, id)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, domain.ErrServiceNotFound
|
|
||||||
}
|
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r Service) DeleteService(ctx context.Context, idList []int) (int, error) {
|
|
||||||
q, args, err := query.New().
|
|
||||||
Delete("service").
|
|
||||||
Where(squirrel.Eq{"id": idList}).
|
|
||||||
ToSql()
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessagef(err, "build query")
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := r.db.Exec(ctx, q, args...)
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessagef(err, "exec db")
|
|
||||||
}
|
|
||||||
|
|
||||||
rowsAffected, err := result.RowsAffected()
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessagef(err, "get rows affected")
|
|
||||||
}
|
|
||||||
|
|
||||||
return int(rowsAffected), nil
|
|
||||||
}
|
|
||||||
+38
-27
@@ -4,12 +4,14 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
|
||||||
"github.com/Masterminds/squirrel"
|
|
||||||
"github.com/integration-system/isp-kit/db"
|
|
||||||
"github.com/integration-system/isp-kit/db/query"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/Masterminds/squirrel"
|
||||||
|
"github.com/txix-open/isp-kit/db"
|
||||||
|
"github.com/txix-open/isp-kit/db/query"
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Token struct {
|
type Token struct {
|
||||||
@@ -23,12 +25,14 @@ func NewToken(db db.DB) Token {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) {
|
func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.SaveToken")
|
||||||
|
|
||||||
q := `
|
q := `
|
||||||
INSERT INTO token
|
INSERT INTO token
|
||||||
(token, app_id, expire_time)
|
(token, app_id, expire_time)
|
||||||
VALUES ($1, $2, $3)
|
VALUES ($1, $2, $3)
|
||||||
RETURNING token, app_id, expire_time, created_at
|
RETURNING token, app_id, expire_time, created_at
|
||||||
`
|
`
|
||||||
result := entity.Token{}
|
result := entity.Token{}
|
||||||
err := r.db.SelectRow(ctx, &result, q, token, appId, expireTime)
|
err := r.db.SelectRow(ctx, &result, q, token, appId, expireTime)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -39,21 +43,28 @@ func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTim
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, error) {
|
func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.GetTokenById")
|
||||||
|
|
||||||
q := `
|
q := `
|
||||||
SELECT token, app_id, expire_time, created_at
|
SELECT token, app_id, expire_time, created_at
|
||||||
FROM system
|
FROM token
|
||||||
WHERE token = $1
|
WHERE token = $1
|
||||||
`
|
`
|
||||||
result := entity.Token{}
|
result := entity.Token{}
|
||||||
err := r.db.SelectRow(ctx, &result, q, token)
|
err := r.db.SelectRow(ctx, &result, q, token)
|
||||||
if err != nil {
|
switch {
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
return nil, nil //nolint:nilnil
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
default:
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) {
|
func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.GetTokenByAppIdList")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select("token", "app_id", "expire_time", "created_at").
|
Select("token", "app_id", "expire_time", "created_at").
|
||||||
From("token").
|
From("token").
|
||||||
@@ -67,13 +78,15 @@ func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]enti
|
|||||||
result := make([]entity.Token, 0)
|
result := make([]entity.Token, 0)
|
||||||
err = r.db.Select(ctx, &result, q, args...)
|
err = r.db.Select(ctx, &result, q, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "select db")
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
|
func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.DeleteToken")
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Delete("token").
|
Delete("token").
|
||||||
Where(squirrel.Eq{"token": tokens}).
|
Where(squirrel.Eq{"token": tokens}).
|
||||||
@@ -84,7 +97,7 @@ func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
|
|||||||
|
|
||||||
result, err := r.db.Exec(ctx, q, args...)
|
result, err := r.db.Exec(ctx, q, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, errors.WithMessagef(err, "exec db")
|
return 0, errors.WithMessagef(err, "exec query %s", q)
|
||||||
}
|
}
|
||||||
|
|
||||||
rowsAffected, err := result.RowsAffected()
|
rowsAffected, err := result.RowsAffected()
|
||||||
@@ -96,25 +109,23 @@ func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r Token) AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error) {
|
func (r Token) AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error) {
|
||||||
|
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.AuthDataByToken")
|
||||||
|
|
||||||
q := `
|
q := `
|
||||||
SELECT system_id, domain_id, service_id, app_id, token.expire_time, token.created_at
|
SELECT app_id, application.name AS app_name , token.expire_time, token.created_at
|
||||||
FROM token
|
FROM token
|
||||||
LEFT JOIN application
|
LEFT JOIN application
|
||||||
ON token.app_id = application.id
|
ON token.app_id = application.id
|
||||||
LEFT JOIN service
|
|
||||||
ON application.service_id = service.id
|
|
||||||
LEFT JOIN domain
|
|
||||||
ON service.domain_id = domain.id
|
|
||||||
WHERE token = $1
|
WHERE token = $1
|
||||||
`
|
`
|
||||||
result := entity.AuthData{}
|
result := entity.AuthData{}
|
||||||
err := r.db.SelectRow(ctx, &result, q, token)
|
err := r.db.SelectRow(ctx, &result, q, token)
|
||||||
if err != nil {
|
switch {
|
||||||
if err == sql.ErrNoRows {
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
return nil, domain.ErrTokenNotFound
|
return nil, domain.ErrTokenNotFound
|
||||||
}
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "select row db")
|
return nil, errors.WithMessagef(err, "exec query %s", q)
|
||||||
|
default:
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
}
|
||||||
+97
-66
@@ -1,18 +1,19 @@
|
|||||||
package routes
|
package routes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/integration-system/isp-kit/cluster"
|
|
||||||
"github.com/integration-system/isp-kit/grpc"
|
|
||||||
"github.com/integration-system/isp-kit/grpc/endpoint"
|
|
||||||
"github.com/integration-system/isp-kit/grpc/isp"
|
|
||||||
"isp-system-service/controller"
|
"isp-system-service/controller"
|
||||||
|
"isp-system-service/docs"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/cluster"
|
||||||
|
"github.com/txix-open/isp-kit/common_endpoints"
|
||||||
|
"github.com/txix-open/isp-kit/grpc"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Controllers struct {
|
type Controllers struct {
|
||||||
AccessList controller.AccessList
|
AccessList controller.AccessList
|
||||||
Domain controller.Domain
|
|
||||||
Service controller.Service
|
|
||||||
Application controller.Application
|
Application controller.Application
|
||||||
|
AppGroup controller.AppGroup
|
||||||
Token controller.Token
|
Token controller.Token
|
||||||
Secure controller.Secure
|
Secure controller.Secure
|
||||||
}
|
}
|
||||||
@@ -21,7 +22,7 @@ func EndpointDescriptors() []cluster.EndpointDescriptor {
|
|||||||
return endpointDescriptors(Controllers{})
|
return endpointDescriptors(Controllers{})
|
||||||
}
|
}
|
||||||
|
|
||||||
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
|
func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux {
|
||||||
muxer := grpc.NewMux()
|
muxer := grpc.NewMux()
|
||||||
for _, descriptor := range endpointDescriptors(c) {
|
for _, descriptor := range endpointDescriptors(c) {
|
||||||
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||||
@@ -30,14 +31,14 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||||
return concatCluster([][]cluster.EndpointDescriptor{
|
return concatEndpoints(
|
||||||
secureCluster(c),
|
secureCluster(c),
|
||||||
accessListCluster(c),
|
accessListCluster(c),
|
||||||
domainCluster(c),
|
|
||||||
serviceCluster(c),
|
|
||||||
applicationCluster(c),
|
applicationCluster(c),
|
||||||
tokenCluster(c),
|
tokenCluster(c),
|
||||||
})
|
applicationGroupCluster(c),
|
||||||
|
commonEndpoints(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func secureCluster(c Controllers) []cluster.EndpointDescriptor {
|
func secureCluster(c Controllers) []cluster.EndpointDescriptor {
|
||||||
@@ -60,72 +61,32 @@ func accessListCluster(c Controllers) []cluster.EndpointDescriptor {
|
|||||||
{
|
{
|
||||||
Path: "system/access_list/get_by_id",
|
Path: "system/access_list/get_by_id",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("app_access_view"),
|
||||||
Handler: c.AccessList.GetById,
|
Handler: c.AccessList.GetById,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/access_list/set_one",
|
Path: "system/access_list/set_one",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("app_access_edit"),
|
||||||
Handler: c.AccessList.SetOne,
|
Handler: c.AccessList.SetOne,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/access_list/set_list",
|
Path: "system/access_list/set_list",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("app_access_edit"),
|
||||||
Handler: c.AccessList.SetList,
|
Handler: c.AccessList.SetList,
|
||||||
},
|
},
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func domainCluster(c Controllers) []cluster.EndpointDescriptor {
|
|
||||||
return []cluster.EndpointDescriptor{
|
|
||||||
{
|
{
|
||||||
Path: "system/domain/get_domains_by_system_id",
|
Path: "system/access_list/delete_list",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.Domain.GetBySystemId,
|
Extra: cluster.RequireAdminPermission("app_access_edit"),
|
||||||
|
Handler: c.AccessList.DeleteList,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/domain/create_update_domain",
|
Path: "system/access_list/delete_list_with_methods",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.Domain.CreateUpdate,
|
Extra: cluster.RequireAdminPermission("app_access_edit"),
|
||||||
},
|
Handler: c.AccessList.DeleteListWithMethods,
|
||||||
{
|
|
||||||
Path: "system/domain/get_domain_by_id",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Domain.GetById,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "system/domain/delete_domains",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Domain.Delete,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func serviceCluster(c Controllers) []cluster.EndpointDescriptor {
|
|
||||||
return []cluster.EndpointDescriptor{
|
|
||||||
{
|
|
||||||
Path: "system/service/get_service",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Service.Get,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "system/service/get_services_by_domain_id",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Service.GetByDomainId,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "system/service/create_update_service",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Service.CreateUpdate,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "system/service/get_service_by_id",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Service.GetById,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "system/service/delete_service",
|
|
||||||
Inner: true,
|
|
||||||
Handler: c.Service.Delete,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -135,32 +96,60 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
|
|||||||
{
|
{
|
||||||
Path: "system/application/get_applications",
|
Path: "system/application/get_applications",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_view"),
|
||||||
Handler: c.Application.GetByIdList,
|
Handler: c.Application.GetByIdList,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/application/get_applications_by_service_id",
|
Path: "system/application/get_by_app_group",
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_view"),
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.Application.GetByServiceId,
|
Handler: c.Application.GetByAppGroup,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/application/create_update_application",
|
Path: "system/application/create_update_application",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_app_edit"),
|
||||||
Handler: c.Application.CreateUpdate,
|
Handler: c.Application.CreateUpdate,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/application/get_application_by_id",
|
Path: "system/application/get_application_by_id",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_view"),
|
||||||
Handler: c.Application.GetById,
|
Handler: c.Application.GetById,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Path: "system/application/get_application_by_token",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_view"),
|
||||||
|
Handler: c.Application.GetByToken,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
Path: "system/application/delete_applications",
|
Path: "system/application/delete_applications",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_app_delete"),
|
||||||
Handler: c.Application.Delete,
|
Handler: c.Application.Delete,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/application/get_system_tree",
|
Path: "system/application/next_id",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
Handler: c.Application.GetSystemTree,
|
Handler: c.Application.NextId,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Path: "system/application/get_all",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_view"),
|
||||||
|
Handler: c.Application.GetAll,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Path: "system/application/create_application",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_app_add"),
|
||||||
|
Handler: c.Application.Create,
|
||||||
|
}, {
|
||||||
|
Path: "system/application/update_application",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_app_edit"),
|
||||||
|
Handler: c.Application.Update,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -170,29 +159,71 @@ func tokenCluster(c Controllers) []cluster.EndpointDescriptor {
|
|||||||
{
|
{
|
||||||
Path: "system/token/create_token",
|
Path: "system/token/create_token",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_token_add"),
|
||||||
Handler: c.Token.Create,
|
Handler: c.Token.Create,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/token/revoke_tokens",
|
Path: "system/token/revoke_tokens",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_token_delete"),
|
||||||
Handler: c.Token.Revoke,
|
Handler: c.Token.Revoke,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/token/revoke_tokens_for_app",
|
Path: "system/token/revoke_tokens_for_app",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_token_delete"),
|
||||||
Handler: c.Token.RevokeForApp,
|
Handler: c.Token.RevokeForApp,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "system/token/get_tokens_by_app_id",
|
Path: "system/token/get_tokens_by_app_id",
|
||||||
Inner: true,
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_token_view"),
|
||||||
Handler: c.Token.GetByAppId,
|
Handler: c.Token.GetByAppId,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func concatCluster(clusters [][]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
|
func applicationGroupCluster(c Controllers) []cluster.EndpointDescriptor {
|
||||||
|
return []cluster.EndpointDescriptor{
|
||||||
|
{
|
||||||
|
Path: "system/application_group/create",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_add"),
|
||||||
|
Handler: c.AppGroup.Create,
|
||||||
|
}, {
|
||||||
|
Path: "system/application_group/update",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_edit"),
|
||||||
|
Handler: c.AppGroup.Update,
|
||||||
|
}, {
|
||||||
|
Path: "system/application_group/delete_list",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_delete"),
|
||||||
|
Handler: c.AppGroup.DeleteList,
|
||||||
|
}, {
|
||||||
|
Path: "system/application_group/get_by_id_list",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_view"),
|
||||||
|
Handler: c.AppGroup.GetByIdList,
|
||||||
|
}, {
|
||||||
|
Path: "system/application_group/get_all",
|
||||||
|
Inner: true,
|
||||||
|
Extra: cluster.RequireAdminPermission("application_group_view"),
|
||||||
|
Handler: c.AppGroup.GetAll,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func commonEndpoints() []cluster.EndpointDescriptor {
|
||||||
|
return common_endpoints.CommonEndpoints(
|
||||||
|
"system",
|
||||||
|
common_endpoints.WithSwaggerEndpoint(docs.SwaggerJson),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concatEndpoints(endpoints ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
|
||||||
var result []cluster.EndpointDescriptor
|
var result []cluster.EndpointDescriptor
|
||||||
for _, c := range clusters {
|
for _, c := range endpoints {
|
||||||
result = append(result, c...)
|
result = append(result, c...)
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
|
|||||||
+75
-42
@@ -3,69 +3,68 @@ package service
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type IAccessListAccessListRep interface {
|
type AccessListRepo interface {
|
||||||
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
|
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
|
||||||
|
DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type IAccessListApplicationRep interface {
|
type AccessListSetOneTx interface {
|
||||||
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type IAccessListSetOneTx interface {
|
|
||||||
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
|
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type IAccessListSetListTx interface {
|
type AccessListSetListTx interface {
|
||||||
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
|
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
|
||||||
InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error
|
InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error
|
||||||
DeleteAccessList(ctx context.Context, appId int, methods []string) error
|
DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error
|
||||||
DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
|
DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type IAccessListTxRunner interface {
|
type AccessListTxRunner interface {
|
||||||
AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetOneTx) error) error
|
AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx AccessListSetOneTx) error) error
|
||||||
AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetListTx) error) error
|
AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx AccessListSetListTx) error) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type AccessList struct {
|
type AccessList struct {
|
||||||
tx IAccessListTxRunner
|
tx AccessListTxRunner
|
||||||
accessListRep IAccessListAccessListRep
|
accessListRepo AccessListRepo
|
||||||
applicationRep IAccessListApplicationRep
|
appRepo ApplicationRepo
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewAccessList(
|
func NewAccessList(
|
||||||
tx IAccessListTxRunner,
|
tx AccessListTxRunner,
|
||||||
accessListRep IAccessListAccessListRep,
|
accessListRepo AccessListRepo,
|
||||||
applicationRep IAccessListApplicationRep,
|
appRepo ApplicationRepo,
|
||||||
) AccessList {
|
) AccessList {
|
||||||
return AccessList{
|
return AccessList{
|
||||||
tx: tx,
|
tx: tx,
|
||||||
accessListRep: accessListRep,
|
accessListRepo: accessListRepo,
|
||||||
applicationRep: applicationRep,
|
appRepo: appRepo,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error) {
|
func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error) {
|
||||||
_, err := s.applicationRep.GetApplicationById(ctx, appId)
|
_, err := s.appRepo.GetApplicationById(ctx, appId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get application by id")
|
return nil, errors.WithMessage(err, "get application by id")
|
||||||
}
|
}
|
||||||
|
|
||||||
accessList, err := s.accessListRep.GetAccessListByAppId(ctx, appId)
|
accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, appId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "get access list by app_id")
|
return nil, errors.WithMessage(err, "get access list by app_id")
|
||||||
}
|
}
|
||||||
|
|
||||||
methodInfos := make([]domain.MethodInfo, len(accessList))
|
methodInfos := make([]domain.MethodInfo, len(accessList))
|
||||||
for i, access := range accessList {
|
for i, access := range accessList {
|
||||||
methodInfos[i] = domain.MethodInfo{
|
methodInfos[i] = domain.MethodInfo{
|
||||||
Method: access.Method,
|
HttpMethod: access.HttpMethod,
|
||||||
Value: access.Value,
|
Method: access.Method,
|
||||||
|
Value: access.Value,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,20 +72,21 @@ func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
|
func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
|
||||||
_, err := s.applicationRep.GetApplicationById(ctx, request.AppId)
|
_, err := s.appRepo.GetApplicationById(ctx, request.AppId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get application by id")
|
return nil, errors.WithMessage(err, "get application by id")
|
||||||
}
|
}
|
||||||
|
|
||||||
var resp int
|
var resp int
|
||||||
err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx IAccessListSetOneTx) error {
|
err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx AccessListSetOneTx) error {
|
||||||
resp, err = tx.UpsertAccessList(ctx, entity.AccessList{
|
resp, err = tx.UpsertAccessList(ctx, entity.AccessList{
|
||||||
AppId: request.AppId,
|
AppId: request.AppId,
|
||||||
Method: request.Method,
|
HttpMethod: request.HttpMethod,
|
||||||
Value: request.Value,
|
Method: request.Method,
|
||||||
|
Value: request.Value,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessagef(err, "upsert access list")
|
return errors.WithMessage(err, "upsert access list")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -101,12 +101,12 @@ func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneR
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
|
func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
|
||||||
_, err := s.applicationRep.GetApplicationById(ctx, req.AppId)
|
_, err := s.appRepo.GetApplicationById(ctx, req.AppId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get application by id")
|
return nil, errors.WithMessage(err, "get application by id")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = s.tx.AccessListSetListTx(ctx, func(ctx context.Context, tx IAccessListSetListTx) error {
|
err = s.tx.AccessListSetListTx(ctx, func(ctx context.Context, tx AccessListSetListTx) error {
|
||||||
if req.RemoveOld {
|
if req.RemoveOld {
|
||||||
_, err = tx.DeleteAccessListByAppId(ctx, req.AppId)
|
_, err = tx.DeleteAccessListByAppId(ctx, req.AppId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -115,13 +115,17 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq
|
|||||||
}
|
}
|
||||||
|
|
||||||
newAccessList := make([]entity.AccessList, len(req.Methods))
|
newAccessList := make([]entity.AccessList, len(req.Methods))
|
||||||
updateMethods := make([]string, len(req.Methods))
|
updateMethods := make([]entity.Method, len(req.Methods))
|
||||||
for i, m := range req.Methods {
|
for i, m := range req.Methods {
|
||||||
updateMethods[i] = m.Method
|
updateMethods[i] = entity.Method{
|
||||||
|
HttpMethod: m.HttpMethod,
|
||||||
|
Method: m.Method,
|
||||||
|
}
|
||||||
newAccessList[i] = entity.AccessList{
|
newAccessList[i] = entity.AccessList{
|
||||||
AppId: req.AppId,
|
AppId: req.AppId,
|
||||||
Method: m.Method,
|
HttpMethod: m.HttpMethod,
|
||||||
Value: m.Value,
|
Method: m.Method,
|
||||||
|
Value: m.Value,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,18 +147,47 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq
|
|||||||
return nil, errors.WithMessage(err, "transaction access list set list")
|
return nil, errors.WithMessage(err, "transaction access list set list")
|
||||||
}
|
}
|
||||||
|
|
||||||
accessList, err := s.accessListRep.GetAccessListByAppId(ctx, req.AppId)
|
accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, req.AppId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "get access list by app_id")
|
return nil, errors.WithMessage(err, "get access list by app_id")
|
||||||
}
|
}
|
||||||
|
|
||||||
methodInfos := make([]domain.MethodInfo, len(accessList))
|
methodInfos := make([]domain.MethodInfo, len(accessList))
|
||||||
for i, access := range accessList {
|
for i, access := range accessList {
|
||||||
methodInfos[i] = domain.MethodInfo{
|
methodInfos[i] = domain.MethodInfo{
|
||||||
Method: access.Method,
|
HttpMethod: access.HttpMethod,
|
||||||
Value: access.Value,
|
Method: access.Method,
|
||||||
|
Value: access.Value,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return methodInfos, nil
|
return methodInfos, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s AccessList) DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error {
|
||||||
|
methods := make([]domain.Method, 0, len(req.Methods))
|
||||||
|
for _, method := range req.Methods {
|
||||||
|
methods = append(methods, domain.Method{Method: method})
|
||||||
|
}
|
||||||
|
return s.DeleteListWithMethods(ctx, domain.AccessListDeleteV2ListRequest{
|
||||||
|
AppId: req.AppId,
|
||||||
|
Methods: methods,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s AccessList) DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error {
|
||||||
|
_, err := s.appRepo.GetApplicationById(ctx, req.AppId)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "get application by id")
|
||||||
|
}
|
||||||
|
|
||||||
|
methods := make([]entity.Method, 0, len(req.Methods))
|
||||||
|
for _, method := range req.Methods {
|
||||||
|
methods = append(methods, entity.Method{Method: method.Method, HttpMethod: method.HttpMethod})
|
||||||
|
}
|
||||||
|
err = s.accessListRepo.DeleteAccessList(ctx, req.AppId, methods)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "delete access_list")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"isp-system-service/domain"
|
||||||
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AppGroup struct {
|
||||||
|
repo AppGroupRepo
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAppGroup(repo AppGroupRepo) AppGroup {
|
||||||
|
return AppGroup{
|
||||||
|
repo: repo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) {
|
||||||
|
appGroup, err := s.repo.CreateAppGroup(ctx, req.Name, req.Description)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "create appGroup")
|
||||||
|
}
|
||||||
|
converted := s.convertAppGroup(*appGroup)
|
||||||
|
return &converted, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) {
|
||||||
|
appGroup, err := s.repo.UpdateAppGroup(ctx, req.Id, req.Name, req.Description)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "update appGroup")
|
||||||
|
}
|
||||||
|
converted := s.convertAppGroup(*appGroup)
|
||||||
|
return &converted, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) {
|
||||||
|
deleted, err := s.repo.DeleteAppGroup(ctx, req.IdList)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "delete appGroup")
|
||||||
|
}
|
||||||
|
return &domain.DeleteResponse{
|
||||||
|
Deleted: deleted,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s AppGroup) GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error) {
|
||||||
|
appGroups, err := s.repo.GetAppGroupByIdList(ctx, idList)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "get appGroups by id list")
|
||||||
|
}
|
||||||
|
result := make([]domain.AppGroup, 0, len(appGroups))
|
||||||
|
for _, appGroup := range appGroups {
|
||||||
|
result = append(result, s.convertAppGroup(appGroup))
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s AppGroup) GetAll(ctx context.Context) ([]domain.AppGroup, error) {
|
||||||
|
appGroups, err := s.repo.GetAllAppGroups(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "get all appGroups")
|
||||||
|
}
|
||||||
|
result := make([]domain.AppGroup, 0, len(appGroups))
|
||||||
|
for _, appGroup := range appGroups {
|
||||||
|
result = append(result, s.convertAppGroup(appGroup))
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s AppGroup) convertAppGroup(appGroup entity.AppGroup) domain.AppGroup {
|
||||||
|
return domain.AppGroup{
|
||||||
|
Id: appGroup.Id,
|
||||||
|
Name: appGroup.Name,
|
||||||
|
Description: appGroup.Description.String,
|
||||||
|
CreatedAt: appGroup.CreatedAt,
|
||||||
|
UpdatedAt: appGroup.UpdatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
+110
-188
@@ -3,233 +3,121 @@ package service
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type IApplicationApplicationRep interface {
|
type ApplicationDeleteTx interface {
|
||||||
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
|
|
||||||
GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error)
|
|
||||||
GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error)
|
|
||||||
GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error)
|
|
||||||
CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (*entity.Application, error)
|
|
||||||
UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type IApplicationTokenRep interface {
|
|
||||||
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type IApplicationServiceRep interface {
|
|
||||||
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
|
|
||||||
GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type IApplicationDomainRep interface {
|
|
||||||
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type IApplicationDeleteTx interface {
|
|
||||||
DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error)
|
DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type IApplicationTxRunner interface {
|
type ApplicationTxRunner interface {
|
||||||
ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx IApplicationDeleteTx) error) error
|
ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx ApplicationDeleteTx) error) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type Application struct {
|
type Application struct {
|
||||||
tx IApplicationTxRunner
|
txRunner ApplicationTxRunner
|
||||||
applicationRep IApplicationApplicationRep
|
appRepo ApplicationRepo
|
||||||
domainRep IApplicationDomainRep
|
serviceRepo AppGroupRepo
|
||||||
serviceRep IApplicationServiceRep
|
tokenRepo TokenRepo
|
||||||
tokenRep IApplicationTokenRep
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewApplication(
|
func NewApplication(
|
||||||
tx IApplicationTxRunner,
|
txRunner ApplicationTxRunner,
|
||||||
applicationRep IApplicationApplicationRep,
|
applicationRepo ApplicationRepo,
|
||||||
domainRep IApplicationDomainRep,
|
appGroupRepo AppGroupRepo,
|
||||||
serviceRep IApplicationServiceRep,
|
tokenRepo TokenRepo,
|
||||||
tokenRep IApplicationTokenRep,
|
|
||||||
) Application {
|
) Application {
|
||||||
return Application{
|
return Application{
|
||||||
tx: tx,
|
txRunner: txRunner,
|
||||||
applicationRep: applicationRep,
|
appRepo: applicationRepo,
|
||||||
domainRep: domainRep,
|
serviceRepo: appGroupRepo,
|
||||||
serviceRep: serviceRep,
|
tokenRepo: tokenRepo,
|
||||||
tokenRep: tokenRep,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Application) GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error) {
|
func (s Application) GetById(ctx context.Context, appId int) (*domain.Application, error) {
|
||||||
application, err := s.applicationRep.GetApplicationById(ctx, appId)
|
app, err := s.appRepo.GetApplicationById(ctx, appId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get application by id")
|
return nil, errors.WithMessage(err, "get application by id")
|
||||||
}
|
}
|
||||||
|
|
||||||
arr, err := s.EnrichWithTokens(ctx, []entity.Application{*application})
|
return new(s.convertApplication(*app)), nil
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "enrich application with tokens")
|
|
||||||
}
|
|
||||||
|
|
||||||
return arr[0], nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error) {
|
func (s Application) GetByToken(ctx context.Context, tokenStr string) (*domain.GetApplicationByTokenResponse, error) {
|
||||||
res, err := s.applicationRep.GetApplicationByIdList(ctx, idList)
|
token, err := s.tokenRepo.GetTokenById(ctx, tokenStr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "get token by id")
|
||||||
|
}
|
||||||
|
if token == nil {
|
||||||
|
return nil, domain.ErrApplicationNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
app, err := s.appRepo.GetApplicationById(ctx, token.AppId)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "get app by id")
|
||||||
|
}
|
||||||
|
return &domain.GetApplicationByTokenResponse{
|
||||||
|
ApplicationId: app.Id,
|
||||||
|
ApplicationGroupId: app.ApplicationGroupId,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Application) GetByIdList(ctx context.Context, idList []int) ([]domain.Application, error) {
|
||||||
|
apps, err := s.appRepo.GetApplicationByIdList(ctx, idList)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get application by id list")
|
return nil, errors.WithMessage(err, "get application by id list")
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.EnrichWithTokens(ctx, res)
|
result := make([]domain.Application, len(apps))
|
||||||
}
|
for i, a := range apps {
|
||||||
|
result[i] = s.convertApplication(a)
|
||||||
func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) {
|
|
||||||
arr, err := s.applicationRep.GetApplicationByServiceIdList(ctx, []int{id})
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get application by service_id")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.EnrichWithTokens(ctx, arr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) {
|
|
||||||
domainEntityList, err := s.domainRep.GetDomainBySystemId(ctx, systemId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get domains by system_id")
|
|
||||||
}
|
|
||||||
if len(domainEntityList) == 0 {
|
|
||||||
return []*domain.DomainWithService{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]*domain.DomainWithService, len(domainEntityList))
|
|
||||||
resultByDomainId := make(map[int]*domain.DomainWithService, len(domainEntityList))
|
|
||||||
domainIdList := make([]int, len(domainEntityList))
|
|
||||||
for i, domainEntity := range domainEntityList {
|
|
||||||
domainIdList[i] = domainEntity.Id
|
|
||||||
description := ""
|
|
||||||
if domainEntity.Description != nil {
|
|
||||||
description = *domainEntity.Description
|
|
||||||
}
|
|
||||||
r := &domain.DomainWithService{
|
|
||||||
Id: domainEntity.Id,
|
|
||||||
Name: domainEntity.Name,
|
|
||||||
Description: description,
|
|
||||||
Services: make([]*domain.ServiceWithApps, 0),
|
|
||||||
}
|
|
||||||
resultByDomainId[domainEntity.Id] = r
|
|
||||||
result[i] = r
|
|
||||||
}
|
|
||||||
|
|
||||||
serviceEntityList, err := s.serviceRep.GetServiceByDomainId(ctx, domainIdList)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get service by domain_id")
|
|
||||||
}
|
|
||||||
|
|
||||||
serviceIdList := make([]int, len(serviceEntityList))
|
|
||||||
resultServiceByServiceId := make(map[int]*domain.ServiceWithApps, len(serviceEntityList))
|
|
||||||
for i, serviceEntity := range serviceEntityList {
|
|
||||||
serviceIdList[i] = serviceEntity.Id
|
|
||||||
description := ""
|
|
||||||
if serviceEntity.Description != nil {
|
|
||||||
description = *serviceEntity.Description
|
|
||||||
}
|
|
||||||
resultService := &domain.ServiceWithApps{
|
|
||||||
Id: serviceEntity.Id,
|
|
||||||
Name: serviceEntity.Name,
|
|
||||||
Description: description,
|
|
||||||
Apps: make([]*domain.ApplicationSimple, 0),
|
|
||||||
}
|
|
||||||
r := resultByDomainId[serviceEntity.DomainId]
|
|
||||||
r.Services = append(r.Services, resultService)
|
|
||||||
resultServiceByServiceId[serviceEntity.Id] = resultService
|
|
||||||
}
|
|
||||||
|
|
||||||
applicationEntityList, err := s.applicationRep.GetApplicationByServiceIdList(ctx, serviceIdList)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "get application by service_id")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, applicationEntity := range applicationEntityList {
|
|
||||||
resultService := resultServiceByServiceId[applicationEntity.ServiceId]
|
|
||||||
description := ""
|
|
||||||
if applicationEntity.Description != nil {
|
|
||||||
description = *applicationEntity.Description
|
|
||||||
}
|
|
||||||
resultService.Apps = append(resultService.Apps, &domain.ApplicationSimple{
|
|
||||||
Id: applicationEntity.Id,
|
|
||||||
Name: applicationEntity.Name,
|
|
||||||
Type: applicationEntity.Type,
|
|
||||||
Description: description,
|
|
||||||
Tokens: make([]domain.Token, 0),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
|
func (s Application) GetByAppGroup(ctx context.Context, appGroupId int) ([]domain.Application, error) {
|
||||||
existed, err := s.applicationRep.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId)
|
apps, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, []int{appGroupId})
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
|
||||||
case err != nil:
|
|
||||||
return nil, errors.WithMessage(err, "get application by name and service_id")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.serviceRep.GetServiceById(ctx, req.ServiceId)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get service by id")
|
return nil, errors.WithMessage(err, "get apps by app group ids")
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.Id == 0 {
|
result := make([]domain.Application, len(apps))
|
||||||
if existed != nil {
|
for i, a := range apps {
|
||||||
return nil, domain.ErrApplicationDuplicateName
|
result[i] = s.convertApplication(a)
|
||||||
}
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
_, err = s.applicationRep.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId)
|
func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, error) {
|
||||||
|
if req.Id != 0 {
|
||||||
|
app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get application by name and service_id")
|
return nil, errors.WithMessage(err, "update application")
|
||||||
}
|
}
|
||||||
|
|
||||||
app, err := s.applicationRep.CreateApplication(ctx, req.Name, req.Description, req.ServiceId, req.Type)
|
return new(s.convertApplication(*app)), nil
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "create application")
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := s.EnrichWithTokens(ctx, []entity.Application{*app})
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "enrich application with tokens")
|
|
||||||
}
|
|
||||||
|
|
||||||
return result[0], nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if existed != nil && existed.Id != req.Id {
|
appId, err := s.appRepo.NextApplicationId(ctx)
|
||||||
return nil, domain.ErrApplicationDuplicateName
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.applicationRep.GetApplicationById(ctx, req.Id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get application by id")
|
return nil, errors.WithMessage(err, "next app id")
|
||||||
}
|
}
|
||||||
|
|
||||||
app, err := s.applicationRep.UpdateApplication(ctx, req.Id, req.Name, req.Description)
|
app, err := s.appRepo.CreateApplication(ctx, appId, req.Name, req.Description, req.ApplicationGroupId, req.Type)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "update application")
|
return nil, errors.WithMessage(err, "create application")
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := s.EnrichWithTokens(ctx, []entity.Application{*app})
|
return new(s.convertApplication(*app)), nil
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "enrich application with tokens")
|
|
||||||
}
|
|
||||||
|
|
||||||
return result[0], nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Application) Delete(ctx context.Context, idList []int) (int, error) {
|
func (s Application) Delete(ctx context.Context, idList []int) (int, error) {
|
||||||
count := 0
|
count := 0
|
||||||
err := s.tx.ApplicationDeleteTx(ctx, func(ctx context.Context, tx IApplicationDeleteTx) error {
|
err := s.txRunner.ApplicationDeleteTx(ctx, func(ctx context.Context, tx ApplicationDeleteTx) error {
|
||||||
deletedApp, err := tx.DeleteApplicationByIdList(ctx, idList)
|
deletedApp, err := tx.DeleteApplicationByIdList(ctx, idList)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "delete application by id list")
|
return errors.WithMessage(err, "delete application by id list")
|
||||||
@@ -263,7 +151,7 @@ func (s Application) EnrichWithTokens(ctx context.Context, apps []entity.Applica
|
|||||||
result[i] = awt
|
result[i] = awt
|
||||||
}
|
}
|
||||||
|
|
||||||
tokens, err := s.tokenRep.GetTokenByAppIdList(ctx, appIdList)
|
tokens, err := s.tokenRepo.GetTokenByAppIdList(ctx, appIdList)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get token by app_id list")
|
return nil, errors.WithMessage(err, "get token by app_id list")
|
||||||
}
|
}
|
||||||
@@ -276,19 +164,53 @@ func (s Application) EnrichWithTokens(ctx context.Context, apps []entity.Applica
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Application) convertApplication(req entity.Application) domain.Application {
|
func (s Application) NextId(ctx context.Context) (int, error) {
|
||||||
desc := ""
|
nextId, err := s.appRepo.NextApplicationId(ctx)
|
||||||
if req.Description != nil {
|
if err != nil {
|
||||||
desc = *req.Description
|
return 0, errors.WithMessage(err, "get next application id")
|
||||||
|
}
|
||||||
|
return nextId, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Application) GetAll(ctx context.Context) ([]domain.Application, error) {
|
||||||
|
apps, err := s.appRepo.GetAllApplications(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "get applications list")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
result := make([]domain.Application, 0, len(apps))
|
||||||
|
for _, app := range apps {
|
||||||
|
result = append(result, s.convertApplication(app))
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.Application, error) {
|
||||||
|
app, err := s.appRepo.CreateApplication(ctx, req.Id, req.Name, req.Description, req.ApplicationGroupId, req.Type)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "create application")
|
||||||
|
}
|
||||||
|
|
||||||
|
return new(s.convertApplication(*app)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error) {
|
||||||
|
app, err := s.appRepo.UpdateApplicationWithNewId(ctx, req.OldId, req.NewId, req.Name, req.Description)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "update application")
|
||||||
|
}
|
||||||
|
|
||||||
|
return new(s.convertApplication(*app)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Application) convertApplication(req entity.Application) domain.Application {
|
||||||
return domain.Application{
|
return domain.Application{
|
||||||
Id: req.Id,
|
Id: req.Id,
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
Description: desc,
|
Description: req.Description.String,
|
||||||
ServiceId: req.ServiceId,
|
ApplicationGroupId: req.ApplicationGroupId,
|
||||||
Type: req.Type,
|
Type: req.Type,
|
||||||
CreatedAt: req.CreatedAt,
|
CreatedAt: req.CreatedAt,
|
||||||
UpdatedAt: req.UpdatedAt,
|
UpdatedAt: req.UpdatedAt,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package baseline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"isp-system-service/conf"
|
||||||
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
const adminAppId = 1
|
||||||
|
|
||||||
|
type Transaction interface {
|
||||||
|
CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error)
|
||||||
|
CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error)
|
||||||
|
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
|
||||||
|
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
|
||||||
|
GetTokenById(ctx context.Context, token string) (*entity.Token, error)
|
||||||
|
TryLock(ctx context.Context, key string) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type TxRunner interface {
|
||||||
|
BaselineTx(ctx context.Context, tx func(ctx context.Context, tx Transaction) error) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
cfg conf.Baseline
|
||||||
|
txRunner TxRunner
|
||||||
|
logger log.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(cfg conf.Baseline, txRunner TxRunner, logger log.Logger) Service {
|
||||||
|
return Service{
|
||||||
|
cfg: cfg,
|
||||||
|
txRunner: txRunner,
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Service) Do(ctx context.Context) error {
|
||||||
|
ctx = log.ToContext(ctx, log.String("worker", "baseline"))
|
||||||
|
if s.cfg.InitialAdminUiToken == "" {
|
||||||
|
s.logger.Info(ctx, "initial admin ui token is empty, skip baseline")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.txRunner.BaselineTx(ctx, s.transaction)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "run baseline transaction")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Service) transaction(ctx context.Context, tx Transaction) error {
|
||||||
|
locked, err := tx.TryLock(ctx, "isp-system-service.baseline")
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "try lock isp-system-service.baseline")
|
||||||
|
}
|
||||||
|
if !locked {
|
||||||
|
s.logger.Info(ctx, "baseline is locked, skip baseline")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := tx.GetTokenById(ctx, s.cfg.InitialAdminUiToken)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "get token by id")
|
||||||
|
}
|
||||||
|
if token != nil {
|
||||||
|
s.logger.Info(ctx, "initial admin ui token is exist, skip baseline")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
s.logger.Info(ctx, "initial admin ui token is empty, run baseline")
|
||||||
|
|
||||||
|
service, err := tx.CreateAppGroup(ctx, "rootService", "")
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "create service")
|
||||||
|
}
|
||||||
|
|
||||||
|
app, err := tx.CreateApplication(ctx, adminAppId, "admin", "", service.Id, "SYSTEM")
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "create application")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = tx.SaveToken(ctx, s.cfg.InitialAdminUiToken, app.Id, -1)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "save token")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = tx.UpsertAccessList(ctx, entity.AccessList{
|
||||||
|
AppId: app.Id,
|
||||||
|
Method: "admin/auth/login",
|
||||||
|
Value: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "upsert access list")
|
||||||
|
}
|
||||||
|
|
||||||
|
s.logger.Info(ctx, "baseline done")
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -1,119 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
|
||||||
"isp-system-service/entity"
|
|
||||||
)
|
|
||||||
|
|
||||||
type IDomainDomainRep interface {
|
|
||||||
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
|
|
||||||
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
|
|
||||||
GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error)
|
|
||||||
CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error)
|
|
||||||
UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error)
|
|
||||||
DeleteDomain(ctx context.Context, idList []int) (int, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Domain struct {
|
|
||||||
domainRep IDomainDomainRep
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDomain(
|
|
||||||
domainRep IDomainDomainRep,
|
|
||||||
) Domain {
|
|
||||||
return Domain{
|
|
||||||
domainRep: domainRep,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) {
|
|
||||||
domainEntity, err := s.domainRep.GetDomainById(ctx, id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get domain by id")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := s.convertDomain(*domainEntity)
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Domain) GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error) {
|
|
||||||
domainEntity, err := s.domainRep.GetDomainBySystemId(ctx, systemId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get domain by system_id")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]domain.Domain, len(domainEntity))
|
|
||||||
for i := range domainEntity {
|
|
||||||
result[i] = s.convertDomain(domainEntity[i])
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error) {
|
|
||||||
existed, err := s.domainRep.GetDomainByNameAndSystemId(ctx, req.Name, systemId)
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrDomainNotFound):
|
|
||||||
case err != nil:
|
|
||||||
return nil, errors.WithMessage(err, "get domain by name and system_id")
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Id == 0 {
|
|
||||||
if existed != nil {
|
|
||||||
return nil, domain.ErrDomainDuplicateName
|
|
||||||
}
|
|
||||||
|
|
||||||
domainEntity, err := s.domainRep.CreateDomain(ctx, req.Name, req.Description, systemId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "create domain")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := s.convertDomain(*domainEntity)
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if existed != nil && existed.Id != req.Id {
|
|
||||||
return nil, domain.ErrDomainDuplicateName
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.domainRep.GetDomainById(ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get domain by id")
|
|
||||||
}
|
|
||||||
|
|
||||||
domainEntity, err := s.domainRep.UpdateDomain(ctx, req.Id, req.Name, req.Description)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "update domain")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := s.convertDomain(*domainEntity)
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Domain) Delete(ctx context.Context, idList []int) (int, error) {
|
|
||||||
result, err := s.domainRep.DeleteDomain(ctx, idList)
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessage(err, "delete domain")
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Domain) convertDomain(req entity.Domain) domain.Domain {
|
|
||||||
desc := ""
|
|
||||||
if req.Description != nil {
|
|
||||||
desc = *req.Description
|
|
||||||
}
|
|
||||||
result := domain.Domain{
|
|
||||||
Id: req.Id,
|
|
||||||
Name: req.Name,
|
|
||||||
Description: desc,
|
|
||||||
SystemId: req.SystemId,
|
|
||||||
CreatedAt: req.CreatedAt,
|
|
||||||
UpdatedAt: req.UpdatedAt,
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"isp-system-service/entity"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TokenRepo interface {
|
||||||
|
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
|
||||||
|
GetTokenById(ctx context.Context, token string) (*entity.Token, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ApplicationRepo interface {
|
||||||
|
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
|
||||||
|
GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error)
|
||||||
|
GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error)
|
||||||
|
CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error)
|
||||||
|
UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error)
|
||||||
|
UpdateApplicationWithNewId(ctx context.Context, oldId int, newId int, name string, description string) (*entity.Application, error)
|
||||||
|
NextApplicationId(ctx context.Context) (int, error)
|
||||||
|
GetAllApplications(ctx context.Context) ([]entity.Application, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type AppGroupRepo interface {
|
||||||
|
GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error)
|
||||||
|
GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error)
|
||||||
|
GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error)
|
||||||
|
GetAppGroupByName(ctx context.Context, name string) (*entity.AppGroup, error)
|
||||||
|
CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error)
|
||||||
|
UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error)
|
||||||
|
DeleteAppGroup(ctx context.Context, idList []int) (int, error)
|
||||||
|
}
|
||||||
@@ -4,9 +4,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type TokenRep interface {
|
type TokenRep interface {
|
||||||
@@ -14,7 +15,7 @@ type TokenRep interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AccessListRep interface {
|
type AccessListRep interface {
|
||||||
GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error)
|
GetAccessListByAppIdAndMethod(ctx context.Context, appId int, httpMethod string, method string) (*entity.AccessList, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
@@ -44,15 +45,18 @@ func (s Service) Authenticate(ctx context.Context, token string) (*domain.AuthDa
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &domain.AuthData{
|
return &domain.AuthData{
|
||||||
SystemId: authData.SystemId,
|
AppName: authData.AppName,
|
||||||
DomainId: authData.DomainId,
|
|
||||||
ServiceId: authData.ServiceId,
|
|
||||||
ApplicationId: authData.AppId,
|
ApplicationId: authData.AppId,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Service) Authorize(ctx context.Context, appId int, endpoint string) (bool, error) {
|
func (s Service) Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error) {
|
||||||
accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod(ctx, appId, endpoint)
|
accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod(
|
||||||
|
ctx,
|
||||||
|
req.ApplicationId,
|
||||||
|
req.HttpMethod,
|
||||||
|
req.Endpoint,
|
||||||
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, errors.WithMessage(err, "get access list by app_id and method")
|
return false, errors.WithMessage(err, "get access list by app_id and method")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,145 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
|
||||||
"isp-system-service/entity"
|
|
||||||
)
|
|
||||||
|
|
||||||
type IServiceServiceRep interface {
|
|
||||||
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
|
|
||||||
GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error)
|
|
||||||
GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error)
|
|
||||||
GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error)
|
|
||||||
CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error)
|
|
||||||
UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error)
|
|
||||||
DeleteService(ctx context.Context, idList []int) (int, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type IServiceDomainRep interface {
|
|
||||||
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Service struct {
|
|
||||||
domainRep IServiceDomainRep
|
|
||||||
serviceRep IServiceServiceRep
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewService(
|
|
||||||
domainRep IServiceDomainRep,
|
|
||||||
serviceRep IServiceServiceRep,
|
|
||||||
) Service {
|
|
||||||
return Service{
|
|
||||||
domainRep: domainRep,
|
|
||||||
serviceRep: serviceRep,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) {
|
|
||||||
serviceEntity, err := s.serviceRep.GetServiceById(ctx, id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "get service by id")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := s.convertService(*serviceEntity)
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error) {
|
|
||||||
serviceEntity, err := s.serviceRep.GetServiceByIdList(ctx, idList)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get system by id list")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]domain.Service, len(serviceEntity))
|
|
||||||
for i := range serviceEntity {
|
|
||||||
result[i] = s.convertService(serviceEntity[i])
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error) {
|
|
||||||
serviceEntity, err := s.serviceRep.GetServiceByDomainId(ctx, []int{domainId})
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get system by id list")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]domain.Service, len(serviceEntity))
|
|
||||||
for i := range serviceEntity {
|
|
||||||
result[i] = s.convertService(serviceEntity[i])
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
|
|
||||||
existed, err := s.serviceRep.GetServiceByNameAndDomainId(ctx, req.Name, req.DomainId)
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrServiceNotFound):
|
|
||||||
case err != nil:
|
|
||||||
return nil, errors.WithMessage(err, "get service by name and domain_id")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.domainRep.GetDomainById(ctx, req.DomainId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get domain by id")
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Id == 0 {
|
|
||||||
if existed != nil {
|
|
||||||
return nil, domain.ErrDomainDuplicateName
|
|
||||||
}
|
|
||||||
|
|
||||||
serviceEntity, err := s.serviceRep.CreateService(ctx, req.Name, req.Description, req.DomainId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "create service")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := s.convertService(*serviceEntity)
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if existed != nil && existed.Id != req.Id {
|
|
||||||
return nil, domain.ErrDomainDuplicateName
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.serviceRep.GetServiceById(ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "get service by id")
|
|
||||||
}
|
|
||||||
|
|
||||||
serviceEntity, err := s.serviceRep.UpdateService(ctx, req.Id, req.Name, req.Description)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "update service")
|
|
||||||
}
|
|
||||||
|
|
||||||
result := s.convertService(*serviceEntity)
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Service) Delete(ctx context.Context, idList []int) (int, error) {
|
|
||||||
result, err := s.serviceRep.DeleteService(ctx, idList)
|
|
||||||
if err != nil {
|
|
||||||
return 0, errors.WithMessage(err, "delete service")
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Service) convertService(req entity.Service) domain.Service {
|
|
||||||
desc := ""
|
|
||||||
if req.Description != nil {
|
|
||||||
desc = *req.Description
|
|
||||||
}
|
|
||||||
result := domain.Service{
|
|
||||||
Id: req.Id,
|
|
||||||
Name: req.Name,
|
|
||||||
Description: desc,
|
|
||||||
DomainId: req.DomainId,
|
|
||||||
CreatedAt: req.CreatedAt,
|
|
||||||
UpdatedAt: req.UpdatedAt,
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
+40
-71
@@ -3,80 +3,59 @@ package service
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ITokenSource interface {
|
type ApplicationTokenCreator interface {
|
||||||
CreateApplicationToken() (string, error)
|
CreateApplicationToken() (string, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ITokenAppEnrich interface {
|
type AppEnricher interface {
|
||||||
EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error)
|
EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ITokenApplicationRep interface {
|
type TokenCreateTx interface {
|
||||||
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ITokenServiceRep interface {
|
|
||||||
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ITokenDomainRep interface {
|
|
||||||
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ITokenTokenRep interface {
|
|
||||||
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ITokenCreateTx interface {
|
|
||||||
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
|
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ITokenRevokeTx interface {
|
type TokenRevokeTx interface {
|
||||||
DeleteToken(ctx context.Context, tokens []string) (int, error)
|
DeleteToken(ctx context.Context, tokens []string) (int, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ITokenTxRunner interface {
|
type TokenTxRunner interface {
|
||||||
TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx ITokenCreateTx) error) error
|
TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx TokenCreateTx) error) error
|
||||||
TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx ITokenRevokeTx) error) error
|
TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx TokenRevokeTx) error) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type Token struct {
|
type Token struct {
|
||||||
jwt ITokenSource
|
jwt ApplicationTokenCreator
|
||||||
appEnrich ITokenAppEnrich
|
appEnricher AppEnricher
|
||||||
tx ITokenTxRunner
|
tx TokenTxRunner
|
||||||
appRep ITokenApplicationRep
|
appRepo ApplicationRepo
|
||||||
domainRep ITokenDomainRep
|
tokenRepo TokenRepo
|
||||||
serviceRep ITokenServiceRep
|
|
||||||
tokenRep ITokenTokenRep
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewToken(
|
func NewToken(
|
||||||
jwtGenerate ITokenSource,
|
jwtGenerate ApplicationTokenCreator,
|
||||||
appEnrich ITokenAppEnrich,
|
appEnricher AppEnricher,
|
||||||
tx ITokenTxRunner,
|
tx TokenTxRunner,
|
||||||
appRep ITokenApplicationRep,
|
appRepo ApplicationRepo,
|
||||||
domainRep ITokenDomainRep,
|
tokenRepo TokenRepo,
|
||||||
serviceRep ITokenServiceRep,
|
|
||||||
tokenRep ITokenTokenRep,
|
|
||||||
) Token {
|
) Token {
|
||||||
return Token{
|
return Token{
|
||||||
appEnrich: appEnrich,
|
appEnricher: appEnricher,
|
||||||
jwt: jwtGenerate,
|
jwt: jwtGenerate,
|
||||||
tx: tx,
|
tx: tx,
|
||||||
appRep: appRep,
|
appRepo: appRepo,
|
||||||
domainRep: domainRep,
|
tokenRepo: tokenRepo,
|
||||||
serviceRep: serviceRep,
|
|
||||||
tokenRep: tokenRep,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error) {
|
func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error) {
|
||||||
tokenEntity, err := s.tokenRep.GetTokenByAppIdList(ctx, []int{appId})
|
tokenEntity, err := s.tokenRepo.GetTokenByAppIdList(ctx, []int{appId})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get token by app_id list")
|
return nil, errors.WithMessage(err, "get token by app_id list")
|
||||||
}
|
}
|
||||||
@@ -90,30 +69,20 @@ func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
|
func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
|
||||||
applicationEntity, err := s.appRep.GetApplicationById(ctx, req.AppId)
|
applicationEntity, err := s.appRepo.GetApplicationById(ctx, req.AppId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "get application by id")
|
return nil, errors.WithMessage(err, "get application by id")
|
||||||
}
|
|
||||||
|
|
||||||
serviceEntity, err := s.serviceRep.GetServiceById(ctx, applicationEntity.ServiceId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "get service by id")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.domainRep.GetDomainById(ctx, serviceEntity.DomainId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "get domain by id")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
token, err := s.jwt.CreateApplicationToken()
|
token, err := s.jwt.CreateApplicationToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "create application token")
|
return nil, errors.WithMessage(err, "create application token")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx ITokenCreateTx) error {
|
err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx TokenCreateTx) error {
|
||||||
_, err = tx.SaveToken(ctx, token, req.AppId, req.ExpireTimeMs)
|
_, err = tx.SaveToken(ctx, token, req.AppId, req.ExpireTimeMs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessagef(err, "tx save token")
|
return errors.WithMessage(err, "tx save token")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -122,35 +91,35 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma
|
|||||||
return nil, errors.WithMessage(err, "token create transaction")
|
return nil, errors.WithMessage(err, "token create transaction")
|
||||||
}
|
}
|
||||||
|
|
||||||
arr, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*applicationEntity})
|
arr, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*applicationEntity})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "application enrich with tokens")
|
return nil, errors.WithMessage(err, "application enrich with tokens")
|
||||||
}
|
}
|
||||||
|
|
||||||
return arr[0], nil
|
return arr[0], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
|
func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
|
||||||
app, err := s.appRep.GetApplicationById(ctx, req.AppId)
|
app, err := s.appRepo.GetApplicationById(ctx, req.AppId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "get application by id")
|
return nil, errors.WithMessage(err, "get application by id")
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = s.revokeTokens(ctx, req.Tokens)
|
_, err = s.revokeTokens(ctx, req.Tokens)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "reboke tokens")
|
return nil, errors.WithMessage(err, "revoke tokens")
|
||||||
}
|
}
|
||||||
|
|
||||||
res, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*app})
|
res, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*app})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessagef(err, "application enrich")
|
return nil, errors.WithMessage(err, "application enrich")
|
||||||
}
|
}
|
||||||
|
|
||||||
return res[0], nil
|
return res[0], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Token) RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error) {
|
func (s Token) RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error) {
|
||||||
tokens, err := s.tokenRep.GetTokenByAppIdList(ctx, []int{appId})
|
tokens, err := s.tokenRepo.GetTokenByAppIdList(ctx, []int{appId})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get token by app_id list")
|
return nil, errors.WithMessage(err, "get token by app_id list")
|
||||||
}
|
}
|
||||||
@@ -169,10 +138,10 @@ func (s Token) revokeTokens(ctx context.Context, tokens []string) (*domain.Delet
|
|||||||
}
|
}
|
||||||
|
|
||||||
var count int
|
var count int
|
||||||
err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx ITokenRevokeTx) error {
|
err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx TokenRevokeTx) error {
|
||||||
deleted, err := tx.DeleteToken(ctx, tokens)
|
deleted, err := tx.DeleteToken(ctx, tokens)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessagef(err, "tx delete token")
|
return errors.WithMessage(err, "tx delete token")
|
||||||
}
|
}
|
||||||
|
|
||||||
count = deleted
|
count = deleted
|
||||||
|
|||||||
@@ -4,18 +4,17 @@ import (
|
|||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/txix-open/isp-kit/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type TokenSource struct {
|
type TokenSource struct{}
|
||||||
}
|
|
||||||
|
|
||||||
func NewTokenSource() TokenSource {
|
func NewTokenSource() TokenSource {
|
||||||
return TokenSource{}
|
return TokenSource{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s TokenSource) CreateApplicationToken() (string, error) {
|
func (s TokenSource) CreateApplicationToken() (string, error) {
|
||||||
cryptoRand := make([]byte, 128) //nolint:gomnd
|
cryptoRand := make([]byte, 128) //nolint:mnd
|
||||||
_, err := rand.Read(cryptoRand)
|
_, err := rand.Read(cryptoRand)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.WithMessage(err, "crypto/rand read")
|
return "", errors.WithMessage(err, "crypto/rand read")
|
||||||
|
|||||||
@@ -0,0 +1,223 @@
|
|||||||
|
package tests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
|
|
||||||
|
"isp-system-service/assembly"
|
||||||
|
"isp-system-service/conf"
|
||||||
|
"isp-system-service/domain"
|
||||||
|
"isp-system-service/entity"
|
||||||
|
"isp-system-service/repository"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/suite"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
|
"github.com/txix-open/isp-kit/test"
|
||||||
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
|
"github.com/txix-open/isp-kit/test/fake"
|
||||||
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAccessListSuite(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
suite.Run(t, &AccessListSuite{})
|
||||||
|
}
|
||||||
|
|
||||||
|
type AccessListSuite struct {
|
||||||
|
suite.Suite
|
||||||
|
|
||||||
|
test *test.Test
|
||||||
|
testDb *dbt.TestDb
|
||||||
|
api *client.Client
|
||||||
|
accessListRepo repository.AccessList
|
||||||
|
appId int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AccessListSuite) SetupTest() {
|
||||||
|
s.test, _ = test.New(s.T())
|
||||||
|
|
||||||
|
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
|
||||||
|
|
||||||
|
locator := assembly.NewLocator(s.testDb, s.test.Logger())
|
||||||
|
config := locator.Config(conf.Remote{})
|
||||||
|
_, s.api = grpct.TestServer(s.test, config.Handler)
|
||||||
|
s.accessListRepo = repository.NewAccessList(s.testDb)
|
||||||
|
|
||||||
|
appGroup, err := repository.NewAppGroup(s.testDb).CreateAppGroup(
|
||||||
|
s.T().Context(),
|
||||||
|
fake.It[string](),
|
||||||
|
fake.It[string](),
|
||||||
|
)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
s.appId = fake.It[int]()
|
||||||
|
|
||||||
|
_, err = repository.NewApplication(s.testDb).CreateApplication(
|
||||||
|
s.T().Context(),
|
||||||
|
s.appId,
|
||||||
|
fake.It[string](),
|
||||||
|
fake.It[string](),
|
||||||
|
appGroup.Id,
|
||||||
|
domain.ApplicationSystemType,
|
||||||
|
)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AccessListSuite) TestGetById_HappyPath() {
|
||||||
|
expectedAccessList := []entity.AccessList{
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), expectedAccessList)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
req := domain.Identity{
|
||||||
|
Id: s.appId,
|
||||||
|
}
|
||||||
|
var accessList []domain.MethodInfo
|
||||||
|
err = s.api.Invoke("system/access_list/get_by_id").
|
||||||
|
JsonRequestBody(&req).
|
||||||
|
JsonResponseBody(&accessList).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Len(accessList, len(expectedAccessList))
|
||||||
|
|
||||||
|
actualAccessList := s.convertAccessList(accessList)
|
||||||
|
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AccessListSuite) TestSetOne_HappyPath() {
|
||||||
|
expectedAccessList := []entity.AccessList{
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), expectedAccessList)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
req := domain.AccessListSetOneRequest{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: expectedAccessList[0].Method,
|
||||||
|
Value: true,
|
||||||
|
}
|
||||||
|
err = s.api.Invoke("system/access_list/set_one").
|
||||||
|
JsonRequestBody(&req).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
for i := range expectedAccessList {
|
||||||
|
expectedAccessList[i].Value = true
|
||||||
|
}
|
||||||
|
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AccessListSuite) TestSetList_HappyPath() {
|
||||||
|
req := domain.AccessListSetListRequest{
|
||||||
|
AppId: s.appId,
|
||||||
|
Methods: []domain.MethodInfo{
|
||||||
|
{
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.api.Invoke("system/access_list/set_list").
|
||||||
|
JsonRequestBody(&req).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Len(actualAccessList, len(req.Methods))
|
||||||
|
|
||||||
|
expectedAccessList := s.convertAccessList(req.Methods)
|
||||||
|
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AccessListSuite) TestDeleteList_HappyPath() {
|
||||||
|
accessList := []entity.AccessList{
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: fake.It[string](),
|
||||||
|
Value: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), accessList)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
req := domain.AccessListDeleteListRequest{
|
||||||
|
AppId: s.appId,
|
||||||
|
Methods: []string{
|
||||||
|
accessList[0].Method,
|
||||||
|
accessList[1].Method,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
err = s.api.Invoke("system/access_list/delete_list").
|
||||||
|
JsonRequestBody(&req).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Len(actualAccessList, 1)
|
||||||
|
s.Require().Equal(accessList[2], actualAccessList[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AccessListSuite) convertAccessList(methods []domain.MethodInfo) []entity.AccessList {
|
||||||
|
converted := make([]entity.AccessList, 0, len(methods))
|
||||||
|
for _, method := range methods {
|
||||||
|
converted = append(converted, entity.AccessList{
|
||||||
|
AppId: s.appId,
|
||||||
|
Method: method.Method,
|
||||||
|
Value: method.Value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return converted
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
package tests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"isp-system-service/assembly"
|
||||||
|
"isp-system-service/conf"
|
||||||
|
"isp-system-service/domain"
|
||||||
|
"isp-system-service/entity"
|
||||||
|
"isp-system-service/repository"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/suite"
|
||||||
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
|
"github.com/txix-open/isp-kit/test"
|
||||||
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
|
"github.com/txix-open/isp-kit/test/fake"
|
||||||
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestApplicationGroupSuite(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
suite.Run(t, &AppGroupSuite{})
|
||||||
|
}
|
||||||
|
|
||||||
|
type AppGroupSuite struct {
|
||||||
|
suite.Suite
|
||||||
|
|
||||||
|
test *test.Test
|
||||||
|
testDb *dbt.TestDb
|
||||||
|
appGroupRepo repository.AppGroup
|
||||||
|
api *client.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) SetupTest() {
|
||||||
|
s.test, _ = test.New(s.T())
|
||||||
|
|
||||||
|
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
|
||||||
|
|
||||||
|
locator := assembly.NewLocator(s.testDb, s.test.Logger())
|
||||||
|
config := locator.Config(conf.Remote{})
|
||||||
|
_, s.api = grpct.TestServer(s.test, config.Handler)
|
||||||
|
s.appGroupRepo = repository.NewAppGroup(s.testDb)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestGetByIdList() {
|
||||||
|
toGenerate := 10
|
||||||
|
appGroups := make([]domain.AppGroup, 0, toGenerate)
|
||||||
|
ids := make([]int, 0, toGenerate)
|
||||||
|
for range 10 {
|
||||||
|
appGroup := s.createAppGroup()
|
||||||
|
appGroups = append(appGroups, domain.AppGroup{
|
||||||
|
Id: appGroup.Id,
|
||||||
|
Name: appGroup.Name,
|
||||||
|
Description: appGroup.Description.String,
|
||||||
|
CreatedAt: time.Time{},
|
||||||
|
UpdatedAt: time.Time{},
|
||||||
|
})
|
||||||
|
ids = append(ids, appGroup.Id)
|
||||||
|
}
|
||||||
|
result := []domain.AppGroup{}
|
||||||
|
apiReq := domain.IdListRequest{IdList: ids}
|
||||||
|
err := s.api.Invoke("system/application_group/get_by_id_list").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
for i := range result {
|
||||||
|
s.Require().NotEmpty(result[i].CreatedAt)
|
||||||
|
result[i].CreatedAt = time.Time{}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result[i].UpdatedAt)
|
||||||
|
result[i].UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
s.Require().ElementsMatch(appGroups, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestGetByIdList_EmptyDescription() {
|
||||||
|
toGenerate := 10
|
||||||
|
appGroups := make([]domain.AppGroup, 0, toGenerate)
|
||||||
|
ids := make([]int, 0, toGenerate)
|
||||||
|
for range 10 {
|
||||||
|
appGroup, err := s.appGroupRepo.CreateAppGroup(
|
||||||
|
s.T().Context(),
|
||||||
|
fake.It[string](),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
appGroups = append(appGroups, domain.AppGroup{
|
||||||
|
Id: appGroup.Id,
|
||||||
|
Name: appGroup.Name,
|
||||||
|
Description: "",
|
||||||
|
CreatedAt: time.Time{},
|
||||||
|
UpdatedAt: time.Time{},
|
||||||
|
})
|
||||||
|
ids = append(ids, appGroup.Id)
|
||||||
|
}
|
||||||
|
result := []domain.AppGroup{}
|
||||||
|
apiReq := domain.IdListRequest{IdList: ids}
|
||||||
|
err := s.api.Invoke("system/application_group/get_by_id_list").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
for i := range result {
|
||||||
|
s.Require().NotEmpty(result[i].CreatedAt)
|
||||||
|
result[i].CreatedAt = time.Time{}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result[i].UpdatedAt)
|
||||||
|
result[i].UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
s.Require().ElementsMatch(appGroups, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestGetByIdList_NotFoundAppGroups() {
|
||||||
|
appGroup := s.createAppGroup()
|
||||||
|
result := []domain.AppGroup{}
|
||||||
|
|
||||||
|
apiReq := domain.IdListRequest{IdList: []int{appGroup.Id + 1}}
|
||||||
|
err := s.api.Invoke("system/application_group/get_by_id_list").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Empty(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestCreate_HappyPath() {
|
||||||
|
apiReq := domain.CreateAppGroupRequest{
|
||||||
|
Name: fake.It[string](),
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
var result domain.AppGroup
|
||||||
|
err := s.api.Invoke("system/application_group/create").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
s.Require().Equal(apiReq.Name, result.Name)
|
||||||
|
s.Require().Equal(apiReq.Description, result.Description)
|
||||||
|
|
||||||
|
appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), result.Id)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Equal(apiReq.Name, appGroup.Name)
|
||||||
|
s.Require().Equal(apiReq.Description, appGroup.Description.String)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestCreate_AppGroupNameNotUnique() {
|
||||||
|
appGroup := s.createAppGroup()
|
||||||
|
|
||||||
|
apiReq := domain.CreateAppGroupRequest{
|
||||||
|
Name: appGroup.Name,
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
var result domain.AppGroup
|
||||||
|
err := s.api.Invoke("system/application_group/create").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeAppGroupDuplicateName, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestUpdate_HappyPath() {
|
||||||
|
appGroupToUpdate := s.createAppGroup()
|
||||||
|
|
||||||
|
apiReq := domain.UpdateAppGroupRequest{
|
||||||
|
Id: appGroupToUpdate.Id,
|
||||||
|
Name: fake.It[string](),
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
var result domain.AppGroup
|
||||||
|
err := s.api.Invoke("system/application_group/update").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
s.Require().Equal(apiReq.Name, result.Name)
|
||||||
|
s.Require().Equal(apiReq.Description, result.Description)
|
||||||
|
|
||||||
|
appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), apiReq.Id)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Equal(apiReq.Name, appGroup.Name)
|
||||||
|
s.Require().Equal(apiReq.Description, appGroup.Description.String)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestUpdate_AppGroupNameNotUnique() {
|
||||||
|
appGroupToUpdate := s.createAppGroup()
|
||||||
|
appGroup := s.createAppGroup()
|
||||||
|
|
||||||
|
apiReq := domain.UpdateAppGroupRequest{
|
||||||
|
Id: appGroupToUpdate.Id,
|
||||||
|
Name: appGroup.Name,
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
err := s.api.Invoke("system/application_group/update").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeAppGroupDuplicateName, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestUpdate_AppGroupNotFound() {
|
||||||
|
apiReq := domain.UpdateAppGroupRequest{
|
||||||
|
Id: fake.It[int](),
|
||||||
|
Name: fake.It[string](),
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
err := s.api.Invoke("system/application_group/update").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeAppGroupNotFound, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestDeleteList() {
|
||||||
|
appGroupToDelete := s.createAppGroup()
|
||||||
|
appGroup := s.createAppGroup()
|
||||||
|
|
||||||
|
var result domain.DeleteResponse
|
||||||
|
apiReq := domain.IdListRequest{IdList: []int{appGroupToDelete.Id}}
|
||||||
|
err := s.api.Invoke("system/application_group/delete_list").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Equal(1, result.Deleted)
|
||||||
|
|
||||||
|
_, err = s.appGroupRepo.GetAppGroupById(s.T().Context(), appGroup.Id)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) TestGetAll() {
|
||||||
|
toGenerate := 10
|
||||||
|
appGroups := make([]domain.AppGroup, 0, toGenerate)
|
||||||
|
for range 10 {
|
||||||
|
appGroup := s.createAppGroup()
|
||||||
|
appGroups = append(appGroups, domain.AppGroup{
|
||||||
|
Id: appGroup.Id,
|
||||||
|
Name: appGroup.Name,
|
||||||
|
Description: appGroup.Description.String,
|
||||||
|
CreatedAt: time.Time{},
|
||||||
|
UpdatedAt: time.Time{},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
result := []domain.AppGroup{}
|
||||||
|
err := s.api.Invoke("system/application_group/get_all").
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
for i := range result {
|
||||||
|
s.Require().NotEmpty(result[i].CreatedAt)
|
||||||
|
result[i].CreatedAt = time.Time{}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result[i].UpdatedAt)
|
||||||
|
result[i].UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
s.Require().ElementsMatch(appGroups, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AppGroupSuite) createAppGroup() *entity.AppGroup {
|
||||||
|
appGroup, err := s.appGroupRepo.CreateAppGroup(
|
||||||
|
s.T().Context(),
|
||||||
|
fake.It[string](),
|
||||||
|
fake.It[string](),
|
||||||
|
)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
return appGroup
|
||||||
|
}
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
package tests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"isp-system-service/assembly"
|
||||||
|
"isp-system-service/conf"
|
||||||
|
"isp-system-service/domain"
|
||||||
|
"isp-system-service/entity"
|
||||||
|
"isp-system-service/repository"
|
||||||
|
"math"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/suite"
|
||||||
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
|
"github.com/txix-open/isp-kit/test"
|
||||||
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
|
"github.com/txix-open/isp-kit/test/fake"
|
||||||
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestApplicationSuite(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
suite.Run(t, &ApplicationSuite{})
|
||||||
|
}
|
||||||
|
|
||||||
|
type ApplicationSuite struct {
|
||||||
|
suite.Suite
|
||||||
|
|
||||||
|
test *test.Test
|
||||||
|
testDb *dbt.TestDb
|
||||||
|
appRepo repository.Application
|
||||||
|
appGroupRepo repository.AppGroup
|
||||||
|
tokenRepo repository.Token
|
||||||
|
api *client.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) SetupTest() {
|
||||||
|
s.test, _ = test.New(s.T())
|
||||||
|
|
||||||
|
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
|
||||||
|
|
||||||
|
locator := assembly.NewLocator(s.testDb, s.test.Logger())
|
||||||
|
config := locator.Config(conf.Remote{})
|
||||||
|
_, s.api = grpct.TestServer(s.test, config.Handler)
|
||||||
|
s.appRepo = repository.NewApplication(s.testDb)
|
||||||
|
s.appGroupRepo = repository.NewAppGroup(s.testDb)
|
||||||
|
s.tokenRepo = repository.NewToken(s.testDb)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestGetAllApplications() {
|
||||||
|
expectedApps := s.insertApps(2)
|
||||||
|
|
||||||
|
result := []domain.Application{}
|
||||||
|
err := s.api.Invoke("system/application/get_all").
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
for i := range result {
|
||||||
|
s.Require().NotEmpty(result[i].CreatedAt)
|
||||||
|
result[i].CreatedAt = time.Time{}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result[i].UpdatedAt)
|
||||||
|
result[i].UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
s.Require().ElementsMatch(expectedApps, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) Test_GetByAppId() {
|
||||||
|
expectedApps := s.insertApps(2)
|
||||||
|
|
||||||
|
result := []domain.Application{}
|
||||||
|
err := s.api.Invoke("system/application/get_by_app_group").
|
||||||
|
JsonRequestBody(domain.Identity{
|
||||||
|
Id: expectedApps[0].ApplicationGroupId,
|
||||||
|
}).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
for i := range result {
|
||||||
|
s.Require().NotEmpty(result[i].CreatedAt)
|
||||||
|
result[i].CreatedAt = time.Time{}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result[i].UpdatedAt)
|
||||||
|
result[i].UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
s.Require().ElementsMatch(expectedApps, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) Test_GetByAppId_NotFoundAny() {
|
||||||
|
_ = s.insertApps(2)
|
||||||
|
|
||||||
|
result := []domain.Application{}
|
||||||
|
err := s.api.Invoke("system/application/get_by_app_group").
|
||||||
|
JsonRequestBody(domain.Identity{
|
||||||
|
Id: math.MaxInt32,
|
||||||
|
}).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Empty(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestCreate_HappyPath() {
|
||||||
|
result := domain.Application{}
|
||||||
|
appGroup := s.createAppGroup()
|
||||||
|
|
||||||
|
apiReq := domain.CreateApplicationRequest{
|
||||||
|
Id: 1,
|
||||||
|
Name: fake.It[string](),
|
||||||
|
Type: domain.ApplicationSystemType,
|
||||||
|
ApplicationGroupId: appGroup.Id,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.api.Invoke("system/application/create_application").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result.CreatedAt)
|
||||||
|
result.CreatedAt = time.Time{}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result.UpdatedAt)
|
||||||
|
result.UpdatedAt = time.Time{}
|
||||||
|
|
||||||
|
expectedApp := domain.Application{
|
||||||
|
Id: apiReq.Id,
|
||||||
|
Name: apiReq.Name,
|
||||||
|
Description: apiReq.Description,
|
||||||
|
Type: apiReq.Type,
|
||||||
|
ApplicationGroupId: apiReq.ApplicationGroupId,
|
||||||
|
}
|
||||||
|
s.Require().Equal(expectedApp, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestCreate_AppGroupNotFound() {
|
||||||
|
apiReq := domain.CreateApplicationRequest{
|
||||||
|
Id: 1,
|
||||||
|
Name: fake.It[string](),
|
||||||
|
Type: domain.ApplicationSystemType,
|
||||||
|
ApplicationGroupId: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.api.Invoke("system/application/create_application").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeAppGroupNotFound, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestCreate_ApplicationNameNotUniqueInAppGroup() {
|
||||||
|
inserted := s.insertApps(1)
|
||||||
|
|
||||||
|
apiReq := domain.CreateApplicationRequest{
|
||||||
|
Id: inserted[0].Id + 1,
|
||||||
|
Name: inserted[0].Name,
|
||||||
|
Type: domain.ApplicationSystemType,
|
||||||
|
ApplicationGroupId: inserted[0].ApplicationGroupId,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.api.Invoke("system/application/create_application").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeApplicationDuplicateName, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() {
|
||||||
|
inserted := s.insertApps(1)
|
||||||
|
|
||||||
|
apiReq := domain.CreateApplicationRequest{
|
||||||
|
Id: inserted[0].Id,
|
||||||
|
Name: inserted[0].Name,
|
||||||
|
Type: domain.ApplicationSystemType,
|
||||||
|
ApplicationGroupId: inserted[0].ApplicationGroupId,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.api.Invoke("system/application/create_application").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeApplicationDuplicateId, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestUpdate_HappyPath() {
|
||||||
|
inserted := s.insertApps(2)
|
||||||
|
apiReq := domain.UpdateApplicationRequest{
|
||||||
|
OldId: inserted[0].Id,
|
||||||
|
NewId: inserted[0].Id + inserted[1].Id,
|
||||||
|
Name: fake.It[string](),
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
|
||||||
|
var result domain.Application
|
||||||
|
err := s.api.Invoke("system/application/update_application").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result.CreatedAt)
|
||||||
|
result.CreatedAt = time.Time{}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(result.UpdatedAt)
|
||||||
|
result.UpdatedAt = time.Time{}
|
||||||
|
|
||||||
|
expectedApp := domain.Application{
|
||||||
|
Id: apiReq.NewId,
|
||||||
|
Name: apiReq.Name,
|
||||||
|
Description: apiReq.Description,
|
||||||
|
Type: inserted[0].Type,
|
||||||
|
ApplicationGroupId: inserted[0].ApplicationGroupId,
|
||||||
|
}
|
||||||
|
s.Require().Equal(expectedApp, result)
|
||||||
|
|
||||||
|
app, err := s.appRepo.GetApplicationById(s.T().Context(), apiReq.NewId)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
expectedDbApp := entity.Application{
|
||||||
|
Id: apiReq.NewId,
|
||||||
|
Name: apiReq.Name,
|
||||||
|
Description: app.Description,
|
||||||
|
Type: inserted[0].Type,
|
||||||
|
ApplicationGroupId: inserted[0].ApplicationGroupId,
|
||||||
|
}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(app.CreatedAt)
|
||||||
|
app.CreatedAt = time.Time{}
|
||||||
|
|
||||||
|
s.Require().NotEmpty(app.UpdatedAt)
|
||||||
|
app.UpdatedAt = time.Time{}
|
||||||
|
s.Require().Equal(expectedDbApp, *app)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestUpdate_ApplicationNameNotUniqueInAppGroup() {
|
||||||
|
inserted := s.insertApps(2)
|
||||||
|
apiReq := domain.UpdateApplicationRequest{
|
||||||
|
NewId: inserted[0].Id,
|
||||||
|
OldId: inserted[0].Id,
|
||||||
|
Name: inserted[1].Name,
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.api.Invoke("system/application/update_application").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeApplicationDuplicateName, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestUpdate_AppIdNotUnique() {
|
||||||
|
inserted := s.insertApps(2)
|
||||||
|
apiReq := domain.UpdateApplicationRequest{
|
||||||
|
OldId: inserted[0].Id,
|
||||||
|
NewId: inserted[1].Id,
|
||||||
|
Name: fake.It[string](),
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.api.Invoke("system/application/update_application").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeApplicationDuplicateId, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestUpdate_AppNotFound() {
|
||||||
|
apiReq := domain.UpdateApplicationRequest{
|
||||||
|
OldId: fake.It[int](),
|
||||||
|
NewId: fake.It[int](),
|
||||||
|
Name: fake.It[string](),
|
||||||
|
Description: fake.It[string](),
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.api.Invoke("system/application/update_application").
|
||||||
|
JsonRequestBody(apiReq).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeApplicationNotFound, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestGetByToken() {
|
||||||
|
insertedApps := s.insertApps(2)
|
||||||
|
|
||||||
|
token := fake.It[string]()
|
||||||
|
expectedApp := domain.GetApplicationByTokenResponse{
|
||||||
|
ApplicationId: insertedApps[0].Id,
|
||||||
|
ApplicationGroupId: insertedApps[0].ApplicationGroupId,
|
||||||
|
}
|
||||||
|
_, err := s.tokenRepo.SaveToken(s.T().Context(), token, expectedApp.ApplicationId, fake.It[int]())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
result := domain.GetApplicationByTokenResponse{}
|
||||||
|
err = s.api.Invoke("system/application/get_application_by_token").
|
||||||
|
JsonRequestBody(domain.GetApplicationByTokenRequest{Token: token}).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Equal(expectedApp, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) TestGetByToken_NotFound() {
|
||||||
|
s.insertApps(2)
|
||||||
|
|
||||||
|
result := domain.GetApplicationByTokenResponse{}
|
||||||
|
err := s.api.Invoke("system/application/get_application_by_token").
|
||||||
|
JsonRequestBody(domain.GetApplicationByTokenRequest{Token: fake.It[string]()}).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
apiError := apierrors.FromError(err)
|
||||||
|
s.Require().NotNil(apiError)
|
||||||
|
s.Require().Equal(domain.ErrCodeApplicationNotFound, apiError.ErrorCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) createAppGroup() *entity.AppGroup {
|
||||||
|
appGroup, err := s.appGroupRepo.CreateAppGroup(
|
||||||
|
s.T().Context(),
|
||||||
|
fake.It[string](),
|
||||||
|
fake.It[string](),
|
||||||
|
)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
return appGroup
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApplicationSuite) insertApps(appsCount uint) []domain.Application {
|
||||||
|
toInsert := fake.It[[]domain.Application](fake.MinSliceSize(appsCount), fake.MaxSliceSize(appsCount))
|
||||||
|
|
||||||
|
appGroup := s.createAppGroup()
|
||||||
|
toExpect := make([]domain.Application, 0, len(toInsert))
|
||||||
|
for _, app := range toInsert {
|
||||||
|
appId, err := s.appRepo.NextApplicationId(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
createdApp, err := s.appRepo.CreateApplication(
|
||||||
|
s.T().Context(),
|
||||||
|
appId,
|
||||||
|
app.Name,
|
||||||
|
app.Description,
|
||||||
|
appGroup.Id,
|
||||||
|
app.Type,
|
||||||
|
)
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().NotEmpty(createdApp.CreatedAt)
|
||||||
|
s.Require().NotEmpty(createdApp.UpdatedAt)
|
||||||
|
|
||||||
|
toExpect = append(toExpect, domain.Application{
|
||||||
|
Id: createdApp.Id,
|
||||||
|
Name: createdApp.Name,
|
||||||
|
Description: createdApp.Description.String,
|
||||||
|
ApplicationGroupId: createdApp.ApplicationGroupId,
|
||||||
|
Type: createdApp.Type,
|
||||||
|
CreatedAt: time.Time{},
|
||||||
|
UpdatedAt: time.Time{},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return toExpect
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package tests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/stretchr/testify/suite"
|
||||||
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
|
"github.com/txix-open/isp-kit/test"
|
||||||
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
|
"github.com/txix-open/isp-kit/test/fake"
|
||||||
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
|
"isp-system-service/assembly"
|
||||||
|
"isp-system-service/conf"
|
||||||
|
"isp-system-service/service/baseline"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBaselineSuite(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
suite.Run(t, &BaselineSuite{})
|
||||||
|
}
|
||||||
|
|
||||||
|
type BaselineSuite struct {
|
||||||
|
suite.Suite
|
||||||
|
|
||||||
|
test *test.Test
|
||||||
|
testDb *dbt.TestDb
|
||||||
|
baseline baseline.Service
|
||||||
|
api *client.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BaselineSuite) SetupSuite() {
|
||||||
|
s.test, _ = test.New(s.T())
|
||||||
|
|
||||||
|
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
|
||||||
|
|
||||||
|
locator := assembly.NewLocator(s.testDb, s.test.Logger())
|
||||||
|
config := locator.Config(conf.Remote{
|
||||||
|
Baseline: conf.Baseline{
|
||||||
|
InitialAdminUiToken: fake.It[string](),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
s.baseline = config.Baseline
|
||||||
|
_, s.api = grpct.TestServer(s.test, config.Handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BaselineSuite) TestBaselineSuccess() {
|
||||||
|
err := s.baseline.Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
|
||||||
|
err = s.baseline.Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
}
|
||||||
@@ -1,26 +1,17 @@
|
|||||||
package tests
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/integration-system/isp-kit/test/dbt"
|
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func InsertDomain(db *dbt.TestDb, value entity.Domain) {
|
func InsertAppGroup(db *dbt.TestDb, value entity.AppGroup) {
|
||||||
q := `
|
q := `
|
||||||
INSERT INTO domain
|
INSERT INTO application_group
|
||||||
(id, name, description, system_id, created_at, updated_at)
|
(id, name, description, created_at, updated_at)
|
||||||
VALUES
|
VALUES
|
||||||
(:id, :name, :description, 1, :created_at, :updated_at)
|
(:id, :name, :description, :created_at, :updated_at)
|
||||||
`
|
|
||||||
db.Must().ExecNamed(q, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func InsertService(db *dbt.TestDb, value entity.Service) {
|
|
||||||
q := `
|
|
||||||
INSERT INTO service
|
|
||||||
(id, name, description, domain_id, created_at, updated_at)
|
|
||||||
VALUES
|
|
||||||
(:id, :name, :description, :domain_id, :created_at, :updated_at)
|
|
||||||
`
|
`
|
||||||
db.Must().ExecNamed(q, value)
|
db.Must().ExecNamed(q, value)
|
||||||
}
|
}
|
||||||
@@ -28,9 +19,9 @@ func InsertService(db *dbt.TestDb, value entity.Service) {
|
|||||||
func InsertApplication(db *dbt.TestDb, value entity.Application) {
|
func InsertApplication(db *dbt.TestDb, value entity.Application) {
|
||||||
q := `
|
q := `
|
||||||
INSERT INTO application
|
INSERT INTO application
|
||||||
(id, name, description, service_id, created_at, updated_at)
|
(id, name, description, application_group_id, created_at, updated_at)
|
||||||
VALUES
|
VALUES
|
||||||
(:id, :name, :description, :service_id, :created_at, :updated_at)
|
(:id, :name, :description, :application_group_id, :created_at, :updated_at)
|
||||||
`
|
`
|
||||||
db.Must().ExecNamed(q, value)
|
db.Must().ExecNamed(q, value)
|
||||||
}
|
}
|
||||||
+77
-65
@@ -1,64 +1,56 @@
|
|||||||
package tests
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/integration-system/isp-kit/dbx/migration"
|
"github.com/txix-open/isp-kit/dbx"
|
||||||
"github.com/integration-system/isp-kit/grpc/client"
|
|
||||||
"github.com/integration-system/isp-kit/test"
|
|
||||||
"github.com/integration-system/isp-kit/test/dbt"
|
|
||||||
"github.com/integration-system/isp-kit/test/grpct"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"github.com/stretchr/testify/suite"
|
|
||||||
"isp-system-service/assembly"
|
"isp-system-service/assembly"
|
||||||
"isp-system-service/conf"
|
"isp-system-service/conf"
|
||||||
"isp-system-service/domain"
|
"isp-system-service/domain"
|
||||||
"isp-system-service/entity"
|
"isp-system-service/entity"
|
||||||
"isp-system-service/migrations"
|
|
||||||
|
"github.com/stretchr/testify/suite"
|
||||||
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
|
"github.com/txix-open/isp-kit/test"
|
||||||
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
|
"github.com/txix-open/isp-kit/test/grpct"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSecureSuite(t *testing.T) {
|
func TestSecureSuite(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
suite.Run(t, &SecureSuite{})
|
suite.Run(t, &SecureSuite{})
|
||||||
}
|
}
|
||||||
|
|
||||||
type SecureSuite struct {
|
type SecureSuite struct {
|
||||||
suite.Suite
|
suite.Suite
|
||||||
test *test.Test
|
|
||||||
require *require.Assertions
|
test *test.Test
|
||||||
testDb *dbt.TestDb
|
testDb *dbt.TestDb
|
||||||
api *client.Client
|
api *client.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SecureSuite) SetupSuite() {
|
func (s *SecureSuite) SetupSuite() {
|
||||||
s.test, s.require = test.New(s.T())
|
s.test, _ = test.New(s.T())
|
||||||
|
|
||||||
s.testDb = dbt.New(s.test)
|
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
|
||||||
migrations.Initialize.SetParams("../migrations", s.testDb.Schema())
|
|
||||||
|
|
||||||
db, err := s.testDb.DB()
|
|
||||||
s.require.NoError(err)
|
|
||||||
|
|
||||||
err = migration.NewRunner(db.DB.DB, "../migrations").Run()
|
|
||||||
s.require.NoError(err)
|
|
||||||
|
|
||||||
locator := assembly.NewLocator(s.testDb, s.test.Logger())
|
locator := assembly.NewLocator(s.testDb, s.test.Logger())
|
||||||
handler := locator.Handler(conf.Remote{})
|
config := locator.Config(conf.Remote{})
|
||||||
_, s.api = grpct.TestServer(s.test, handler)
|
_, s.api = grpct.TestServer(s.test, config.Handler)
|
||||||
|
|
||||||
createdTime := time.Now().UTC()
|
createdTime := time.Now().UTC()
|
||||||
InsertDomain(s.testDb, entity.Domain{
|
InsertAppGroup(s.testDb, entity.AppGroup{
|
||||||
Id: 3, Name: "test_domain", SystemId: 1, CreatedAt: createdTime, UpdatedAt: createdTime,
|
Id: 5, Name: "test_application_group", CreatedAt: createdTime, UpdatedAt: createdTime,
|
||||||
})
|
|
||||||
InsertService(s.testDb, entity.Service{
|
|
||||||
Id: 5, Name: "test_service", DomainId: 3, CreatedAt: createdTime, UpdatedAt: createdTime,
|
|
||||||
})
|
})
|
||||||
InsertApplication(s.testDb, entity.Application{
|
InsertApplication(s.testDb, entity.Application{
|
||||||
Id: 7, Name: "test_application", ServiceId: 5, CreatedAt: createdTime, UpdatedAt: createdTime,
|
Id: 7, Name: "test_application", ApplicationGroupId: 5, CreatedAt: createdTime, UpdatedAt: createdTime,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nolint: gosec
|
||||||
func (s *SecureSuite) TestAuthenticate_Success() {
|
func (s *SecureSuite) TestAuthenticate_Success() {
|
||||||
InsertToken(s.testDb, entity.Token{
|
InsertToken(s.testDb, entity.Token{
|
||||||
Token: "test_token_success", AppId: 7, ExpireTime: -1, CreatedAt: time.Now().UTC(),
|
Token: "test_token_success", AppId: 7, ExpireTime: -1, CreatedAt: time.Now().UTC(),
|
||||||
@@ -69,16 +61,14 @@ func (s *SecureSuite) TestAuthenticate_Success() {
|
|||||||
JsonRequestBody(domain.AuthenticateRequest{
|
JsonRequestBody(domain.AuthenticateRequest{
|
||||||
Token: "test_token_success",
|
Token: "test_token_success",
|
||||||
}).
|
}).
|
||||||
ReadJsonResponse(&result).
|
JsonResponseBody(&result).
|
||||||
Do(context.Background())
|
Do(s.T().Context())
|
||||||
s.require.NoError(err)
|
s.Require().NoError(err)
|
||||||
s.require.Equal(domain.AuthenticateResponse{
|
s.Require().Equal(domain.AuthenticateResponse{
|
||||||
Authenticated: true,
|
Authenticated: true,
|
||||||
ErrorReason: "",
|
ErrorReason: "",
|
||||||
AuthData: &domain.AuthData{
|
AuthData: &domain.AuthData{
|
||||||
SystemId: 1,
|
AppName: "test_application",
|
||||||
DomainId: 3,
|
|
||||||
ServiceId: 5,
|
|
||||||
ApplicationId: 7,
|
ApplicationId: 7,
|
||||||
},
|
},
|
||||||
}, result)
|
}, result)
|
||||||
@@ -90,10 +80,10 @@ func (s *SecureSuite) TestAuthenticate_NotFound() {
|
|||||||
JsonRequestBody(domain.AuthenticateRequest{
|
JsonRequestBody(domain.AuthenticateRequest{
|
||||||
Token: "test_token_not_found",
|
Token: "test_token_not_found",
|
||||||
}).
|
}).
|
||||||
ReadJsonResponse(&result).
|
JsonResponseBody(&result).
|
||||||
Do(context.Background())
|
Do(s.T().Context())
|
||||||
s.require.NoError(err)
|
s.Require().NoError(err)
|
||||||
s.require.Equal(domain.AuthenticateResponse{
|
s.Require().Equal(domain.AuthenticateResponse{
|
||||||
Authenticated: false,
|
Authenticated: false,
|
||||||
ErrorReason: domain.ErrTokenNotFound.Error(),
|
ErrorReason: domain.ErrTokenNotFound.Error(),
|
||||||
AuthData: nil,
|
AuthData: nil,
|
||||||
@@ -110,21 +100,20 @@ func (s *SecureSuite) TestAuthenticate_NotExpired() {
|
|||||||
JsonRequestBody(domain.AuthenticateRequest{
|
JsonRequestBody(domain.AuthenticateRequest{
|
||||||
Token: "test_token_not_expired",
|
Token: "test_token_not_expired",
|
||||||
}).
|
}).
|
||||||
ReadJsonResponse(&result).
|
JsonResponseBody(&result).
|
||||||
Do(context.Background())
|
Do(s.T().Context())
|
||||||
s.require.NoError(err)
|
s.Require().NoError(err)
|
||||||
s.require.Equal(domain.AuthenticateResponse{
|
s.Require().Equal(domain.AuthenticateResponse{
|
||||||
Authenticated: true,
|
Authenticated: true,
|
||||||
ErrorReason: "",
|
ErrorReason: "",
|
||||||
AuthData: &domain.AuthData{
|
AuthData: &domain.AuthData{
|
||||||
SystemId: 1,
|
AppName: "test_application",
|
||||||
DomainId: 3,
|
|
||||||
ServiceId: 5,
|
|
||||||
ApplicationId: 7,
|
ApplicationId: 7,
|
||||||
},
|
},
|
||||||
}, result)
|
}, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nolint: gosec
|
||||||
func (s *SecureSuite) TestAuthenticate_Expired() {
|
func (s *SecureSuite) TestAuthenticate_Expired() {
|
||||||
InsertToken(s.testDb, entity.Token{
|
InsertToken(s.testDb, entity.Token{
|
||||||
Token: "test_token_expired", AppId: 7, ExpireTime: 0, CreatedAt: time.Now().UTC(),
|
Token: "test_token_expired", AppId: 7, ExpireTime: 0, CreatedAt: time.Now().UTC(),
|
||||||
@@ -135,10 +124,10 @@ func (s *SecureSuite) TestAuthenticate_Expired() {
|
|||||||
JsonRequestBody(domain.AuthenticateRequest{
|
JsonRequestBody(domain.AuthenticateRequest{
|
||||||
Token: "test_token_expired",
|
Token: "test_token_expired",
|
||||||
}).
|
}).
|
||||||
ReadJsonResponse(&result).
|
JsonResponseBody(&result).
|
||||||
Do(context.Background())
|
Do(s.T().Context())
|
||||||
s.require.NoError(err)
|
s.Require().NoError(err)
|
||||||
s.require.Equal(domain.AuthenticateResponse{
|
s.Require().Equal(domain.AuthenticateResponse{
|
||||||
Authenticated: false,
|
Authenticated: false,
|
||||||
ErrorReason: domain.ErrTokenExpired.Error(),
|
ErrorReason: domain.ErrTokenExpired.Error(),
|
||||||
AuthData: nil,
|
AuthData: nil,
|
||||||
@@ -158,10 +147,10 @@ func (s *SecureSuite) TestAuthorize_Success_True() {
|
|||||||
ApplicationId: 7,
|
ApplicationId: 7,
|
||||||
Endpoint: "endpoint/available",
|
Endpoint: "endpoint/available",
|
||||||
}).
|
}).
|
||||||
ReadJsonResponse(&result).
|
JsonResponseBody(&result).
|
||||||
Do(context.Background())
|
Do(s.T().Context())
|
||||||
s.require.NoError(err)
|
s.Require().NoError(err)
|
||||||
s.require.Equal(domain.AuthorizeResponse{
|
s.Require().Equal(domain.AuthorizeResponse{
|
||||||
Authorized: true,
|
Authorized: true,
|
||||||
}, result)
|
}, result)
|
||||||
}
|
}
|
||||||
@@ -179,10 +168,10 @@ func (s *SecureSuite) TestAuthorize_Success_False() {
|
|||||||
ApplicationId: 7,
|
ApplicationId: 7,
|
||||||
Endpoint: "endpoint/not_available",
|
Endpoint: "endpoint/not_available",
|
||||||
}).
|
}).
|
||||||
ReadJsonResponse(&result).
|
JsonResponseBody(&result).
|
||||||
Do(context.Background())
|
Do(s.T().Context())
|
||||||
s.require.NoError(err)
|
s.Require().NoError(err)
|
||||||
s.require.Equal(domain.AuthorizeResponse{
|
s.Require().Equal(domain.AuthorizeResponse{
|
||||||
Authorized: false,
|
Authorized: false,
|
||||||
}, result)
|
}, result)
|
||||||
}
|
}
|
||||||
@@ -194,10 +183,33 @@ func (s *SecureSuite) TestAuthorize_NotFound() {
|
|||||||
ApplicationId: 7,
|
ApplicationId: 7,
|
||||||
Endpoint: "endpoint/not_found",
|
Endpoint: "endpoint/not_found",
|
||||||
}).
|
}).
|
||||||
ReadJsonResponse(&result).
|
JsonResponseBody(&result).
|
||||||
Do(context.Background())
|
Do(s.T().Context())
|
||||||
s.require.NoError(err)
|
s.Require().NoError(err)
|
||||||
s.require.Equal(domain.AuthorizeResponse{
|
s.Require().Equal(domain.AuthorizeResponse{
|
||||||
Authorized: false,
|
Authorized: false,
|
||||||
}, result)
|
}, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *SecureSuite) TestAuthorize_WithHttpMethod_Success_True() {
|
||||||
|
InsertAccessList(s.testDb, entity.AccessList{
|
||||||
|
AppId: 7,
|
||||||
|
HttpMethod: http.MethodGet,
|
||||||
|
Method: "endpoint/available_http",
|
||||||
|
Value: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
result := domain.AuthorizeResponse{}
|
||||||
|
err := s.api.Invoke("system/secure/authorize").
|
||||||
|
JsonRequestBody(domain.AuthorizeRequest{
|
||||||
|
ApplicationId: 7,
|
||||||
|
HttpMethod: http.MethodGet,
|
||||||
|
Endpoint: "endpoint/available_http",
|
||||||
|
}).
|
||||||
|
JsonResponseBody(&result).
|
||||||
|
Do(s.T().Context())
|
||||||
|
s.Require().NoError(err)
|
||||||
|
s.Require().Equal(domain.AuthorizeResponse{
|
||||||
|
Authorized: true,
|
||||||
|
}, result)
|
||||||
|
}
|
||||||
+28
-6
@@ -2,10 +2,12 @@ package transaction
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"isp-system-service/service/baseline"
|
||||||
|
|
||||||
"github.com/integration-system/isp-kit/db"
|
|
||||||
"isp-system-service/repository"
|
"isp-system-service/repository"
|
||||||
"isp-system-service/service"
|
"isp-system-service/service"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Manager struct {
|
type Manager struct {
|
||||||
@@ -22,7 +24,7 @@ type accessListSetOneTx struct {
|
|||||||
repository.AccessList
|
repository.AccessList
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Manager) AccessListSetOneTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IAccessListSetOneTx) error) error {
|
func (m Manager) AccessListSetOneTx(ctx context.Context, msgTx func(ctx context.Context, tx service.AccessListSetOneTx) error) error {
|
||||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||||
accessListRepository := repository.NewAccessList(tx)
|
accessListRepository := repository.NewAccessList(tx)
|
||||||
return msgTx(ctx, accessListSetOneTx{
|
return msgTx(ctx, accessListSetOneTx{
|
||||||
@@ -35,7 +37,7 @@ type accessListSetListTx struct {
|
|||||||
repository.AccessList
|
repository.AccessList
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Manager) AccessListSetListTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IAccessListSetListTx) error) error {
|
func (m Manager) AccessListSetListTx(ctx context.Context, msgTx func(ctx context.Context, tx service.AccessListSetListTx) error) error {
|
||||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||||
accessListRep := repository.NewAccessList(tx)
|
accessListRep := repository.NewAccessList(tx)
|
||||||
return msgTx(ctx, accessListSetListTx{
|
return msgTx(ctx, accessListSetListTx{
|
||||||
@@ -48,7 +50,7 @@ type applicationDeleteTx struct {
|
|||||||
repository.Application
|
repository.Application
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Manager) ApplicationDeleteTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IApplicationDeleteTx) error) error {
|
func (m Manager) ApplicationDeleteTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ApplicationDeleteTx) error) error {
|
||||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||||
applicationRep := repository.NewApplication(tx)
|
applicationRep := repository.NewApplication(tx)
|
||||||
return msgTx(ctx, applicationDeleteTx{
|
return msgTx(ctx, applicationDeleteTx{
|
||||||
@@ -61,7 +63,7 @@ type tokenCreateTx struct {
|
|||||||
repository.Token
|
repository.Token
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Manager) TokenCreateTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ITokenCreateTx) error) error {
|
func (m Manager) TokenCreateTx(ctx context.Context, msgTx func(ctx context.Context, tx service.TokenCreateTx) error) error {
|
||||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||||
tokenRep := repository.NewToken(tx)
|
tokenRep := repository.NewToken(tx)
|
||||||
return msgTx(ctx, tokenCreateTx{
|
return msgTx(ctx, tokenCreateTx{
|
||||||
@@ -74,7 +76,7 @@ type tokenRevokeTx struct {
|
|||||||
repository.Token
|
repository.Token
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ITokenRevokeTx) error) error {
|
func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Context, tx service.TokenRevokeTx) error) error {
|
||||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||||
tokenRep := repository.NewToken(tx)
|
tokenRep := repository.NewToken(tx)
|
||||||
return msgTx(ctx, tokenRevokeTx{
|
return msgTx(ctx, tokenRevokeTx{
|
||||||
@@ -82,3 +84,23 @@ func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Conte
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type baselineTx struct {
|
||||||
|
repository.Locker
|
||||||
|
repository.AppGroup
|
||||||
|
repository.Application
|
||||||
|
repository.AccessList
|
||||||
|
repository.Token
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Manager) BaselineTx(ctx context.Context, txTx func(ctx context.Context, tx baseline.Transaction) error) error {
|
||||||
|
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||||
|
return txTx(ctx, baselineTx{
|
||||||
|
Locker: repository.NewLocker(tx),
|
||||||
|
AppGroup: repository.NewAppGroup(tx),
|
||||||
|
Application: repository.NewApplication(tx),
|
||||||
|
AccessList: repository.NewAccessList(tx),
|
||||||
|
Token: repository.NewToken(tx),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
Reference in new issue
Block a user