10 Commits
83 changed files with 6796 additions and 2048 deletions

No files matched your search

+2 -1
View File
@@ -71,5 +71,6 @@ fabric.properties
/vendor/ /vendor/
google/ google/
package.json package.json
structure/
yarn.lock yarn.lock
conf/config_dev.yml
+3
View File
@@ -0,0 +1,3 @@
include:
- project: '$CI_PROJECT_PATH'
file: '/ci-isp-go-service.yml'
+53
View File
@@ -0,0 +1,53 @@
run:
allow-parallel-runners: true
issues:
exclude-rules:
- path: controller #достаточное кол-во контекса на уровне контроллеров
linters:
- wrapcheck
- path: transaction #транзакции прозрачны
linters:
- wrapcheck
linters:
enable-all: true
disable:
- goimports #у нас собственные правила форматирования импортов
- wsl #расставление пробелов очень индивидуально
- varnamelen #очень индивидуально (db)
- exhaustruct #не имеет смысла
- contextcheck #не имеет смысла
- gci #у нас собственные правила форматирования импортов
- gofumpt #у нас собственные правила форматирования импортов
- nolintlint #Goland все равно форматирует с отступом
- nlreturn #не всегда имеет смысл
- godot #не актуально для свагера
- godox #не позволяет оставлять todo
- depguard #не всегда имеет смысл
- dupword #не имеет смысла
- tagalign #не всегда имеет смысл
- musttag #у нас собственные правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внених для нас структур
- perfsprint #мнимая производительность в угоду читаемости
- gomnd #устарел
- exportloopref #устарел
- execinquery #устарел
linters-settings:
funlen:
lines: 80
lll:
line-length: 150
cyclop:
max-complexity: 15 #по умолчанию 10 мало
revive:
rules:
- name: var-naming #отключаем Id -> ID
disabled: true
stylecheck:
checks: #отключаем Id -> ID
- "-ST1000"
- "-ST1016"
- "-ST1020"
- "-ST1021"
- "-ST1022"
testifylint:
disable:
- compares
+1 -1
View File
@@ -1 +1 @@
0.3.0 5.2.1
+79
View File
@@ -0,0 +1,79 @@
### 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
* Удален `InstanceUuid`
* Удалена интеграция с Redis
* Генерация токенов теперь использует обычный crypto/rand вместо JWT
* Убран из конфига defaultTokenExpireTime
* Добавлены методы проверки подлинности токенов и прав у приложений
* system/secure/authenticate
* system/secure/authorize
### v3.0.2
* исправлена ошибка при обновлении имени или описании у созданного application
### v3.0.1
* mark `InstanceUuid` as required
### v3.0.0
* migrate to isp-kit
* split domain and entity structs
* prepare to remove system block
* remove CRUD for system
* use default system_id
* remove migration initializing city_module
* unite requests to redis into one directory
* prepare to remove redis
* update go to 1.17
### v2.2.7
* updated dependencies
* migrated to common local config
### v2.2.6
* fix migrations
### v2.2.5
* updated dependencies
### v2.2.4
* updated isp-lib
### v2.2.3
* updated isp-lib
* updated isp-lib-test
### v2.2.2
* updated isp-lib
* updated isp-event-lib
### v2.2.1
* fix linter
### v2.2.0
* update libs
### v2.1.0
* update to go mod
### v2.0.0
* update `isp-lib` to 2.0.0
### v1.2.0
* add `access list` methods
* fix revoke token
### v1.1.3
* update to new log
* migrate to new db client
### v1.1.2
* add document generation
### v1.1.1
* update config description
* update lib
### v1.1.0
* add default remote configuration
+41
View File
@@ -0,0 +1,41 @@
FROM dockerhub.mos.ru/mosos/arbat:15.5 as builder
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.24 git
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/mosos/arbat:15.5
RUN cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime
RUN echo "Europe/Moscow" > /etc/timezone
ARG UID=10001
RUN useradd \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
--user-group \
appuser
RUN mkdir -p /app/data
RUN chown appuser:appuser /app/data
VOLUME /app/data
USER appuser
WORKDIR /app
ARG app_name
ENV app_name_env=$app_name
COPY --from=builder main /app/$app_name_env
COPY /conf/config.yml /app/config.yml
COPY /conf/default_remote_config.json* /app/default_remote_config.json
COPY /migrations /app/migrations
ENTRYPOINT /app/$app_name_env
Generated
-599
View File
@@ -1,599 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214"
name = "github.com/StackExchange/wmi"
packages = ["."]
pruneopts = "UT"
revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338"
version = "1.0.0"
[[projects]]
digest = "1:320e7ead93de9fd2b0e59b50fd92a4d50c1f8ab455d96bc2eb083267453a9709"
name = "github.com/asaskevich/govalidator"
packages = ["."]
pruneopts = "UT"
revision = "ccb8e960c48f04d6935e72476ae4a51028f9e22f"
version = "v9"
[[projects]]
digest = "1:652880afc6b57ce0a67173f552cb35ccda816493a1da6ca20e5074a66bcd083f"
name = "github.com/buaazp/fasthttprouter"
packages = ["."]
pruneopts = "UT"
revision = "ade4e2031af3aed7fffd241084aad80a58faf421"
version = "v0.1.1"
[[projects]]
digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd"
name = "github.com/fsnotify/fsnotify"
packages = ["."]
pruneopts = "UT"
revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
version = "v1.4.7"
[[projects]]
digest = "1:64a5a67c69b70c2420e607a8545d674a23778ed9c3e80607bfd17b77c6c87f6a"
name = "github.com/go-ole/go-ole"
packages = [
".",
"oleutil",
]
pruneopts = "UT"
revision = "a41e3c4b706f6ae8dfbff342b06e40fa4d2d0506"
version = "v1.2.1"
[[projects]]
digest = "1:e7f1117ec9d37b59ba6d70bbd8feaa9cd2d1c6f676dc88ee152f5a57908fea4b"
name = "github.com/go-pg/pg"
packages = [
".",
"internal",
"internal/parser",
"internal/pool",
"orm",
"types",
]
pruneopts = "UT"
revision = "514bed76d8f579d6ff8d40294fa77e476a5c1b3f"
version = "v6.15.0"
[[projects]]
digest = "1:7c2fd446293ff7799cc496d3446e674ee67902d119f244de645caf95dff1bb98"
name = "github.com/go-redis/redis"
packages = [
".",
"internal",
"internal/consistenthash",
"internal/hashtag",
"internal/pool",
"internal/proto",
"internal/singleflight",
"internal/util",
]
pruneopts = "UT"
revision = "f3bba01df2026fc865f7782948845db9cf44cf23"
version = "v6.14.1"
[[projects]]
digest = "1:33ed5e4977aa41d90a7944c173080c9cf6c5ecba2419ff7c8e1385f16a67bc8c"
name = "github.com/golang/protobuf"
packages = [
"proto",
"ptypes",
"ptypes/any",
"ptypes/duration",
"ptypes/struct",
"ptypes/timestamp",
]
pruneopts = "UT"
revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5"
version = "v1.2.0"
[[projects]]
branch = "master"
digest = "1:324591cd9122f94cc39a87bd44ec71153672c239e2cff5743bfad96b60be3749"
name = "github.com/googollee/go-engine.io"
packages = [
".",
"message",
"parser",
"polling",
"transport",
"websocket",
]
pruneopts = "UT"
revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509"
[[projects]]
branch = "master"
digest = "1:8ec54d9488698e9db22139250bde10e35aab02c20236e4d1c1457604c2c4fe18"
name = "github.com/googollee/go-socket.io"
packages = ["."]
pruneopts = "UT"
revision = "25e1f67559cf5d0e41efbc3e0157bb952596ffc3"
[[projects]]
digest = "1:7b5c6e2eeaa9ae5907c391a91c132abfd5c9e8a784a341b5625e750c67e6825d"
name = "github.com/gorilla/websocket"
packages = ["."]
pruneopts = "UT"
revision = "66b9c49e59c6c48f0ffce28c2d8b8a5678502c6d"
version = "v1.4.0"
[[projects]]
digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10"
name = "github.com/hashicorp/hcl"
packages = [
".",
"hcl/ast",
"hcl/parser",
"hcl/printer",
"hcl/scanner",
"hcl/strconv",
"hcl/token",
"json/parser",
"json/scanner",
"json/token",
]
pruneopts = "UT"
revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241"
version = "v1.0.0"
[[projects]]
branch = "master"
digest = "1:1b1d9534e35d61e861a7356f7f2d766e57e2777dbf79be60e1ac56bbd60adf51"
name = "github.com/integration-system/go-cmp"
packages = [
"cmp",
"cmp/internal/diff",
"cmp/internal/function",
"cmp/internal/value",
]
pruneopts = "UT"
revision = "ed1c8d9bf7906aec13cf28080fdf069d7687471a"
[[projects]]
branch = "master"
digest = "1:9e2fd899fdb17e28e9d036fe7a604a1e04918aa4865d5a2150008fc12c6134be"
name = "github.com/integration-system/golang-socketio"
packages = [
".",
"protocol",
"transport",
]
pruneopts = "UT"
revision = "5959fcea049facd9441fff9de976191accd3cf9f"
[[projects]]
branch = "master"
digest = "1:64ca7b65a9993ecfcae59e75f1f0f6e2102bc99b6e2a2387ad1d29f36567e199"
name = "github.com/integration-system/isp-lib"
packages = [
"backend",
"bootstrap",
"config",
"config/schema",
"database",
"http",
"logger",
"metric",
"proto/stubs",
"redis",
"socket",
"streaming",
"structure",
"token-gen",
"utils",
]
pruneopts = "UT"
revision = "0f71aaf83133a59c9fc143faecbd38b86ed068e2"
[[projects]]
branch = "master"
digest = "1:a992b3ab79433b828258f9fe99af29da5aeb2e48bf8076a41ba556ac90ac04d3"
name = "github.com/integration-system/jsonschema"
packages = ["."]
pruneopts = "UT"
revision = "170a88febd847f36821e99ec54a095e6cec48528"
[[projects]]
branch = "master"
digest = "1:fd97437fbb6b7dce04132cf06775bd258cce305c44add58eb55ca86c6c325160"
name = "github.com/jinzhu/inflection"
packages = ["."]
pruneopts = "UT"
revision = "04140366298a54a039076d798123ffa108fff46c"
[[projects]]
digest = "1:5d713dbcad44f3358fec51fd5573d4f733c02cac5a40dcb177787ad5ffe9272f"
name = "github.com/json-iterator/go"
packages = [
".",
"extra",
]
pruneopts = "UT"
revision = "1624edc4454b8682399def8740d46db5e4362ba4"
version = "v1.1.5"
[[projects]]
digest = "1:cdbed6a7b574b13bbabcd8c36c5be56d6444789bab21fcd37d39655eab0b2141"
name = "github.com/klauspost/compress"
packages = [
"flate",
"gzip",
"zlib",
]
pruneopts = "UT"
revision = "b939724e787a27c0005cabe3f78e7ed7987ac74f"
version = "v1.4.0"
[[projects]]
digest = "1:4ea0668d490ca32a38366453a486e2e8c60fbdaf1f2607c96b4a093d8a5c8de7"
name = "github.com/klauspost/cpuid"
packages = ["."]
pruneopts = "UT"
revision = "ae7887de9fa5d2db4eaa8174a7eff2c1ac00f2da"
version = "v1.1"
[[projects]]
digest = "1:0a69a1c0db3591fcefb47f115b224592c8dfa4368b7ba9fae509d5e16cdc95c8"
name = "github.com/konsorten/go-windows-terminal-sequences"
packages = ["."]
pruneopts = "UT"
revision = "5c8c8bd35d3832f5d134ae1e1e375b69a4d25242"
version = "v1.0.1"
[[projects]]
digest = "1:8ef506fc2bb9ced9b151dafa592d4046063d744c646c1bbe801982ce87e4bc24"
name = "github.com/lib/pq"
packages = [
".",
"oid",
]
pruneopts = "UT"
revision = "4ded0e9383f75c197b3a2aaa6d590ac52df6fd79"
version = "v1.0.0"
[[projects]]
digest = "1:c568d7727aa262c32bdf8a3f7db83614f7af0ed661474b24588de635c20024c7"
name = "github.com/magiconair/properties"
packages = ["."]
pruneopts = "UT"
revision = "c2353362d570a7bfa228149c62842019201cfb71"
version = "v1.8.0"
[[projects]]
digest = "1:c658e84ad3916da105a761660dcaeb01e63416c8ec7bc62256a9b411a05fcd67"
name = "github.com/mattn/go-colorable"
packages = ["."]
pruneopts = "UT"
revision = "167de6bfdfba052fa6b2d3664c8f5272e23c9072"
version = "v0.0.9"
[[projects]]
digest = "1:0981502f9816113c9c8c4ac301583841855c8cf4da8c72f696b3ebedf6d0e4e5"
name = "github.com/mattn/go-isatty"
packages = ["."]
pruneopts = "UT"
revision = "6ca4dbf54d38eea1a992b3c722a76a5d1c4cb25c"
version = "v0.0.4"
[[projects]]
branch = "master"
digest = "1:2b32af4d2a529083275afc192d1067d8126b578c7a9613b26600e4df9c735155"
name = "github.com/mgutz/ansi"
packages = ["."]
pruneopts = "UT"
revision = "9520e82c474b0a04dd04f8a40959027271bab992"
[[projects]]
digest = "1:53bc4cd4914cd7cd52139990d5170d6dc99067ae31c56530621b18b35fc30318"
name = "github.com/mitchellh/mapstructure"
packages = ["."]
pruneopts = "UT"
revision = "3536a929edddb9a5b34bd6861dc4a9647cb459fe"
version = "v1.1.2"
[[projects]]
digest = "1:33422d238f147d247752996a26574ac48dcf472976eda7f5134015f06bf16563"
name = "github.com/modern-go/concurrent"
packages = ["."]
pruneopts = "UT"
revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94"
version = "1.0.3"
[[projects]]
digest = "1:e32bdbdb7c377a07a9a46378290059822efdce5c8d96fe71940d87cb4f918855"
name = "github.com/modern-go/reflect2"
packages = ["."]
pruneopts = "UT"
revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd"
version = "1.0.1"
[[projects]]
branch = "master"
digest = "1:84bd7f8a2e0bcd53ddc33c3b47c34c1fe340c8632cbe928f7f8ae10ec6ecdd62"
name = "github.com/mohae/deepcopy"
packages = ["."]
pruneopts = "UT"
revision = "c48cc78d482608239f6c4c92a4abd87eb8761c90"
[[projects]]
digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e"
name = "github.com/pelletier/go-toml"
packages = ["."]
pruneopts = "UT"
revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194"
version = "v1.2.0"
[[projects]]
digest = "1:65c6401efaeb147041aed03d5b18862ce666a54e4ce754ea6ddbfa5ddaa24b07"
name = "github.com/pressly/goose"
packages = ["."]
pruneopts = "UT"
revision = "95600eb369b1f657efd54a401ab85d0647a1db80"
version = "v2.3.0"
[[projects]]
branch = "master"
digest = "1:c4556a44e350b50a490544d9b06e9fba9c286c21d6c0e47f54f3a9214597298c"
name = "github.com/rcrowley/go-metrics"
packages = ["."]
pruneopts = "UT"
revision = "e2704e165165ec55d062f5919b4b29494e9fa790"
[[projects]]
digest = "1:7c974e104a8fb96baf5bf09dcfbc4ba804de8edb4f0d73aa5d61d3a8e46e885f"
name = "github.com/shirou/gopsutil"
packages = [
"cpu",
"internal/common",
]
pruneopts = "UT"
revision = "8048a2e9c5773235122027dd585cf821b2af1249"
version = "v2.18.07"
[[projects]]
digest = "1:3f53e9e4dfbb664cd62940c9c4b65a2171c66acd0b7621a1a6b8e78513525a52"
name = "github.com/sirupsen/logrus"
packages = ["."]
pruneopts = "UT"
revision = "ad15b42461921f1fb3529b058c6786c6a45d5162"
version = "v1.1.1"
[[projects]]
digest = "1:6a4a11ba764a56d2758899ec6f3848d24698d48442ebce85ee7a3f63284526cd"
name = "github.com/spf13/afero"
packages = [
".",
"mem",
]
pruneopts = "UT"
revision = "d40851caa0d747393da1ffb28f7f9d8b4eeffebd"
version = "v1.1.2"
[[projects]]
digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f"
name = "github.com/spf13/cast"
packages = ["."]
pruneopts = "UT"
revision = "8965335b8c7107321228e3e3702cab9832751bac"
version = "v1.2.0"
[[projects]]
digest = "1:68ea4e23713989dc20b1bded5d9da2c5f9be14ff9885beef481848edd18c26cb"
name = "github.com/spf13/jwalterweatherman"
packages = ["."]
pruneopts = "UT"
revision = "4a4406e478ca629068e7768fc33f3f044173c0a6"
version = "v1.0.0"
[[projects]]
digest = "1:c1b1102241e7f645bc8e0c22ae352e8f0dc6484b6cb4d132fa9f24174e0119e2"
name = "github.com/spf13/pflag"
packages = ["."]
pruneopts = "UT"
revision = "298182f68c66c05229eb03ac171abe6e309ee79a"
version = "v1.0.3"
[[projects]]
digest = "1:214775c11fd26da94a100111a62daa25339198a4f9c57cb4aab352da889f5b93"
name = "github.com/spf13/viper"
packages = ["."]
pruneopts = "UT"
revision = "2c12c60302a5a0e62ee102ca9bc996277c2f64f5"
version = "v1.2.1"
[[projects]]
branch = "master"
digest = "1:d32b64a7a82dd36b674fb73ff767e949eb7155b6b574ff276f49d4edc8af105f"
name = "github.com/thecodeteam/goodbye"
packages = ["."]
pruneopts = "UT"
revision = "a83968bda2d37294a3541b7d2207fb6f5a3559a3"
[[projects]]
digest = "1:c468422f334a6b46a19448ad59aaffdfc0a36b08fdcc1c749a0b29b6453d7e59"
name = "github.com/valyala/bytebufferpool"
packages = ["."]
pruneopts = "UT"
revision = "e746df99fe4a3986f4d4f79e13c1e0117ce9c2f7"
version = "v1.0.0"
[[projects]]
branch = "master"
digest = "1:71d4697600b36699831188365840b77814f1d5e740d6c27aa82278ffcf1e6ea1"
name = "github.com/valyala/fasthttp"
packages = [
".",
"fasthttputil",
"stackless",
]
pruneopts = "UT"
revision = "63ea2d380ff30e6f09dc8c39205363c7c064bc31"
[[projects]]
branch = "master"
digest = "1:c83590426ecf1362e77a9054afed570b201de1a353398a6157ecce06583ea024"
name = "github.com/vmihailenco/sasl"
packages = ["."]
pruneopts = "UT"
revision = "2f13c189728a02f8cc31b3b9cc06047b383c21cc"
[[projects]]
digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9"
name = "github.com/x-cray/logrus-prefixed-formatter"
packages = ["."]
pruneopts = "UT"
revision = "bb2702d423886830dee131692131d35648c382e2"
version = "v0.5.2"
[[projects]]
branch = "master"
digest = "1:cb77e5934866333fa0784326a57e64c4da128001c94fbd1d29819d79bd3b1087"
name = "golang.org/x/crypto"
packages = [
"pbkdf2",
"ssh/terminal",
]
pruneopts = "UT"
revision = "e3636079e1a4c1f337f212cc5cd2aca108f6c900"
[[projects]]
branch = "master"
digest = "1:505dbee0833715a72a529bb57c354826ad42a4496fad787fa143699b4de1a6d0"
name = "golang.org/x/net"
packages = [
"context",
"http/httpguts",
"http2",
"http2/hpack",
"idna",
"internal/timeseries",
"trace",
]
pruneopts = "UT"
revision = "146acd28ed5894421fb5aac80ca93bc1b1f46f87"
[[projects]]
branch = "master"
digest = "1:850d28ab022512e2cd3cf511a77f363c29e22689b4031f2050871f5de47ae4a0"
name = "golang.org/x/sys"
packages = [
"unix",
"windows",
]
pruneopts = "UT"
revision = "4497e2df6f9e69048a54498c7affbbec3294ad47"
[[projects]]
digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18"
name = "golang.org/x/text"
packages = [
"collate",
"collate/build",
"internal/colltab",
"internal/gen",
"internal/tag",
"internal/triegen",
"internal/ucd",
"language",
"secure/bidirule",
"transform",
"unicode/bidi",
"unicode/cldr",
"unicode/norm",
"unicode/rangetable",
]
pruneopts = "UT"
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
version = "v0.3.0"
[[projects]]
branch = "master"
digest = "1:e3b8d9d88865972c4c90948166b34ffa8b105e00ba55407b48e211852752cc69"
name = "google.golang.org/genproto"
packages = [
"googleapis/rpc/errdetails",
"googleapis/rpc/status",
]
pruneopts = "UT"
revision = "af9cb2a35e7f169ec875002c1829c9b315cddc04"
[[projects]]
digest = "1:ab8e92d746fb5c4c18846b0879842ac8e53b3d352449423d0924a11f1020ae1b"
name = "google.golang.org/grpc"
packages = [
".",
"balancer",
"balancer/base",
"balancer/roundrobin",
"codes",
"connectivity",
"credentials",
"encoding",
"encoding/proto",
"grpclog",
"internal",
"internal/backoff",
"internal/channelz",
"internal/envconfig",
"internal/grpcrand",
"internal/transport",
"keepalive",
"metadata",
"naming",
"peer",
"resolver",
"resolver/dns",
"resolver/passthrough",
"stats",
"status",
"tap",
]
pruneopts = "UT"
revision = "8dea3dc473e90c8179e519d91302d0597c0ca1d1"
version = "v1.15.0"
[[projects]]
digest = "1:c805e517269b0ba4c21ded5836019ed7d16953d4026cb7d00041d039c7906be9"
name = "gopkg.in/natefinch/lumberjack.v2"
packages = ["."]
pruneopts = "UT"
revision = "a96e63847dc3c67d17befa69c303767e2f84e54f"
version = "v2.1"
[[projects]]
digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202"
name = "gopkg.in/yaml.v2"
packages = ["."]
pruneopts = "UT"
revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183"
version = "v2.2.1"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
input-imports = [
"github.com/go-pg/pg",
"github.com/go-pg/pg/orm",
"github.com/go-redis/redis",
"github.com/integration-system/isp-lib/backend",
"github.com/integration-system/isp-lib/bootstrap",
"github.com/integration-system/isp-lib/config",
"github.com/integration-system/isp-lib/database",
"github.com/integration-system/isp-lib/metric",
"github.com/integration-system/isp-lib/redis",
"github.com/integration-system/isp-lib/socket",
"github.com/integration-system/isp-lib/structure",
"github.com/integration-system/isp-lib/token-gen",
"github.com/integration-system/isp-lib/utils",
"github.com/pressly/goose",
"google.golang.org/grpc/codes",
"google.golang.org/grpc/metadata",
"google.golang.org/grpc/status",
]
solver-name = "gps-cdcl"
solver-version = 1
-30
View File
@@ -1,30 +0,0 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true
[prune]
go-tests = true
unused-packages = true
+1
View File
@@ -0,0 +1 @@
test2
+85
View File
@@ -0,0 +1,85 @@
package assembly
import (
"context"
"github.com/txix-open/isp-kit/rc"
"github.com/pkg/errors"
"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/grpc"
"github.com/txix-open/isp-kit/log"
"isp-system-service/conf"
)
type Assembly struct {
boot *bootstrap.Bootstrap
db *dbrx.Client
server *grpc.Server
logger *log.Adapter
}
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
logger := boot.App.Logger()
dbCli := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, logger))
server := grpc.NewServer()
return &Assembly{
boot: boot,
db: dbCli,
server: server,
logger: logger,
}, nil
}
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
newCfg, _, err := rc.Upgrade[conf.Remote](a.boot.RemoteConfig, remoteConfig)
if err != nil {
a.boot.Fatal(errors.WithMessage(err, "upgrade remote config"))
}
a.logger.SetLevel(newCfg.LogLevel)
err = a.db.Upgrade(ctx, newCfg.Database)
if err != nil {
a.boot.Fatal(errors.WithMessage(err, "upgrade db client"))
}
locator := NewLocator(a.db, a.logger)
config := locator.Config(newCfg)
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
}
func (a *Assembly) Runners() []app.Runner {
eventHandler := cluster.NewEventHandler().
RemoteConfigReceiver(a)
return []app.Runner{
app.RunnerFunc(func(ctx context.Context) error {
return a.server.ListenAndServe(a.boot.BindingAddress)
}),
app.RunnerFunc(func(ctx context.Context) error {
return a.boot.ClusterCli.Run(ctx, eventHandler)
}),
}
}
func (a *Assembly) Closers() []app.Closer {
return []app.Closer{
a.boot.ClusterCli,
app.CloserFunc(func() error {
a.server.Shutdown()
return nil
}),
a.db,
}
}
+87
View File
@@ -0,0 +1,87 @@
package assembly
import (
"isp-system-service/conf"
"isp-system-service/controller"
"isp-system-service/repository"
"isp-system-service/routes"
"isp-system-service/service"
"isp-system-service/service/baseline"
"isp-system-service/service/secure"
"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 {
db.DB
db.Transactional
}
type Locator struct {
db DB
logger log.Logger
}
func NewLocator(db DB, logger log.Logger) Locator {
return Locator{
db: db,
logger: logger,
}
}
type Config struct {
Handler *grpc.Mux
Baseline baseline.Service
}
func (l Locator) Config(cfg conf.Remote) Config {
txManager := transaction.NewManager(l.db)
accessListRep := repository.NewAccessList(l.db)
applicationRep := repository.NewApplication(l.db)
domainRep := repository.NewDomain(l.db)
appGroupRep := repository.NewAppGroup(l.db)
tokenRep := repository.NewToken(l.db)
secureService := secure.NewService(tokenRep, accessListRep)
accessListService := service.NewAccessList(txManager, accessListRep, applicationRep)
applicationService := service.NewApplication(txManager, applicationRep, domainRep, appGroupRep, tokenRep)
domainService := service.NewDomain(domainRep)
serviceService := service.NewService(domainRep, appGroupRep)
jwtService := service.NewTokenSource()
tokenService := service.NewToken(jwtService, applicationService, txManager,
applicationRep, domainRep, appGroupRep, tokenRep,
)
secureController := controller.NewSecure(secureService)
accessListController := controller.NewAccessList(accessListService)
applicationController := controller.NewApplication(applicationService)
domainController := controller.NewDomain(domainService)
serviceController := controller.NewService(serviceService)
tokenController := controller.NewToken(tokenService)
appGroupService := service.NewAppGroup(appGroupRep)
appGroupController := controller.NewAppGroup(appGroupService)
c := routes.Controllers{
Secure: secureController,
AccessList: accessListController,
Domain: domainController,
Service: serviceController,
Application: applicationController,
Token: tokenController,
AppGroup: appGroupController,
}
mapper := endpoint.DefaultWrapper(l.logger, grpclog.Log(l.logger, true))
server := routes.Handler(mapper, c)
baselineService := baseline.NewService(cfg.Baseline, txManager, l.logger)
return Config{
Handler: server,
Baseline: baselineService,
}
}
+9 -2
View File
@@ -7,5 +7,12 @@ grpcOuterAddress:
grpcInnerAddress: grpcInnerAddress:
ip: 0.0.0.0 ip: 0.0.0.0
port: 9005 port: 9005
moduleName: system moduleName: isp-system-service
instanceUuid: 3f4faf30-8482-48ef-931a-b15575a3af1d
infraServerPort: 9555
logfile:
path: /var/log/isp-system-service/runtime.log
maxSizeMb: 512
maxBackups: 4
compress: true
+14
View File
@@ -0,0 +1,14 @@
{
"logLevel": "debug",
"database": {
"schema": "isp_system_service",
"database": "{{ msp_pgsql_name }}",
"password": "{{ msp_pgsql_password }}",
"username": "{{ msp_pgsql_user }}",
"host": "{{ msp_pgsql_address }}",
"port": 5432
},
"baseline": {
"initialAdminUiToken": "{{ isp_service_admin_token }}"
}
}
-11
View File
@@ -1,11 +0,0 @@
package conf
import "github.com/integration-system/isp-lib/structure"
type Configuration struct {
InstanceUuid string
ModuleName string
ConfigServiceAddress structure.AddressConfiguration
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
GrpcInnerAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcInnerAddress"`
}
+28
View File
@@ -0,0 +1,28 @@
package conf
import (
"reflect"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/rc/schema"
"github.com/txix-open/jsonschema"
)
//nolint:gochecknoinits
func init() {
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
t.Type = "string"
t.Enum = []interface{}{"debug", "info", "error", "fatal"}
})
}
type Remote struct {
Database dbx.Config `schema:"Настройка базы данных"`
Baseline Baseline
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
}
type Baseline struct {
InitialAdminUiToken string
}
-13
View File
@@ -1,13 +0,0 @@
package conf
import (
"github.com/integration-system/isp-lib/database"
"github.com/integration-system/isp-lib/structure"
)
type RemoteConfig struct {
DB database.DBConfiguration `schema:"Database"`
RedisAddress structure.AddressConfiguration `schema:"Redis"`
DefaultTokenExpireTime int64 `schema:"Default token expire time,In milliseconds"`
Metrics structure.MetricConfiguration `schema:"Metrics"`
}
+13
View File
@@ -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{})
}
+115
View File
@@ -0,0 +1,115 @@
package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
)
type AccessListService interface {
GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error)
SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error)
SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error)
}
type AccessList struct {
service AccessListService
}
func NewAccessList(service AccessListService) AccessList {
return AccessList{
service: service,
}
}
// GetById godoc
//
// @Tags accessList
// @Summary Получить список доступности методов для приложения
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
// @Accept json
// @Produce json
// @Param body body domain.Identity false "идентификатор приложения"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} apierrors.Error
// @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) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
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
}
}
// SetOne godoc
//
// @Tags accessList
// @Summary Настроить доступность метода для приложения
// @Description Возвращает количество измененных строк
// @Accept json
// @Produce json
// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа"
// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк"
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/set_one [POST]
func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
result, err := c.service.SetOne(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.AppId),
err,
)
case err != nil:
return nil, err
default:
return result, nil
}
}
// SetList godoc
//
// @Tags accessList
// @Summary Настроить доступность списка методов для приложения
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
// @Accept json
// @Produce json
// @Param body body domain.AccessListSetListRequest false "объект настройки доступа"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/set_list [POST]
func (c AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
result, err := c.service.SetList(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.AppId),
err,
)
case err != nil:
return nil, err
default:
return result, nil
}
}
+139
View File
@@ -0,0 +1,139 @@
package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/pkg/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)
}
+264 -162
View File
@@ -1,191 +1,293 @@
package controller package controller
import ( import (
"isp-system-service/entity" "context"
"isp-system-service/model" "fmt"
"github.com/integration-system/isp-lib/database" "isp-system-service/domain"
"github.com/integration-system/isp-lib/utils"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
) )
func GetApplications(list []int32) ([]*AppWithToken, error) { type ApplicationService interface {
res, err := model.AppRep.GetApplications(list) GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error)
if err != nil { GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error)
return nil, err GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error)
} SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error)
return enrichWithTokens(res...) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, 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.ApplicationWithTokens, error)
Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error)
} }
func GetApplicationsByServiceId(identity Identity) ([]*AppWithToken, error) { type Application struct {
arr, err := model.AppRep.GetApplicationsByServiceId(identity.Id) service ApplicationService
if err != nil {
return nil, err
}
return enrichWithTokens(arr...)
} }
func CreateUpdateApplication(app entity.Application) (*AppWithToken, error) { func NewApplication(service ApplicationService) Application {
existed, err := model.AppRep.GetApplicationByNameAndServiceId(app.Name, app.ServiceId) return Application{
if err != nil { service: service,
return nil, err
}
s, e := model.ServiceRep.GetServiceById(app.ServiceId)
if e != nil {
return nil, e
}
if s == nil {
return nil, status.Errorf(codes.InvalidArgument, "Service with id %d not found", app.ServiceId)
}
if app.Id == 0 {
if existed != nil {
return nil, status.Errorf(codes.AlreadyExists, "Application with name %s already exists", app.Name)
}
app, e := model.AppRep.CreateApplication(app)
enrichWithTokens(app)
return &AppWithToken{App: app, Tokens: []entity.Token{}}, e
} else {
if existed != nil && existed.Id != app.Id {
return nil, status.Errorf(codes.AlreadyExists, "Application with name %s already exists", app.Name)
}
existed, err = model.AppRep.GetApplicationById(app.Id)
if err != nil {
return nil, err
}
if existed == nil {
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", app.Id)
}
app, e := model.AppRep.UpdateApplication(app)
if e != nil {
return nil, e
}
arr, err := enrichWithTokens(app)
if err != nil {
return nil, err
}
return arr[0], nil
} }
} }
func GetApplicationById(identity Identity) (*AppWithToken, error) { // GetById godoc
application, err := model.AppRep.GetApplicationById(identity.Id) //
if err != nil { // @Tags application
// @Summary Получить приложение по идентификатору
// @Description Возвращает описание приложения по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/get_application_by_id [POST]
func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
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 return nil, err
default:
return result, nil
} }
if application == nil {
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", identity.Id)
}
arr, err := enrichWithTokens(*application)
if err != nil {
return nil, err
}
return arr[0], nil
} }
func DeleteApplications(list []int32) (DeleteResponse, error) { // GetByIdList godoc
if len(list) == 0 { //
return DeleteResponse{}, status.Errorf(codes.InvalidArgument, "At least one id are required") // @Tags application
} // @Summary Получить список приложений
var count = 0 // @Description Возвращает массив приложений с токенами по их идентификаторам
err := database.RunInTransaction(func(appRep model.AppRepository, tokenRep model.TokenRepository) error { // @Accept json
for _, appId := range list { // @Produce json
_, err := revokeTokensForApp(Identity{appId}, &tokenRep) // @Param body body []integer false "Массив идентификаторов приложений"
if err != nil { // @Success 200 {array} domain.ApplicationWithTokens
return err // @Failure 500 {object} apierrors.Error
} // @Router /application/get_applications [POST]
} func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) {
res, err := appRep.DeleteApplications(list) return c.service.GetByIdList(ctx, req)
if err != nil {
return err
}
count = res
return nil
})
if err != nil {
return DeleteResponse{}, err
}
return DeleteResponse{Deleted: count}, nil
} }
func GetSystemTree(md metadata.MD) ([]*DomainWithServices, error) { // GetByServiceId godoc
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md) //
if err != nil { // @Tags application
return nil, err // @Summary Получить список приложений по идентификатору сервиса
} // @Description Возвращает список приложений по запрошенному идентификатору сервиса
domains, err := model.DomainRep.GetDomainsBySystemId(int32(sysId)) // @Accept json
if err != nil { // @Produce json
return nil, err // @Param body body domain.Identity true "Идентификатор сервиса"
} // @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} apierrors.Error
l := len(domains) // @Router /application/get_applications_by_service_id [POST]
if l == 0 { func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) {
return []*DomainWithServices{}, nil return c.service.GetByServiceId(ctx, req.Id)
}
idList := make([]int32, l)
domainsMap := make(map[int32]*DomainWithServices, l)
res := make([]*DomainWithServices, l)
for i, d := range domains {
idList[i] = d.Id
dws := &DomainWithServices{Id: d.Id, Name: d.Name, Description: d.Description}
domainsMap[d.Id] = dws
res[i] = dws
}
services, err := model.ServiceRep.GetServicesByDomainId(idList...)
if err != nil {
return nil, err
}
l = len(services)
idList = make([]int32, l)
servicesMap := make(map[int32]*ServiceWithApps, l)
for i, s := range services {
idList[i] = s.Id
d := domainsMap[s.DomainId]
swa := &ServiceWithApps{Id: s.Id, Name: s.Name, Description: s.Description}
d.Services = append(d.Services, swa)
servicesMap[s.Id] = swa
}
apps, err := model.AppRep.GetApplicationsByServiceId(idList...)
if err != nil {
return nil, err
}
for _, app := range apps {
s := servicesMap[app.ServiceId]
s.Apps = append(s.Apps, &SimpleApp{Id: app.Id,
Name: app.Name,
Type: app.Type,
Description: app.Description,
})
}
return res, nil
} }
func enrichWithTokens(apps ...entity.Application) ([]*AppWithToken, error) { // GetSystemTree godoc
l := len(apps) //
if len(apps) == 0 { // @Tags application
return []*AppWithToken{}, nil // @Summary Метод получения системного дерева
// @Description Возвращает описание взаимосвязей сервисов и приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.DomainWithService
// @Failure 500 {object} apierrors.Error
// @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
//
// @Tags application
// @Summary Создать/обновить приложение
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/create_update_application [POST]
func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.CreateUpdate(ctx, req)
switch {
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service with id %d not found", req.ServiceId),
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.ErrApplicationNotFound):
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
} }
idList := make([]int32, l) }
appMap := make(map[int32]*AppWithToken, l)
enriched := make([]*AppWithToken, l) // Delete godoc
for i, a := range apps { //
idList[i] = a.Id // @Tags application
awt := &AppWithToken{App: a} // @Summary Удалить приложения
appMap[a.Id] = awt // @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений
enriched[i] = awt // @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/delete_applications [POST]
func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest,
"At least one id are required", errors.New("invalid id count"))
} }
tokens, err := model.TokenRep.GetTokensByAppId(idList...)
result, err := c.service.Delete(ctx, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
for _, v := range tokens {
app := appMap[v.AppId]
app.Tokens = append(app.Tokens, v)
}
return enriched, nil
return &domain.DeleteResponse{
Deleted: result,
}, 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.ApplicationWithTokens
// @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.ApplicationWithTokens, 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.ApplicationWithTokens
// @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.ApplicationWithTokens, 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
}
} }
+124 -69
View File
@@ -1,87 +1,142 @@
package controller package controller
import ( import (
"isp-system-service/entity" "context"
"isp-system-service/model" "fmt"
"github.com/integration-system/isp-lib/utils" "isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
) )
/*func GetDomains(list []int32) ([]entity.Domain, error) { type DomainService interface {
res, err := model.DomainRep.GetDomains(list) GetById(ctx context.Context, id int) (*domain.Domain, error)
if err != nil { GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error)
return res, err CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error)
} Delete(ctx context.Context, idList []int) (int, error)
return res, nil
}*/
func GetDomainsBySystemId(md metadata.MD) ([]entity.Domain, error) {
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
if err != nil {
return nil, err
}
return model.DomainRep.GetDomainsBySystemId(int32(sysId))
} }
func CreateUpdateDomain(domain entity.Domain, md metadata.MD) (*entity.Domain, error) { type Domain struct {
existed, err := model.DomainRep.GetDomainByNameAndSystemId(domain.Name, domain.SystemId) service DomainService
if err != nil { }
return nil, err
}
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md) func NewDomain(service DomainService) Domain {
if err != nil { return Domain{
return nil, err service: service,
}
domain.SystemId = int32(sysId)
sys, e := model.SystemRep.GetSystemById(domain.SystemId)
if e != nil {
return nil, err
}
if sys == nil {
return nil, status.Errorf(codes.InvalidArgument, "System with id %d not found", domain.SystemId)
}
if domain.Id == 0 {
if existed != nil {
return nil, status.Errorf(codes.AlreadyExists, "Domain with name %s already exists", domain.Name)
}
domain, e := model.DomainRep.CreateDomain(domain)
return &domain, e
} else {
if existed != nil && existed.Id != domain.Id {
return nil, status.Errorf(codes.AlreadyExists, "Domain with name %s already exists", domain.Name)
}
existed, err = model.DomainRep.GetDomainById(domain.Id)
if err != nil {
return nil, err
}
if existed == nil {
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", domain.Id)
}
domain, e := model.DomainRep.UpdateDomain(domain)
return &domain, e
} }
} }
func GetDomainById(identity Identity) (*entity.Domain, error) { // GetById godoc
domain, err := model.DomainRep.GetDomainById(identity.Id) //
// @Tags domain
// @Summary Получить домен по идентификатору
// @Description Возвращает описание домена по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {object} domain.Domain
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @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, apierrors.New(
codes.NotFound,
domain.ErrCodeDomainNotFound,
fmt.Sprintf("domain with id %d not found", req.Id),
err,
)
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} apierrors.Error
// @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} apierrors.Error
// @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, apierrors.NewBusinessError(
domain.ErrCodeSystemNotFound,
fmt.Sprintf("system with id %d not found", domain.DefaultSystemId),
err,
)
case errors.Is(err, domain.ErrDomainNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeDomainNotFound,
fmt.Sprintf("domain with id %d not found", req.Id),
err,
)
case errors.Is(err, domain.ErrDomainDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeDomainDuplicateName,
fmt.Sprintf("domain with name %s already exists", req.Name),
err,
)
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} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /domain/delete_domains [POST]
func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest,
"At least one id are required", errors.New("invalid id count"))
}
result, err := c.service.Delete(ctx, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if domain == nil {
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", identity.Id)
}
return domain, err
}
func DeleteDomains(list []int32) (DeleteResponse, error) { return &domain.DeleteResponse{
if len(list) == 0 { Deleted: result,
return DeleteResponse{Deleted: 0}, status.Errorf(codes.InvalidArgument, "At least one id are required") }, nil
}
res, err := model.DomainRep.DeleteDomains(list)
return DeleteResponse{Deleted: res}, err
} }
+84
View File
@@ -0,0 +1,84 @@
package controller
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
)
type SecureService interface {
Authenticate(ctx context.Context, token string) (*domain.AuthData, error)
Authorize(ctx context.Context, appId int, endpoint string) (bool, error)
}
type Secure struct {
service SecureService
}
func NewSecure(service SecureService) Secure {
return Secure{
service: service,
}
}
// Authenticate godoc
//
// @Tags secure
// @Summary Метод аутентификации токена
// @Description Проверяет наличие токена в системе,
// @Accept json
// @Produce json
// @Param body body domain.AuthenticateRequest true "Тело запроса"
// @Success 200 {array} domain.AuthenticateResponse
// @Failure 500 {object} apierrors.Error
// @Router /secure/authenticate [POST]
func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest) (*domain.AuthenticateResponse, error) {
result, err := c.service.Authenticate(ctx, req.Token)
switch {
case errors.Is(err, domain.ErrTokenNotFound):
return &domain.AuthenticateResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenNotFound.Error(),
}, nil
case errors.Is(err, domain.ErrTokenExpired):
return &domain.AuthenticateResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenExpired.Error(),
}, nil
case err != nil:
return nil, errors.WithMessage(err, "authenticate")
default:
return &domain.AuthenticateResponse{
Authenticated: true,
AuthData: result,
}, nil
}
}
// Authorize godoc
//
// @Tags secure
// @Summary Метод авторизации приложения
// @Description Проверяет доступ приложения к запрашиваемому ендпоинту
// @Accept json
// @Produce json
// @Param body body domain.AuthorizeRequest true "Тело запрос"
// @Success 200 {array} domain.AuthorizeResponse
// @Failure 500 {object} apierrors.Error
// @Router /secure/authorize [POST]
func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) {
result, err := c.service.Authorize(ctx, req.ApplicationId, req.Endpoint)
switch {
case errors.Is(err, domain.ErrAccessListNotFound):
return &domain.AuthorizeResponse{
Authorized: false,
}, nil
case err != nil:
return nil, errors.WithMessage(err, "authorize")
default:
return &domain.AuthorizeResponse{
Authorized: result,
}, nil
}
}
+144 -57
View File
@@ -1,74 +1,161 @@
package controller package controller
import ( import (
"isp-system-service/entity" "context"
"isp-system-service/model" "fmt"
"isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
func GetService(list []int32) ([]entity.Service, error) { type ServiceService interface {
res, err := model.ServiceRep.GetServices(list) GetById(ctx context.Context, id int) (*domain.Service, error)
if err != nil { GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error)
return res, err 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,
} }
return res, nil
} }
func GetServicesByDomainId(identity Identity) ([]entity.Service, error) { // GetById godoc
return model.ServiceRep.GetServicesByDomainId(identity.Id) //
// @Tags service
// @Summary Получить сервис по идентификатору
// @Description Возвращает описание сервиса по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор сервиса"
// @Success 200 {object} domain.Service
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @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.ErrAppGroupNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service with id %d not found", req.Id),
err,
)
case err != nil:
return nil, err
default:
return result, nil
}
} }
func CreateUpdateService(service entity.Service) (*entity.Service, error) { // Get godoc
existed, err := model.ServiceRep.GetServiceByNameAndDomainId(service.Name, service.DomainId) //
// @Tags service
// @Summary Получить список сервисов
// @Description Возвращает список сервисов по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов сервисов"
// @Success 200 {array} domain.Service
// @Failure 500 {object} apierrors.Error
// @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} apierrors.Error
// @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} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @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, apierrors.NewBusinessError(
domain.ErrCodeDomainNotFound,
fmt.Sprintf("domain with id %d not found", req.DomainId),
err,
)
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service with id %d not found", req.Id),
err,
)
case errors.Is(err, domain.ErrAppGroupDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service with name %s already exists", req.Name),
err,
)
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} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /service/delete_service [POST]
func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest,
"At least one id are required", errors.New("invalid id count"))
}
result, err := c.service.Delete(ctx, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
domain, e := model.DomainRep.GetDomainById(service.DomainId)
if e != nil {
return nil, err
}
if domain == nil {
return nil, status.Errorf(codes.InvalidArgument, "Domain with id %d not found", service.DomainId)
}
if service.Id == 0 {
if existed != nil {
return nil, status.Errorf(codes.AlreadyExists, "Service with name %s already exists", service.Name)
}
service, e := model.ServiceRep.CreateService(service)
return &service, e
} else {
if existed != nil && existed.Id != service.Id {
return nil, status.Errorf(codes.AlreadyExists, "Service with name %s already exists", service.Name)
}
existed, err = model.ServiceRep.GetServiceById(service.Id)
if err != nil {
return nil, err
}
if existed == nil {
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", service.Id)
}
service, e := model.ServiceRep.UpdateService(service)
return &service, e
}
}
func GetServiceById(identity Identity) (*entity.Service, error) { return &domain.DeleteResponse{
service, err := model.ServiceRep.GetServiceById(identity.Id) Deleted: result,
if err != nil { }, nil
return nil, err
}
if service == nil {
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", identity.Id)
}
return service, err
}
func DeleteService(list []int32) (DeleteResponse, error) {
if len(list) == 0 {
return DeleteResponse{Deleted: 0}, status.Error(codes.InvalidArgument, "At least one id are required")
}
res, err := model.ServiceRep.DeleteServices(list)
return DeleteResponse{Deleted: res}, err
} }
-49
View File
@@ -1,49 +0,0 @@
package controller
import (
"isp-system-service/entity"
)
type DeleteResponse struct {
Deleted int
}
type Identity struct {
Id int32 `json:"id" valid:"required~Required"`
}
type AppWithToken struct {
App entity.Application
Tokens []entity.Token
}
type SimpleApp struct {
Id int32
Name string
Description string
Type string
Tokens []entity.Token
}
type ServiceWithApps struct {
Id int32
Name string
Description string
Apps []*SimpleApp
}
type DomainWithServices struct {
Id int32
Name string
Description string
Services []*ServiceWithApps
}
type RevokeTokensRequest struct {
AppId int32 `valid:"required~Required"`
Tokens []string
}
type CreateTokenRequest struct {
AppId int32 `valid:"required~Required"`
ExpireTimeMs int64
}
-65
View File
@@ -1,65 +0,0 @@
package controller
import (
"fmt"
"isp-system-service/entity"
"isp-system-service/model"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func GetSystems(list []int32) ([]entity.System, error) {
res, err := model.SystemRep.GetSystems(list)
if err != nil {
return res, err
}
return res, nil
}
func CreateUpdateSystem(system entity.System) (*entity.System, error) {
existed, err := model.SystemRep.GetSystemByName(system.Name)
if err != nil {
return nil, err
}
if system.Id == 0 {
if existed != nil {
return nil, status.Errorf(codes.AlreadyExists, "System with name %s already exists", system.Name)
}
sys, e := model.SystemRep.CreateSystem(system)
return &sys, e
} else {
if existed != nil && existed.Id != system.Id {
return nil, status.Errorf(codes.AlreadyExists, "System with name %s already exists", system.Name)
}
existed, err = model.SystemRep.GetSystemById(system.Id)
if err != nil {
return nil, err
}
if existed == nil {
return nil, status.Error(codes.NotFound, fmt.Sprintf("System with id %d not found", system.Id))
}
sys, e := model.SystemRep.UpdateSystem(system)
return &sys, e
}
}
func GetSystemById(identity Identity) (*entity.System, error) {
sys, err := model.SystemRep.GetSystemById(identity.Id)
if err != nil {
return nil, err
}
if sys == nil {
return nil, status.Error(codes.NotFound, fmt.Sprintf("System with id %d not found", identity.Id))
}
return sys, err
}
func DeleteSystems(list []int32) (DeleteResponse, error) {
if len(list) == 0 {
return DeleteResponse{}, status.Error(codes.InvalidArgument, "At least one id are required")
}
res, err := model.SystemRep.DeleteSystems(list)
return DeleteResponse{Deleted: res}, err
}
+100 -190
View File
@@ -1,206 +1,116 @@
package controller package controller
import ( import (
"time" "context"
"isp-system-service/conf"
"isp-system-service/entity"
"isp-system-service/model"
"fmt" "fmt"
"github.com/go-redis/redis"
"github.com/integration-system/isp-lib/config" "isp-system-service/domain"
"github.com/integration-system/isp-lib/redis"
"github.com/integration-system/isp-lib/token-gen" "github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
const ( type TokenService interface {
SystemIdentityFieldInDb = "1" GetByAppId(ctx context.Context, appId int) ([]domain.Token, error)
DomainIdentityFieldInDb = "2" Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error)
ServiceIdentityFieldInDb = "3" Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error)
ApplicationIdentityFieldInDb = "4" RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error)
)
var (
generator = tg.NewGenerator(tg.DefaultAlphabet)
)
type BoolResponse struct {
Ok bool
} }
func CreateToken(req CreateTokenRequest) (*AppWithToken, error) { type Token struct {
m, err, app := GetIdMap(req.AppId) service TokenService
if err != nil { }
func NewToken(service TokenService) Token {
return Token{
service: service,
}
}
// GetByAppId godoc
//
// @Tags token
// @Summary Получить токены по идентификатору приложения
// @Description Возвращает список токенов, привязанных к приложению
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {array} entity.Token
// @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) {
return c.service.GetByAppId(ctx, req.Id)
}
// Create godoc
//
// @Tags token
// @Summary Создать токен
// @Description Создает токен и привязывает его к приложению
// @Accept json
// @Produce json
// @Param body body domain.TokenCreateRequest true "Объект создания токена"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 500 {object} apierrors.Error
// @Router /token/create_token [POST]
func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.Create(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.AppId),
err,
)
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service for app_id id %d not found", req.AppId),
err,
)
case errors.Is(err, domain.ErrDomainNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeDomainNotFound,
fmt.Sprintf("domain for app_id id %d not found", req.AppId),
err,
)
case err != nil:
return nil, err return nil, err
default:
return result, nil
} }
cfg := config.GetRemote().(*conf.RemoteConfig)
var id string
var existed = true
for existed {
id = generator.Next(tg.DefaultTokenLength)
t, err := model.TokenRep.GetTokenById(id)
if err != nil {
return nil, err
}
existed = t != nil
}
expTime := req.ExpireTimeMs
if expTime == 0 {
expTime = cfg.DefaultTokenExpireTime
}
token := entity.Token{
Token: id,
ExpireTime: expTime,
AppId: req.AppId,
CreatedAt: time.Now(),
}
c := rd.GetClient()
err = SetIdentityMapForToken(token, m)
if err != nil {
return nil, err
}
token, err = model.TokenRep.SaveToken(token)
if err != nil {
c.Del(token.Token)
return nil, err
}
arr, err := enrichWithTokens(*app)
if err != nil {
return nil, err
}
return arr[0], nil
} }
func RevokeTokens(req RevokeTokensRequest) (*AppWithToken, error) { // Revoke godoc
app, err := model.AppRep.GetApplicationById(req.AppId) //
if err != nil { // @Tags token
return nil, err // @Summary Отозвать токены
} // @Description Отвязывает токены от приложений и удаляет их
_, err = revokeTokens(req.Tokens, &model.TokenRep) // @Accept json
if err != nil { // @Produce json
return nil, err // @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов"
} // @Success 200 {object} domain.ApplicationWithTokens
res, err := enrichWithTokens(*app) // @Failure 500 {object} apierrors.Error
if err != nil { // @Router /token/revoke_tokens [POST]
return nil, err func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
} return c.service.Revoke(ctx, req)
return res[0], nil
} }
func RevokeTokensForApp(identity Identity) (*DeleteResponse, error) { // RevokeForApp godoc
return revokeTokensForApp(identity, &model.TokenRep) //
} // @Tags token
// @Summary Отозвать токены для приложения
func GetTokensByAppId(identity Identity) ([]entity.Token, error) { // @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения
return model.TokenRep.GetTokensByAppId(identity.Id) // @Accept json
} // @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
func SetIdentityMapForTokenV2(token string, expireTime int64, idMap map[string]interface{}) error { // @Success 200 {object} domain.DeleteResponse
c := rd.GetClient() // @Failure 500 {object} apierrors.Error
cfg := config.Get().(*conf.Configuration) // @Router /token/revoke_tokens_for_app [POST]
_, e := c.UseDbTx(rd.ApplicationTokenDb, func(p redis.Pipeliner) error { func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) {
t := fmt.Sprintf("%s|%s", token, cfg.InstanceUuid) return c.service.RevokeByAppId(ctx, req.Id)
stat := p.HMSet(t, idMap)
err := stat.Err()
if err != nil {
return err
}
if expireTime > 0 {
err = p.Expire(token, time.Duration(expireTime)*time.Millisecond).Err()
}
return err
})
return e
}
func SetIdentityMapForToken(token entity.Token, idMap map[string]interface{}) error {
return SetIdentityMapForTokenV2(token.Token, token.ExpireTime, idMap)
}
func GetIdMap(appId int32) (map[string]interface{}, error, *entity.Application) {
app, err := model.AppRep.GetApplicationById(appId)
if err != nil {
return nil, err, nil
}
if app == nil {
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", appId), nil
}
service, err := model.ServiceRep.GetServiceById(app.ServiceId)
if err != nil {
return nil, err, app
}
if service == nil {
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", app.ServiceId), app
}
domain, err := model.DomainRep.GetDomainById(service.DomainId)
if err != nil {
return nil, err, app
}
if domain == nil {
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", service.DomainId), app
}
system, err := model.SystemRep.GetSystemById(domain.SystemId)
if err != nil {
return nil, err, app
}
if system == nil {
return nil, status.Errorf(codes.NotFound, "System with id %d not found", domain.SystemId), app
}
return map[string]interface{}{
SystemIdentityFieldInDb: system.Id,
DomainIdentityFieldInDb: domain.Id,
ServiceIdentityFieldInDb: service.Id,
ApplicationIdentityFieldInDb: app.Id,
}, nil, app
}
func revokeTokensForApp(identity Identity, tokenRep *model.TokenRepository) (*DeleteResponse, error) {
tokens, err := GetTokensByAppId(identity)
if err != nil {
return nil, err
}
l := len(tokens)
if l == 0 {
return &DeleteResponse{0}, nil
}
tokenIdList := make([]string, l)
for i, t := range tokens {
tokenIdList[i] = t.Token
}
return revokeTokens(tokenIdList, tokenRep)
}
func revokeTokens(tokens []string, tokenRep *model.TokenRepository) (*DeleteResponse, error) {
var count = 0
if len(tokens) == 0 {
return &DeleteResponse{0}, nil
}
c := rd.GetClient()
_, e := c.UseDbTx(rd.ApplicationTokenDb, func(p redis.Pipeliner) error {
deleted, err := tokenRep.DeleteTokens(tokens)
count = deleted
if err != nil {
return err
}
res := p.Del(tokens...)
return res.Err()
})
if e != nil {
return nil, e
}
return &DeleteResponse{count}, nil
} }
+1363
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
package domain
type AccessListSetOneRequest struct {
AppId int `validate:"required"`
Method string `validate:"required"`
Value bool
}
type AccessListSetOneResponse struct {
Count int
}
type AccessListSetListRequest struct {
AppId int `validate:"required"`
RemoveOld bool
Methods []MethodInfo
}
type MethodInfo struct {
Method string
Value bool
}
+26
View File
@@ -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"`
}
+56
View File
@@ -0,0 +1,56 @@
package domain
import (
"time"
)
const (
ApplicationSystemType = "SYSTEM"
ApplicationMobileType = "MOBILE"
)
type Application struct {
Id int
Name string
Description string
ServiceId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
}
type ApplicationCreateUpdateRequest struct {
Id int
Name string `validate:"required"`
Description string
ServiceId int `validate:"required"`
Type string `validate:"required,oneof=SYSTEM MOBILE"`
}
type ApplicationWithTokens struct {
App Application
Tokens []Token
}
type ApplicationSimple struct {
Id int
Name string
Description string
Type string
Tokens []Token
}
type CreateApplicationRequest struct {
Id int `validate:"required"`
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
}
+11
View File
@@ -0,0 +1,11 @@
package domain
type (
Identity struct {
Id int `validate:"required"`
}
DeleteResponse struct {
Deleted int
}
)
+27
View File
@@ -0,0 +1,27 @@
package domain
import (
"time"
)
type DomainCreateUpdateRequest struct {
Id int
Name string `validate:"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
}
+39
View File
@@ -0,0 +1,39 @@
package domain
import (
"github.com/pkg/errors"
)
const (
ErrCodeInvalidRequest = 600
ErrCodeApplicationNotFound = 602
ErrCodeApplicationDuplicateName = 603
ErrCodeApplicationDuplicateId = 604
ErrCodeAppGroupNotFound = 605
ErrCodeAppGroupDuplicateName = 606
ErrCodeSystemNotFound = 607
ErrCodeDomainNotFound = 608
ErrCodeDomainDuplicateName = 609
)
var (
ErrDomainNotFound = errors.New("domain not found")
ErrDomainDuplicateName = errors.New("domain name already exist")
ErrAppGroupNotFound = errors.New("application group not found")
ErrAppGroupDuplicateName = errors.New("application group name already exist")
ErrSystemNotFound = errors.New("system not found")
ErrApplicationNotFound = errors.New("application not found")
ErrApplicationDuplicateName = errors.New("application name already exist")
ErrApplicationDuplicateId = errors.New("application id already exist")
ErrTokenNotFound = errors.New("token not found")
ErrTokenExpired = errors.New("token is expired")
ErrAccessListNotFound = errors.New("access_list not found")
)
+27
View File
@@ -0,0 +1,27 @@
package domain
type AuthenticateRequest struct {
Token string `validate:"required"`
}
type AuthenticateResponse struct {
Authenticated bool
ErrorReason string
AuthData *AuthData
}
type AuthData struct {
SystemId int
DomainId int
ServiceId int
ApplicationId int
}
type AuthorizeRequest struct {
ApplicationId int `validate:"required"`
Endpoint string `validate:"required"`
}
type AuthorizeResponse struct {
Authorized bool
}
+28
View File
@@ -0,0 +1,28 @@
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 `validate:"required"`
Description string
DomainId int `validate:"required"`
}
type ServiceWithApps struct {
Id int
Name string
Description string
Apps []*ApplicationSimple
}
+5
View File
@@ -0,0 +1,5 @@
package domain
const (
DefaultSystemId = 1
)
+22
View File
@@ -0,0 +1,22 @@
package domain
import (
"time"
)
type Token struct {
Token string
AppId int
ExpireTime int
CreatedAt time.Time
}
type TokenRevokeRequest struct {
AppId int `validate:"required"`
Tokens []string
}
type TokenCreateRequest struct {
AppId int `validate:"required"`
ExpireTimeMs int `validate:"required"`
}
+7
View File
@@ -0,0 +1,7 @@
package entity
type AccessList struct {
AppId int
Method string
Value bool
}
+15
View File
@@ -0,0 +1,15 @@
package entity
import (
"database/sql"
"time"
)
type AppGroup struct {
Id int
Name string
Description sql.NullString
DomainId int
CreatedAt time.Time
UpdatedAt time.Time
}
+16
View File
@@ -0,0 +1,16 @@
package entity
import (
"database/sql"
"time"
)
type Application struct {
Id int
Name string
Description sql.NullString
ApplicationGroupId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
}
+14
View File
@@ -0,0 +1,14 @@
package entity
import (
"time"
)
type Domain struct {
Id int
Name string
Description *string
SystemId int
CreatedAt time.Time
UpdatedAt time.Time
}
-60
View File
@@ -1,60 +0,0 @@
package entity
import "time"
const (
RootAdminApplicationId = 1
)
const (
AppTypeSystem = "SYSTEM"
AppTypeMobile = "MOBILE"
)
type System struct {
TableName string `sql:"system_service.system" json:"-"`
Id int32
Name string `valid:"required~Required"`
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
type Domain struct {
TableName string `sql:"system_service.domain" json:"-"`
Id int32
Name string `valid:"required~Required"`
Description string
SystemId int32
CreatedAt time.Time
UpdatedAt time.Time
}
type Service struct {
TableName string `sql:"system_service.service" json:"-"`
Id int32
Name string `valid:"required~Required"`
Description string
DomainId int32 `valid:"required~Required"`
CreatedAt time.Time
UpdatedAt time.Time
}
type Application struct {
TableName string `sql:"system_service.application" json:"-"`
Id int32
Name string `valid:"required~Required"`
Description string
Type string `valid:"required~Required,in(SYSTEM|MOBILE)"`
ServiceId int32 `valid:"required~Required"`
CreatedAt time.Time
UpdatedAt time.Time
}
type Token struct {
TableName string `sql:"system_service.token" json:"-"`
Token string `valid:"required~Required" sql:"pk:token"`
AppId int32 `valid:"required~Required"`
ExpireTime int64
CreatedAt time.Time
}
+21
View File
@@ -0,0 +1,21 @@
package entity
import (
"time"
)
type Token struct {
Token string
AppId int
ExpireTime int
CreatedAt time.Time
}
type AuthData struct {
SystemId int
DomainId int
ApplicationGroupId int
AppId int
ExpireTime int
CreatedAt time.Time
}
+82
View File
@@ -0,0 +1,82 @@
module isp-system-service
go 1.24
require (
github.com/Masterminds/squirrel v1.5.4
github.com/jackc/pgx/v5 v5.7.4
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.10.0
github.com/txix-open/isp-kit v1.46.0
github.com/txix-open/jsonschema v1.2.0
google.golang.org/grpc v1.72.0
)
require (
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.13 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/getsentry/sentry-go v0.31.1 // indirect
github.com/go-faker/faker/v4 v4.6.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jmoiron/sqlx v1.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/pressly/goose/v3 v3.24.2 // indirect
github.com/prometheus/client_golang v1.21.1 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.63.0 // indirect
github.com/prometheus/procfs v0.16.0 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/etp/v4 v4.0.1 // indirect
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/otel v1.35.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 // indirect
go.opentelemetry.io/otel/metric v1.35.0 // indirect
go.opentelemetry.io/otel/sdk v1.35.0 // indirect
go.opentelemetry.io/otel/trace v1.35.0 // indirect
go.opentelemetry.io/proto/otlp v1.5.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/crypto v0.36.0 // indirect
golang.org/x/net v0.38.0 // indirect
golang.org/x/sync v0.12.0 // indirect
golang.org/x/sys v0.31.0 // indirect
golang.org/x/text v0.23.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250324211829-b45e905df463 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+225
View File
@@ -0,0 +1,225 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/getsentry/sentry-go v0.31.1 h1:ELVc0h7gwyhnXHDouXkhqTFSO5oslsRDk0++eyE0KJ4=
github.com/getsentry/sentry-go v0.31.1/go.mod h1:CYNcMMz73YigoHljQRG+qPF+eMq8gG72XcGN/p71BAY=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/go-faker/faker/v4 v4.6.0 h1:6aOPzNptRiDwD14HuAnEtlTa+D1IfFuEHO8+vEFwjTs=
github.com/go-faker/faker/v4 v4.6.0/go.mod h1:ZmrHuVtTTm2Em9e0Du6CJ9CADaLEzGXW62z1YqFH0m0=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-sql-driver/mysql v1.9.1 h1:FrjNGn/BsJQjVRuSa8CBrM5BWA9BWoXXat3KrtSb/iI=
github.com/go-sql-driver/mysql v1.9.1/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.24.2 h1:c/ie0Gm8rnIVKvnDQ/scHErv46jrDv9b4I0WRcFJzYU=
github.com/pressly/goose/v3 v3.24.2/go.mod h1:kjefwFB0eR4w30Td2Gj2Mznyw94vSP+2jJYkOVNbD1k=
github.com/prometheus/client_golang v1.21.1 h1:DOvXXTqVzvkIewV/CDPFdejpMCGeMcbGCQ8YOmu+Ibk=
github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
github.com/prometheus/common v0.63.0 h1:YR/EIY1o3mEFP/kZCD7iDMnLPlGyuU2Gb3HIcXnA98k=
github.com/prometheus/common v0.63.0/go.mod h1:VVFF/fBIoToEnWRVkYoXEkq3R3paCoxG9PXP74SnV18=
github.com/prometheus/procfs v0.16.0 h1:xh6oHhKwnOJKMYiYBDWmkHqQPyiY40sny36Cmx2bbsM=
github.com/prometheus/procfs v0.16.0/go.mod h1:8veyXUu3nGP7oaCxhX6yeaM5u4stL2FeMXnCqhDthZg=
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA=
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
github.com/txix-open/grmq v1.7.0 h1:nwenrlxEjXpK0EBCa/WbIxK+y0mF2pZxNKbheFjQVsI=
github.com/txix-open/grmq v1.7.0/go.mod h1:DAfbV4jLyxQBLG8OYJVy8kCbhucdlu/C/wl+nUDc9p8=
github.com/txix-open/isp-kit v1.46.0 h1:Rqw5X+501vEwMv6oGvC6sYU1++1XiTvxt6Ja/CD7lRw=
github.com/txix-open/isp-kit v1.46.0/go.mod h1:tWz/RGhRHx+JQZa5j1srR9kzL5YkIed3350SQ+FV1Wc=
github.com/txix-open/jsonschema v1.2.0 h1:B8TrdSsPhDvYv67oi/LVqf7/+PuqFlMsNwUzGeHfl1s=
github.com/txix-open/jsonschema v1.2.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 h1:Z0Sqf+U+Sc6hfIXtRCIZlbJprkCjwMFbS4ZbEPQ44To=
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99/go.mod h1:pA0NYmhL0uEkkxj55S+S7MZU4e2QIt46x9XSrzrWc3c=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.60.0 h1:0tY123n7CdWMem7MOVdKOt0YfshufLCwfE5Bob+hQuM=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.60.0/go.mod h1:CosX/aS4eHnG9D7nESYpV753l4j9q5j3SL/PUYd2lR8=
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 h1:1fTNlAIJZGWLP5FVu0fikVry1IsiUnXjf7QFvoNN3Xw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 h1:xJ2qHD0C1BeYVTLLR9sX12+Qb95kfeD/byKj6Ky1pXg=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0/go.mod h1:u5BF1xyjstDowA1R5QAO9JHzqK+ublenEW/dyqTjBVk=
go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=
go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=
go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=
go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg=
go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=
go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=
go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4=
go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
google.golang.org/genproto/googleapis/api v0.0.0-20250324211829-b45e905df463 h1:hE3bRWtU6uceqlh4fhrSnUyjKHMKB9KrTLLG+bc0ddM=
google.golang.org/genproto/googleapis/api v0.0.0-20250324211829-b45e905df463/go.mod h1:U90ffi8eUL9MwPcrJylN5+Mk2v3vuPDptd5yyNUiRR8=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 h1:e0AIkUUhxyBKh6ssZNrAMeqhA7RKUj42346d1y02i2g=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
google.golang.org/grpc v1.72.0 h1:S7UkcVa60b5AAQTaO6ZKamFp1zMZSU0fGDK2WZLbBnM=
google.golang.org/grpc v1.72.0/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.9.1 h1:V/Z1solwAVmMW1yttq3nDdZPJqV1rM05Ccq6KMSZ34g=
modernc.org/memory v1.9.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.36.2 h1:vjcSazuoFve9Wm0IVNHgmJECoOXLZM1KfMXbcX2axHA=
modernc.org/sqlite v1.36.2/go.mod h1:ADySlx7K4FdY5MaJcEv86hTJ0PjedAloTUuif0YS3ws=
-106
View File
@@ -1,106 +0,0 @@
package helper
import (
"isp-system-service/controller"
"isp-system-service/entity"
"google.golang.org/grpc/metadata"
)
type SystemHandler struct {
GetSystems func(list []int32) ([]entity.System, error) `method:"get_systems" group:"system" inner:"true"`
CreateUpdateSystem func(system entity.System) (*entity.System, error) `method:"create_update_system" group:"system" inner:"true"`
GetSystemById func(identity controller.Identity) (*entity.System, error) `method:"get_system_by_id" group:"system" inner:"true"`
DeleteSystems func(list []int32) (controller.DeleteResponse, error) `method:"delete_systems" group:"system" inner:"true"`
}
type DomainHandler struct {
//GetDomains func(list []int32) ([]entity.Domain, error) `method:"get_domains" group:"domain" inner:"true"`
GetDomainsBySystemId func(md metadata.MD) ([]entity.Domain, error) `method:"get_domains_by_system_id" group:"domain" inner:"true"`
CreateUpdateDomain func(domain entity.Domain, md metadata.MD) (*entity.Domain, error) `method:"create_update_domain" group:"domain" inner:"true"`
GetDomainById func(identity controller.Identity) (*entity.Domain, error) `method:"get_domain_by_id" group:"domain" inner:"true"`
DeleteDomains func(list []int32) (controller.DeleteResponse, error) `method:"delete_domains" group:"domain" inner:"true"`
}
type ServiceHandler struct {
GetService func(list []int32) ([]entity.Service, error) `method:"get_service" group:"service" inner:"true"`
GetServicesByDomainId func(identity controller.Identity) ([]entity.Service, error) `method:"get_services_by_domain_id" group:"service" inner:"true"`
CreateUpdateService func(service entity.Service) (*entity.Service, error) `method:"create_update_service" group:"service" inner:"true"`
GetServiceById func(identity controller.Identity) (*entity.Service, error) `method:"get_service_by_id" group:"service" inner:"true"`
DeleteService func(list []int32) (controller.DeleteResponse, error) `method:"delete_service" group:"service" inner:"true"`
}
type ApplicationHandler struct {
GetApplications func(list []int32) ([]*controller.AppWithToken, error) `method:"get_applications" group:"application" inner:"true"`
GetApplicationsByServiceId func(identity controller.Identity) ([]*controller.AppWithToken, error) `method:"get_applications_by_service_id" group:"application" inner:"true"`
CreateUpdateApplication func(application entity.Application) (*controller.AppWithToken, error) `method:"create_update_application" group:"application" inner:"true"`
GetApplicationById func(identity controller.Identity) (*controller.AppWithToken, error) `method:"get_application_by_id" group:"application" inner:"true"`
DeleteApplications func(list []int32) (controller.DeleteResponse, error) `method:"delete_applications" group:"application" inner:"true"`
GetSystemTree func(md metadata.MD) ([]*controller.DomainWithServices, error) `method:"get_system_tree" group:"application" inner:"true"`
}
type TokenHandler struct {
CreateToken func(req controller.CreateTokenRequest) (*controller.AppWithToken, error) `method:"create_token" group:"token" inner:"true"`
RevokeTokens func(request controller.RevokeTokensRequest) (*controller.AppWithToken, error) `method:"revoke_tokens" group:"token" inner:"true"`
RevokeTokensForApp func(identity controller.Identity) (*controller.DeleteResponse, error) `method:"revoke_tokens_for_app" group:"token" inner:"true"`
GetTokensByAppId func(identity controller.Identity) ([]entity.Token, error) `method:"get_tokens_by_app_id" group:"token" inner:"true"`
}
func GetSystemHandler() *SystemHandler {
return &SystemHandler{
GetSystems: controller.GetSystems,
CreateUpdateSystem: controller.CreateUpdateSystem,
GetSystemById: controller.GetSystemById,
DeleteSystems: controller.DeleteSystems,
}
}
func GetDomainHandler() *DomainHandler {
return &DomainHandler{
//GetDomains: controller.GetDomains,
GetDomainsBySystemId: controller.GetDomainsBySystemId,
CreateUpdateDomain: controller.CreateUpdateDomain,
GetDomainById: controller.GetDomainById,
DeleteDomains: controller.DeleteDomains,
}
}
func GetServiceHandler() *ServiceHandler {
return &ServiceHandler{
GetService: controller.GetService,
GetServicesByDomainId: controller.GetServicesByDomainId,
CreateUpdateService: controller.CreateUpdateService,
GetServiceById: controller.GetServiceById,
DeleteService: controller.DeleteService,
}
}
func GetApplicationHandler() *ApplicationHandler {
return &ApplicationHandler{
GetApplications: controller.GetApplications,
GetApplicationsByServiceId: controller.GetApplicationsByServiceId,
CreateUpdateApplication: controller.CreateUpdateApplication,
GetApplicationById: controller.GetApplicationById,
DeleteApplications: controller.DeleteApplications,
GetSystemTree: controller.GetSystemTree,
}
}
func GetTokenHandler() *TokenHandler {
return &TokenHandler{
CreateToken: controller.CreateToken,
GetTokensByAppId: controller.GetTokensByAppId,
RevokeTokens: controller.RevokeTokens,
RevokeTokensForApp: controller.RevokeTokensForApp,
}
}
func GetAllHandlers() []interface{} {
return []interface{}{
GetSystemHandler(),
GetDomainHandler(),
GetServiceHandler(),
GetApplicationHandler(),
GetTokenHandler(),
}
}
+32 -91
View File
@@ -1,107 +1,48 @@
package main package main
import ( import (
"os" "github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/shutdown"
"isp-system-service/assembly"
"isp-system-service/conf" "isp-system-service/conf"
"isp-system-service/helper" "isp-system-service/routes"
"isp-system-service/model"
_ "isp-system-service/migrations"
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/database"
"github.com/integration-system/isp-lib/metric"
"github.com/integration-system/isp-lib/socket"
"context"
"github.com/integration-system/isp-lib/bootstrap"
"github.com/integration-system/isp-lib/redis"
) )
var ( var (
version = "0.1.0" version = "1.0.0"
date = "undefined"
) )
// @title isp-system-service
// @version 1.0.0
// @description Сервис управления реестром внешних приложений и токенами аутентификации
// @license.name GNU GPL v3.0
// @host localhost:9000
// @BasePath /api/system
//go:generate swag init --parseDependency
//go:generate rm -f docs/swagger.json
func main() { func main() {
bootstrap. boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors())
ServiceBootstrap(&conf.Configuration{}, &conf.RemoteConfig{}). app := boot.App
OnLocalConfigLoad(onLocalConfigLoad). logger := app.Logger()
SocketConfiguration(socketConfiguration).
DeclareMe(routesData).
OnRemoteConfigReceive(onRemoteConfigReceive).
OnShutdown(onShutdown).
Run()
}
/*func ensureRootToken() { assembly, err := assembly.New(boot)
tokens, err := model.TokenRep.GetTokensByAppId(entity.RootAdminApplicationId)
if err != nil { if err != nil {
logger.Error(err) logger.Fatal(app.Context(), err)
return
} }
if len(tokens) > 0 { app.AddRunners(assembly.Runners()...)
m, err, _ := controller.GetIdMap(entity.RootAdminApplicationId) app.AddClosers(assembly.Closers()...)
if err != nil {
logger.Error(err)
return
}
for _, token := range tokens {
err = controller.SetIdentityMapForToken(token, m)
if err != nil {
logger.Error(err)
continue
}
}
}
}*/
func socketConfiguration(cfg interface{}) socket.SocketConfiguration { shutdown.On(func() {
appConfig := cfg.(*conf.Configuration) logger.Info(app.Context(), "starting shutdown")
return socket.SocketConfiguration{ app.Shutdown()
Host: appConfig.ConfigServiceAddress.IP, logger.Info(app.Context(), "shutdown completed")
Port: appConfig.ConfigServiceAddress.Port, })
Secure: false,
UrlParams: map[string]string{ err = app.Run()
"module_name": appConfig.ModuleName, if err != nil {
"instance_uuid": appConfig.InstanceUuid, boot.Fatal(err)
},
}
}
func onShutdown(_ context.Context, _ os.Signal) {
backend.StopGrpcServer()
database.Close()
}
func onRemoteConfigReceive(remoteConfig, oldConfig *conf.RemoteConfig) {
if remoteConfig.RedisAddress.GetAddress() != oldConfig.RedisAddress.GetAddress() {
rd.InitClient(rd.RedisConfiguration{
Address: remoteConfig.RedisAddress,
DefaultDB: int(rd.ApplicationTokenDb),
})
}
database.InitDb(remoteConfig.DB)
model.InitDbManager(database.GetDBManager())
metric.InitCollectors(remoteConfig.Metrics, oldConfig.Metrics)
metric.InitHttpServer(remoteConfig.Metrics)
//ensureRootToken()
}
func onLocalConfigLoad(cfg *conf.Configuration) {
handlers := helper.GetAllHandlers()
service := backend.GetDefaultService(cfg.ModuleName, handlers...)
backend.StartBackendGrpcServer(cfg.GrpcInnerAddress, service)
}
func routesData(localConfig interface{}) bootstrap.ModuleInfo {
cfg := localConfig.(*conf.Configuration)
return bootstrap.ModuleInfo{
ModuleName: cfg.ModuleName,
ModuleVersion: version,
GrpcOuterAddress: cfg.GrpcOuterAddress,
Handlers: helper.GetAllHandlers(),
} }
} }
@@ -0,0 +1,10 @@
-- +goose Up
CREATE TABLE access_list
(
app_id INT,
method VARCHAR(255),
value BOOLEAN,
PRIMARY KEY (app_id, method),
CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE
);
-- +goose Down
+1 -1
View File
@@ -1,6 +1,6 @@
-- +goose Up -- +goose Up
INSERT INTO system (id, name) VALUES (1, 'rootSystem'); INSERT INTO system (id, name) VALUES (1, 'rootSystem');
SELECT setval('system_service.system_id_seq' :: regclass, 1); SELECT setval(concat(current_schema(), '.system_id_seq') :: regclass, 1);
-- +goose Down -- +goose Down
DELETE FROM system DELETE FROM system
-126
View File
@@ -1,126 +0,0 @@
package migrations
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/integration-system/isp-lib/config"
"github.com/integration-system/isp-lib/database"
"github.com/pressly/goose"
"io/ioutil"
"isp-system-service/conf"
"isp-system-service/controller"
path2 "path"
)
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(Up, Down)
}
func Up(tx *sql.Tx) error {
path := path2.Join(database.ResolveMigrationsDirectrory(), initFile)
bytes, err := ioutil.ReadFile(path)
if err != nil {
return err
}
var list []controller.DomainWithServices
if err := json.Unmarshal(bytes, &list); err != nil {
return err
}
schema := config.GetRemote().(*conf.RemoteConfig).DB.Schema
lastDomainId := int64(0)
lastServiceId := int64(0)
lastAppId := int64(0)
for _, domain := range list {
domainId := int64(0)
if domainId, err = insertNode(tx, insertDomain, true, schema, domain.Id, domain.Name, domain.Description, 1); err != nil {
return err
}
if domainId > lastDomainId {
lastDomainId = domainId
}
for _, service := range domain.Services {
serviceId := int64(0)
if serviceId, err = insertNode(tx, insertService, true, schema, service.Id, service.Name, service.Description, domainId); err != nil {
return err
}
if serviceId > lastServiceId {
lastServiceId = serviceId
}
for _, app := range service.Apps {
appId := int64(0)
if appId, err = insertNode(tx, insertApp, true, schema, app.Id, app.Name, app.Description, serviceId, app.Type); err != nil {
return err
}
if appId > lastAppId {
lastAppId = appId
}
for _, t := range app.Tokens {
if _, err := insertNode(tx, insertToken, false, schema, t.Token, appId, t.ExpireTime); err != nil {
return err
} else {
idMap := map[string]interface{}{
controller.SystemIdentityFieldInDb: 1,
controller.DomainIdentityFieldInDb: domainId,
controller.ServiceIdentityFieldInDb: serviceId,
controller.ApplicationIdentityFieldInDb: appId,
}
if err := controller.SetIdentityMapForTokenV2(t.Token, t.ExpireTime, idMap); err != nil {
return err
}
}
}
}
}
}
if err := setSeq(tx, schema, "domain", lastDomainId); err != nil {
return err
} else if err := setSeq(tx, schema, "service", lastServiceId); err != nil {
return err
} else if err := setSeq(tx, schema, "application", lastAppId); err != nil {
return err
}
return nil
}
func Down(tx *sql.Tx) error {
return nil
}
func insertNode(tx *sql.Tx, query string, scan bool, args ...interface{}) (int64, error) {
var id int64
var err error
query = fmt.Sprintf(query, args...)
row := tx.QueryRow(query)
if scan {
row.Scan(&id)
}
if err != nil {
return 0, err
}
return id, nil
}
func setSeq(tx *sql.Tx, schema, table string, value int64) error {
q := fmt.Sprintf(setSeqQuery, schema, table, value)
_, err := tx.Exec(q)
return err
}
@@ -0,0 +1,7 @@
-- +goose Up
UPDATE access_list SET value = false WHERE value is null;
ALTER TABLE access_list
ALTER COLUMN value SET NOT NULL;
-- +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');
-90
View File
@@ -1,90 +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
}
]
}
]
}
]
},
{
"id": 2,
"name": "citymodule",
"description": "",
"services": [
{
"id": 2,
"name": "citymodule_service",
"description": "",
"apps": [
{
"id": 2,
"name": "cityservice",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_token }}",
"expireTime": -1
}
]
},
{
"id": 3,
"name": "citymodule",
"description": "",
"type": "MOBILE",
"tokens": [
{
"token": "{{ isp_service_citymodule_token }}",
"expireTime": -1
}
]
},
{
"id": 4,
"name": "cityservice_operator_ui",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_operator_ui_token }}",
"expireTime": -1
}
]
},
{
"id": 5,
"name": "cityservice_web_portal",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_web_portal_token }}",
"expireTime": -1
}
]
}
]
}
]
}
]
-69
View File
@@ -1,69 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
var (
emptyApplication = &entity.Application{}
AppRep AppRepository
)
type AppRepository struct {
DB orm.DB
}
func (ar *AppRepository) GetApplications(list []int32) ([]entity.Application, error) {
var res []entity.Application
q := ar.DB.Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (ar *AppRepository) GetApplicationsByServiceId(serviceId ...int32) ([]entity.Application, error) {
var res []entity.Application
err := ar.DB.Model(&res).Where("service_id IN (?)", pg.In(serviceId)).Order("created_at DESC").Select()
return res, err
}
func (ar *AppRepository) CreateApplication(service entity.Application) (entity.Application, error) {
_, err := ar.DB.Model(&service).Insert()
return service, err
}
func (ar *AppRepository) GetApplicationByNameAndServiceId(name string, serviceId int32) (*entity.Application, error) {
app := new(entity.Application)
err := ar.DB.Model(app).Where("name = ? AND service_id = ?", name, serviceId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return app, err
}
func (ar *AppRepository) UpdateApplication(app entity.Application) (entity.Application, error) {
_, err := ar.DB.Model(&app).Column("name", "description").WherePK().Returning("*").Update()
return app, err
}
func (ar *AppRepository) GetApplicationById(id int32) (*entity.Application, error) {
app := &entity.Application{Id: id}
err := ar.DB.Select(app)
if err == pg.ErrNoRows {
return nil, nil
}
return app, err
}
func (ar *AppRepository) DeleteApplications(list []int32) (int, error) {
res, err := ar.DB.Model(emptyApplication).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
-69
View File
@@ -1,69 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
var (
emptyDomain = &entity.Domain{}
DomainRep DomainRepository
)
type DomainRepository struct {
DB orm.DB
}
func (dr *DomainRepository) GetDomains(list []int32) ([]entity.Domain, error) {
var res []entity.Domain
q := dr.DB.Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (dr *DomainRepository) GetDomainsBySystemId(systemId int32) ([]entity.Domain, error) {
var res []entity.Domain
err := dr.DB.Model(&res).Where("system_id = ?", systemId).Order("created_at DESC").Select()
return res, err
}
func (dr *DomainRepository) CreateDomain(domain entity.Domain) (entity.Domain, error) {
_, err := dr.DB.Model(&domain).Insert()
return domain, err
}
func (dr *DomainRepository) GetDomainByNameAndSystemId(name string, systemId int32) (*entity.Domain, error) {
domain := new(entity.Domain)
err := dr.DB.Model(domain).Where("name = ? AND system_id = ?", name, systemId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return domain, err
}
func (dr *DomainRepository) UpdateDomain(domain entity.Domain) (entity.Domain, error) {
_, err := dr.DB.Model(&domain).Column("name", "description").WherePK().Returning("*").Update()
return domain, err
}
func (dr *DomainRepository) GetDomainById(id int32) (*entity.Domain, error) {
domain := &entity.Domain{Id: id}
err := dr.DB.Select(domain)
if err == pg.ErrNoRows {
return nil, nil
}
return domain, err
}
func (dr *DomainRepository) DeleteDomains(list []int32) (int, error) {
res, err := dr.DB.Model(emptyDomain).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
-69
View File
@@ -1,69 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
var (
emptyService = &entity.Service{}
ServiceRep ServiceRepository
)
type ServiceRepository struct {
DB orm.DB
}
func (sr *ServiceRepository) GetServices(list []int32) ([]entity.Service, error) {
var res []entity.Service
q := sr.DB.Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (sr *ServiceRepository) GetServicesByDomainId(domainId ...int32) ([]entity.Service, error) {
var res []entity.Service
err := sr.DB.Model(&res).Where("domain_id IN (?)", pg.In(domainId)).Order("created_at DESC").Select()
return res, err
}
func (sr *ServiceRepository) CreateService(service entity.Service) (entity.Service, error) {
_, err := sr.DB.Model(&service).Insert()
return service, err
}
func (sr *ServiceRepository) GetServiceByNameAndDomainId(name string, domainId int32) (*entity.Service, error) {
service := new(entity.Service)
err := sr.DB.Model(service).Where("name = ? AND domain_id = ?", name, domainId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return service, err
}
func (sr *ServiceRepository) UpdateService(service entity.Service) (entity.Service, error) {
_, err := sr.DB.Model(&service).Column("name", "description").WherePK().Returning("*").Update()
return service, err
}
func (sr *ServiceRepository) GetServiceById(id int32) (*entity.Service, error) {
service := &entity.Service{Id: id}
err := sr.DB.Select(service)
if err == pg.ErrNoRows {
return nil, nil
}
return service, err
}
func (sr *ServiceRepository) DeleteServices(list []int32) (int, error) {
res, err := sr.DB.Model(emptyService).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
-73
View File
@@ -1,73 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
"github.com/integration-system/isp-lib/database"
)
var (
emptySystem = &entity.System{}
SystemRep SystemRepository
)
type SystemRepository struct {
DB orm.DB
}
func (sr *SystemRepository) GetSystems(list []int32) ([]entity.System, error) {
var res []entity.System
q := sr.DB.Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (sr *SystemRepository) CreateSystem(system entity.System) (entity.System, error) {
_, err := sr.DB.Model(&system).Insert()
return system, err
}
func (sr *SystemRepository) GetSystemByName(name string) (*entity.System, error) {
sys := new(entity.System)
err := sr.DB.Model(sys).Where("name = ?", name).First()
if err == pg.ErrNoRows {
return nil, nil
}
return sys, err
}
func (sr *SystemRepository) UpdateSystem(system entity.System) (entity.System, error) {
_, err := sr.DB.Model(&system).Column("name", "description").WherePK().Returning("*").Update()
return system, err
}
func (sr *SystemRepository) GetSystemById(id int32) (*entity.System, error) {
sys := &entity.System{Id: id}
err := sr.DB.Select(sys)
if err == pg.ErrNoRows {
return nil, nil
}
return sys, err
}
func (sr *SystemRepository) DeleteSystems(list []int32) (int, error) {
res, err := sr.DB.Model(emptySystem).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
func InitDbManager(pdb *database.DBManager) {
db := pdb.Db
SystemRep = SystemRepository{db}
DomainRep = DomainRepository{db}
ServiceRep = ServiceRepository{db}
AppRep = AppRepository{db}
TokenRep = TokenRepository{db}
}
-45
View File
@@ -1,45 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
type TokenRepository struct {
DB orm.DB
}
var (
emptyToken = &entity.Token{}
TokenRep TokenRepository
)
func (tr *TokenRepository) SaveToken(token entity.Token) (entity.Token, error) {
_, err := tr.DB.Model(&token).Insert()
return token, err
}
func (tr *TokenRepository) GetTokenById(id string) (*entity.Token, error) {
token := &entity.Token{Token: id}
err := tr.DB.Select(token)
if err == pg.ErrNoRows {
return nil, nil
}
return token, err
}
func (tr *TokenRepository) GetTokensByAppId(appId ...int32) ([]entity.Token, error) {
var res = make([]entity.Token, 0)
err := tr.DB.Model(&res).Where("app_id IN (?)", pg.In(appId)).Order("created_at DESC").Select()
return res, err
}
func (tr *TokenRepository) DeleteTokens(tokens []string) (int, error) {
res, err := tr.DB.Model(emptyToken).Where("token IN (?)", pg.In(tokens)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
+153
View File
@@ -0,0 +1,153 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"isp-system-service/domain"
"isp-system-service/entity"
)
type AccessList struct {
db db.DB
}
func NewAccessList(db db.DB) AccessList {
return AccessList{
db: db,
}
}
func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error) {
q := `
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)
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) {
q := `
SELECT app_id, method, value
FROM access_list
WHERE app_id = $1
`
result := make([]entity.AccessList, 0)
err := r.db.Select(ctx, &result, q, appId)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []int) ([]entity.AccessList, error) {
q, args, err := query.New().
Select("app_id", "method", "value").
From("access_list").
Where(squirrel.Eq{"app_id": appIdList}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.AccessList, 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 AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error {
qBuilder := query.New().
Insert("access_list").
Columns("app_id", "method", "value")
for _, e := range entity {
qBuilder = qBuilder.Values(e.AppId, e.Method, e.Value)
}
q, args, err := qBuilder.ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, q, args...)
if err != nil {
return errors.WithMessagef(err, "exec query %s", q)
}
return nil
}
func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) {
q := `
INSERT INTO access_list
(app_id, method, value)
VALUES ($1, $2, $3)
ON CONFLICT (app_id, method)
DO UPDATE
SET (value) = (SELECT EXCLUDED.value)
`
result, err := r.db.Exec(ctx, q, e.AppId, e.Method, e.Value)
if err != nil {
return 0, errors.WithMessagef(err, "exec query %s", q)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessage(err, "get rows affected")
}
return int(rowsAffected), nil
}
func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []string) error {
q, args, err := query.New().
Delete("access_list").
Where(squirrel.Eq{
"app_id": appId,
"method": methods,
}).
Suffix("RETURNING app_id, method, value").
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, q, args...)
if err != nil {
return errors.WithMessagef(err, "exec db")
}
return nil
}
func (r AccessList) DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
q := `
DELETE FROM access_list
WHERE app_id = $1
RETURNING app_id, method, value
`
result := make([]entity.AccessList, 0)
err := r.db.Select(ctx, &result, q, appId)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
return result, nil
}
+184
View File
@@ -0,0 +1,184 @@
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/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
)
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) {
q := `
SELECT id, name, description, domain_id, 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) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "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) GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("application_group").
Where(squirrel.Eq{"domain_id": domainIdList}).
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) GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error) {
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM application_group
WHERE name = $1 AND domain_id = $2
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, name, domainId)
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, domainId int) (*entity.AppGroup, error) {
q := `
INSERT INTO application_group
(name, description, domain_id)
VALUES ($1, $2, $3)
ON CONFLICT (name, domain_id) DO NOTHING
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, name, desc, domainId)
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) {
q := `
UPDATE application_group
SET name = $1, description = $2
WHERE id = $3
RETURNING id, name, description, domain_id, 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) {
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) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "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
}
+248
View File
@@ -0,0 +1,248 @@
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/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
)
type Application struct {
db db.DB
}
func NewApplication(db db.DB) Application {
return Application{
db: db,
}
}
func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Application, error) {
q := `
SELECT id, name, description, application_group_id, type, created_at, updated_at
FROM application
WHERE id = $1
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrApplicationNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) {
q, args, err := query.New().
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
From("application").
Where(squirrel.Eq{"id": idList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
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) GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error) {
q, args, err := query.New().
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
From("application").
Where(squirrel.Eq{"application_group_id": appGroupIdList}).
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) GetApplicationByNameAndAppGroupId(ctx context.Context, name string, serviceId int) (*entity.Application, error) {
q := `
SELECT id, name, description, application_group_id, type, created_at, updated_at
FROM application
WHERE name = $1 AND application_group_id = $2
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, name, serviceId)
switch {
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
}
}
func (r Application) CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (
*entity.Application, error) {
q := `
INSERT INTO application
(id, name, description, application_group_id, type)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, name, description, application_group_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id, name, desc, appGroupId, appType)
if err != nil {
return nil, r.handleCreateError(err, q)
}
return &result, nil
}
func (r Application) UpdateApplication(
ctx context.Context,
id int,
name string,
description string,
) (*entity.Application, error) {
q := `
UPDATE application
SET name = $2,
description = $3
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, id, name, description)
if err != nil {
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) {
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
}
func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) {
q, args, err := query.New().
Delete("application").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessage(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessage(err, "get rows affected")
}
return int(rowsAffected), nil
}
func (r Application) NextApplicationId(ctx context.Context) (int, error) {
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) {
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)
}
}
+9
View File
@@ -0,0 +1,9 @@
package repository
const (
applicationPkConstraintName = "application_pkey"
applicationUniqueNameConstraintName = "uq_name_application_group_id"
applicationFkAppGroupConstraintName = "fk_application_group_id"
applicationGroupUniqueNameConstraint = "uq_name_domain_name"
)
+150
View File
@@ -0,0 +1,150 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"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)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrDomainNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
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.WithMessagef(err, "exec query %s", q)
}
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)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrDomainNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
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 {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
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)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrDomainNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
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 query %s", q)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
+40
View File
@@ -0,0 +1,40 @@
package repository
import (
"context"
"hash/fnv"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"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
}
+123
View File
@@ -0,0 +1,123 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Token struct {
db db.DB
}
func NewToken(db db.DB) Token {
return Token{
db: db,
}
}
func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) {
q := `
INSERT INTO token
(token, app_id, expire_time)
VALUES ($1, $2, $3)
RETURNING token, app_id, expire_time, created_at
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token, appId, expireTime)
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, error) {
q := `
SELECT token, app_id, expire_time, created_at
FROM token
WHERE token = $1
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token)
switch {
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
}
}
func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) {
q, args, err := query.New().
Select("token", "app_id", "expire_time", "created_at").
From("token").
Where(squirrel.Eq{"app_id": appIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Token, 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 Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
q, args, err := query.New().
Delete("token").
Where(squirrel.Eq{"token": tokens}).
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 Token) AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error) {
q := `
SELECT system_id, domain_id, application_group_id, app_id, token.expire_time, token.created_at
FROM token
LEFT JOIN application
ON token.app_id = application.id
LEFT JOIN application_group
ON application.application_group_id = application_group.id
LEFT JOIN domain
ON application_group.domain_id = domain.id
WHERE token = $1
`
result := entity.AuthData{}
err := r.db.SelectRow(ctx, &result, q, token)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrTokenNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
+246
View File
@@ -0,0 +1,246 @@
package routes
import (
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"isp-system-service/controller"
)
type Controllers struct {
AccessList controller.AccessList
Domain controller.Domain
Service controller.Service
Application controller.Application
AppGroup controller.AppGroup
Token controller.Token
Secure controller.Secure
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
return endpointDescriptors(Controllers{})
}
func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux {
muxer := grpc.NewMux()
for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
return muxer
}
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return concatCluster(
secureCluster(c),
accessListCluster(c),
domainCluster(c),
serviceCluster(c),
applicationCluster(c),
tokenCluster(c),
applicationGroupCluster(c),
)
}
func secureCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/secure/authenticate",
Inner: true,
Handler: c.Secure.Authenticate,
},
{
Path: "system/secure/authorize",
Inner: true,
Handler: c.Secure.Authorize,
},
}
}
func accessListCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/access_list/get_by_id",
Inner: true,
Handler: c.AccessList.GetById,
},
{
Path: "system/access_list/set_one",
Inner: true,
Handler: c.AccessList.SetOne,
},
{
Path: "system/access_list/set_list",
Inner: true,
Handler: c.AccessList.SetList,
},
}
}
func domainCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/domain/get_domains_by_system_id",
Inner: true,
Handler: c.Domain.GetBySystemId,
},
{
Path: "system/domain/create_update_domain",
Inner: true,
Handler: c.Domain.CreateUpdate,
},
{
Path: "system/domain/get_domain_by_id",
Inner: true,
Handler: c.Domain.GetById,
},
{
Path: "system/domain/delete_domains",
Inner: true,
Handler: c.Domain.Delete,
},
}
}
// deprecated
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,
},
}
}
func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/application/get_applications",
Inner: true,
Handler: c.Application.GetByIdList,
},
{
Path: "system/application/get_applications_by_service_id",
Inner: true,
Handler: c.Application.GetByServiceId,
},
{
Path: "system/application/create_update_application",
Inner: true,
Handler: c.Application.CreateUpdate,
},
{
Path: "system/application/get_application_by_id",
Inner: true,
Handler: c.Application.GetById,
},
{
Path: "system/application/delete_applications",
Inner: true,
Handler: c.Application.Delete,
},
{
Path: "system/application/get_system_tree",
Inner: true,
Handler: c.Application.GetSystemTree,
},
{
Path: "system/application/next_id",
Inner: true,
Handler: c.Application.NextId,
},
{
Path: "system/application/get_all",
Inner: true,
Handler: c.Application.GetAll,
},
{
Path: "system/application/create_application",
Inner: true,
Handler: c.Application.Create,
}, {
Path: "system/application/update_application",
Inner: true,
Handler: c.Application.Update,
},
}
}
func tokenCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/token/create_token",
Inner: true,
Handler: c.Token.Create,
},
{
Path: "system/token/revoke_tokens",
Inner: true,
Handler: c.Token.Revoke,
},
{
Path: "system/token/revoke_tokens_for_app",
Inner: true,
Handler: c.Token.RevokeForApp,
},
{
Path: "system/token/get_tokens_by_app_id",
Inner: true,
Handler: c.Token.GetByAppId,
},
}
}
func applicationGroupCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/application_group/create",
Inner: true,
Handler: c.AppGroup.Create,
}, {
Path: "system/application_group/update",
Inner: true,
Handler: c.AppGroup.Update,
}, {
Path: "system/application_group/delete_list",
Inner: true,
Handler: c.AppGroup.DeleteList,
}, {
Path: "system/application_group/get_by_id_list",
Inner: true,
Handler: c.AppGroup.GetByIdList,
}, {
Path: "system/application_group/get_all",
Inner: true,
Handler: c.AppGroup.GetAll,
},
}
}
func concatCluster(clusters ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
var result []cluster.EndpointDescriptor
for _, c := range clusters {
result = append(result, c...)
}
return result
}
+157
View File
@@ -0,0 +1,157 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type AccessListRepo interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
}
type AccessListSetOneTx interface {
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
}
type AccessListSetListTx interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error
DeleteAccessList(ctx context.Context, appId int, methods []string) error
DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
}
type AccessListTxRunner interface {
AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx AccessListSetOneTx) error) error
AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx AccessListSetListTx) error) error
}
type AccessList struct {
tx AccessListTxRunner
accessListRepo AccessListRepo
appRepo ApplicationRepo
}
func NewAccessList(
tx AccessListTxRunner,
accessListRepo AccessListRepo,
appRepo ApplicationRepo,
) AccessList {
return AccessList{
tx: tx,
accessListRepo: accessListRepo,
appRepo: appRepo,
}
}
func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error) {
_, err := s.appRepo.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get access list by app_id")
}
methodInfos := make([]domain.MethodInfo, len(accessList))
for i, access := range accessList {
methodInfos[i] = domain.MethodInfo{
Method: access.Method,
Value: access.Value,
}
}
return methodInfos, nil
}
func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
_, err := s.appRepo.GetApplicationById(ctx, request.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
var resp int
err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx AccessListSetOneTx) error {
resp, err = tx.UpsertAccessList(ctx, entity.AccessList{
AppId: request.AppId,
Method: request.Method,
Value: request.Value,
})
if err != nil {
return errors.WithMessage(err, "upsert access list")
}
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "transaction access list set one")
}
return &domain.AccessListSetOneResponse{
Count: resp,
}, nil
}
func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
_, err := s.appRepo.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
err = s.tx.AccessListSetListTx(ctx, func(ctx context.Context, tx AccessListSetListTx) error {
if req.RemoveOld {
_, err = tx.DeleteAccessListByAppId(ctx, req.AppId)
if err != nil {
return errors.WithMessage(err, "delete access list by app_id")
}
}
newAccessList := make([]entity.AccessList, len(req.Methods))
updateMethods := make([]string, len(req.Methods))
for i, m := range req.Methods {
updateMethods[i] = m.Method
newAccessList[i] = entity.AccessList{
AppId: req.AppId,
Method: m.Method,
Value: m.Value,
}
}
if len(newAccessList) > 0 {
err = tx.DeleteAccessList(ctx, req.AppId, updateMethods)
if err != nil {
return errors.WithMessage(err, "delete access_list")
}
err = tx.InsertArrayAccessList(ctx, newAccessList)
if err != nil {
return errors.WithMessage(err, "insert access_list")
}
}
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "transaction access list set list")
}
accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get access list by app_id")
}
methodInfos := make([]domain.MethodInfo, len(accessList))
for i, access := range accessList {
methodInfos[i] = domain.MethodInfo{
Method: access.Method,
Value: access.Value,
}
}
return methodInfos, nil
}
+81
View File
@@ -0,0 +1,81 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/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, 1)
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,
}
}
+287
View File
@@ -0,0 +1,287 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type ApplicationDeleteTx interface {
DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error)
}
type ApplicationTxRunner interface {
ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx ApplicationDeleteTx) error) error
}
type Application struct {
txRunner ApplicationTxRunner
appRepo ApplicationRepo
domainRepo DomainRepo
serviceRepo AppGroupRepo
tokenRepo TokenRepo
}
func NewApplication(
txRunner ApplicationTxRunner,
applicationRepo ApplicationRepo,
domainRepo DomainRepo,
appGroupRepo AppGroupRepo,
tokenRepo TokenRepo,
) Application {
return Application{
txRunner: txRunner,
appRepo: applicationRepo,
domainRepo: domainRepo,
serviceRepo: appGroupRepo,
tokenRepo: tokenRepo,
}
}
func (s Application) GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error) {
application, err := s.appRepo.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
arr, err := s.EnrichWithTokens(ctx, []entity.Application{*application})
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) {
res, err := s.appRepo.GetApplicationByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get application by id list")
}
return s.EnrichWithTokens(ctx, res)
}
func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) {
arr, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, []int{id})
if err != nil {
return nil, errors.WithMessage(err, "get application by app_group_id")
}
return s.EnrichWithTokens(ctx, arr)
}
func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) {
domainEntityList, err := s.domainRepo.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.serviceRepo.GetAppGroupByDomainId(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
resultService := &domain.ServiceWithApps{
Id: serviceEntity.Id,
Name: serviceEntity.Name,
Description: serviceEntity.Description.String,
Apps: make([]*domain.ApplicationSimple, 0),
}
r := resultByDomainId[serviceEntity.DomainId]
r.Services = append(r.Services, resultService)
resultServiceByServiceId[serviceEntity.Id] = resultService
}
applicationEntityList, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, serviceIdList)
if err != nil {
return nil, errors.WithMessage(err, "get application by service_id")
}
for _, applicationEntity := range applicationEntityList {
resultService := resultServiceByServiceId[applicationEntity.ApplicationGroupId]
resultService.Apps = append(resultService.Apps, &domain.ApplicationSimple{
Id: applicationEntity.Id,
Name: applicationEntity.Name,
Type: applicationEntity.Type,
Description: applicationEntity.Description.String,
Tokens: make([]domain.Token, 0),
})
}
return result, nil
}
func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
if req.Id == 0 {
_, err := s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId)
if err != nil {
return nil, errors.WithMessage(err, "get application by name and service_id")
}
appId, err := s.appRepo.NextApplicationId(ctx)
if err != nil {
return nil, errors.WithMessage(err, "next app id")
}
app, err := s.appRepo.CreateApplication(ctx, appId, req.Name, req.Description, req.ServiceId, req.Type)
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
}
app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update 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
}
func (s Application) Delete(ctx context.Context, idList []int) (int, error) {
count := 0
err := s.txRunner.ApplicationDeleteTx(ctx, func(ctx context.Context, tx ApplicationDeleteTx) error {
deletedApp, err := tx.DeleteApplicationByIdList(ctx, idList)
if err != nil {
return errors.WithMessage(err, "delete application by id list")
}
count = deletedApp
return nil
})
if err != nil {
return 0, errors.WithMessage(err, "transaction application delete")
}
return count, nil
}
func (s Application) EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error) {
if len(apps) == 0 {
return []*domain.ApplicationWithTokens{}, nil
}
appIdList := make([]int, len(apps))
resultByAppId := make(map[int]*domain.ApplicationWithTokens, len(apps))
result := make([]*domain.ApplicationWithTokens, len(apps))
for i, a := range apps {
appIdList[i] = a.Id
awt := &domain.ApplicationWithTokens{
App: s.convertApplication(a),
Tokens: make([]domain.Token, 0),
}
resultByAppId[a.Id] = awt
result[i] = awt
}
tokens, err := s.tokenRepo.GetTokenByAppIdList(ctx, appIdList)
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
for _, token := range tokens {
r := resultByAppId[token.AppId]
r.Tokens = append(r.Tokens, domain.Token(token))
}
return result, nil
}
func (s Application) NextId(ctx context.Context) (int, error) {
nextId, err := s.appRepo.NextApplicationId(ctx)
if err != nil {
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.ApplicationWithTokens, 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 &domain.ApplicationWithTokens{
App: s.convertApplication(*app),
Tokens: make([]domain.Token, 0),
}, nil
}
func (s Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, 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")
}
result, err := s.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessage(err, "enrich application with tokens")
}
return result[0], nil
}
func (s Application) convertApplication(req entity.Application) domain.Application {
return domain.Application{
Id: req.Id,
Name: req.Name,
Description: req.Description.String,
ServiceId: req.ApplicationGroupId,
Type: req.Type,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
}
+110
View File
@@ -0,0 +1,110 @@
package baseline
import (
"context"
"isp-system-service/conf"
"isp-system-service/entity"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/log"
)
const adminAppId = 1
type Transaction interface {
CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error)
CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*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")
domain, err := tx.CreateDomain(ctx, "root", "", 1)
if err != nil {
return errors.WithMessage(err, "create domain")
}
service, err := tx.CreateAppGroup(ctx, "rootService", "", domain.Id)
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
}
+108
View File
@@ -0,0 +1,108 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Domain struct {
repo DomainRepo
}
func NewDomain(repo DomainRepo) Domain {
return Domain{
repo: repo,
}
}
func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) {
domainEntity, err := s.repo.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.repo.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.repo.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.repo.CreateDomain(ctx, req.Name, req.Description, systemId)
if err != nil {
return nil, errors.WithMessage(err, "create domain")
}
result := s.convertDomain(*domainEntity)
return &result, nil
}
if existed != nil && existed.Id != req.Id {
return nil, domain.ErrDomainDuplicateName
}
_, err = s.repo.GetDomainById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
domainEntity, err := s.repo.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.repo.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
}
+42
View File
@@ -0,0 +1,42 @@
package service
import (
"context"
"isp-system-service/entity"
)
type TokenRepo interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
}
type DomainRepo 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 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)
GetApplicationByNameAndAppGroupId(ctx context.Context, name string, appGroupId 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)
GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error)
GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error)
GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error)
CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error)
UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error)
DeleteAppGroup(ctx context.Context, idList []int) (int, error)
}
+62
View File
@@ -0,0 +1,62 @@
package secure
import (
"context"
"time"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type TokenRep interface {
AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error)
}
type AccessListRep interface {
GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error)
}
type Service struct {
tokenRep TokenRep
accessListRep AccessListRep
}
func NewService(
tokenRep TokenRep,
accessListRep AccessListRep,
) Service {
return Service{
tokenRep: tokenRep,
accessListRep: accessListRep,
}
}
func (s Service) Authenticate(ctx context.Context, token string) (*domain.AuthData, error) {
authData, err := s.tokenRep.AuthDataByToken(ctx, token)
if err != nil {
return nil, errors.WithMessage(err, "get auth data by token")
}
if authData.ExpireTime != -1 &&
authData.CreatedAt.Add(time.Millisecond*time.Duration(authData.ExpireTime)).Before(time.Now().UTC()) {
return nil, domain.ErrTokenExpired
}
return &domain.AuthData{
SystemId: authData.SystemId,
DomainId: authData.DomainId,
ServiceId: authData.ApplicationGroupId,
ApplicationId: authData.AppId,
}, nil
}
func (s Service) Authorize(ctx context.Context, appId int, endpoint string) (bool, error) {
accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod(ctx, appId, endpoint)
if err != nil {
return false, errors.WithMessage(err, "get access list by app_id and method")
}
return accessList.Value, nil
}
+115
View File
@@ -0,0 +1,115 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type Service struct {
domainRepo DomainRepo
serviceRepo AppGroupRepo
}
func NewService(
domainRepo DomainRepo,
serviceRepo AppGroupRepo,
) Service {
return Service{
domainRepo: domainRepo,
serviceRepo: serviceRepo,
}
}
func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) {
serviceEntity, err := s.serviceRepo.GetAppGroupById(ctx, id)
if err != nil {
return nil, errors.WithMessage(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.serviceRepo.GetAppGroupByIdList(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.serviceRepo.GetAppGroupByDomainId(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) {
req.DomainId = 1 // temporary use only 1 domain, soon domain entity will be removed
_, err := s.domainRepo.GetDomainById(ctx, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
if req.Id == 0 {
serviceEntity, err := s.serviceRepo.CreateAppGroup(ctx, req.Name, req.Description, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "create service")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
_, err = s.serviceRepo.GetAppGroupById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
}
serviceEntity, err := s.serviceRepo.UpdateAppGroup(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.serviceRepo.DeleteAppGroup(ctx, idList)
if err != nil {
return 0, errors.WithMessage(err, "delete service")
}
return result, nil
}
func (s Service) convertService(req entity.AppGroup) domain.Service {
result := domain.Service{
Id: req.Id,
Name: req.Name,
Description: req.Description.String,
DomainId: req.DomainId,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
return result
}
+173
View File
@@ -0,0 +1,173 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type ApplicationTokenCreator interface {
CreateApplicationToken() (string, error)
}
type AppEnricher interface {
EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error)
}
type TokenCreateTx interface {
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
}
type TokenRevokeTx interface {
DeleteToken(ctx context.Context, tokens []string) (int, error)
}
type TokenTxRunner interface {
TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx TokenCreateTx) error) error
TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx TokenRevokeTx) error) error
}
type Token struct {
jwt ApplicationTokenCreator
appEnricher AppEnricher
tx TokenTxRunner
appRepo ApplicationRepo
domainRepo DomainRepo
serviceRepo AppGroupRepo
tokenRepo TokenRepo
}
func NewToken(
jwtGenerate ApplicationTokenCreator,
appEnricher AppEnricher,
tx TokenTxRunner,
appRepo ApplicationRepo,
domainRepo DomainRepo,
appGroupRepo AppGroupRepo,
tokenRepo TokenRepo,
) Token {
return Token{
appEnricher: appEnricher,
jwt: jwtGenerate,
tx: tx,
appRepo: appRepo,
domainRepo: domainRepo,
serviceRepo: appGroupRepo,
tokenRepo: tokenRepo,
}
}
func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error) {
tokenEntity, err := s.tokenRepo.GetTokenByAppIdList(ctx, []int{appId})
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
result := make([]domain.Token, len(tokenEntity))
for i, token := range tokenEntity {
result[i] = domain.Token(token)
}
return result, nil
}
func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
applicationEntity, err := s.appRepo.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
serviceEntity, err := s.serviceRepo.GetAppGroupById(ctx, applicationEntity.ApplicationGroupId)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
}
_, err = s.domainRepo.GetDomainById(ctx, serviceEntity.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
token, err := s.jwt.CreateApplicationToken()
if err != nil {
return nil, errors.WithMessage(err, "create application token")
}
err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx TokenCreateTx) error {
_, err = tx.SaveToken(ctx, token, req.AppId, req.ExpireTimeMs)
if err != nil {
return errors.WithMessage(err, "tx save token")
}
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "token create transaction")
}
arr, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*applicationEntity})
if err != nil {
return nil, errors.WithMessage(err, "application enrich with tokens")
}
return arr[0], nil
}
func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
app, err := s.appRepo.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
_, err = s.revokeTokens(ctx, req.Tokens)
if err != nil {
return nil, errors.WithMessage(err, "revoke tokens")
}
res, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessage(err, "application enrich")
}
return res[0], nil
}
func (s Token) RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error) {
tokens, err := s.tokenRepo.GetTokenByAppIdList(ctx, []int{appId})
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
tokenIdList := make([]string, len(tokens))
for i, t := range tokens {
tokenIdList[i] = t.Token
}
return s.revokeTokens(ctx, tokenIdList)
}
func (s Token) revokeTokens(ctx context.Context, tokens []string) (*domain.DeleteResponse, error) {
if len(tokens) == 0 {
return &domain.DeleteResponse{Deleted: 0}, nil
}
var count int
err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx TokenRevokeTx) error {
deleted, err := tx.DeleteToken(ctx, tokens)
if err != nil {
return errors.WithMessage(err, "tx delete token")
}
count = deleted
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "token revoke transaction")
}
return &domain.DeleteResponse{
Deleted: count,
}, nil
}
+25
View File
@@ -0,0 +1,25 @@
package service
import (
"crypto/rand"
"encoding/hex"
"github.com/pkg/errors"
)
type TokenSource struct{}
func NewTokenSource() TokenSource {
return TokenSource{}
}
func (s TokenSource) CreateApplicationToken() (string, error) {
cryptoRand := make([]byte, 128) //nolint:mnd
_, err := rand.Read(cryptoRand)
if err != nil {
return "", errors.WithMessage(err, "crypto/rand read")
}
random := hex.EncodeToString(cryptoRand)
return random, nil
}
+287
View File
@@ -0,0 +1,287 @@
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
domainRepo repository.Domain
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.domainRepo = repository.NewDomain(s.testDb)
s.appGroupRepo = repository.NewAppGroup(s.testDb)
q := `
INSERT INTO domain
(id, name, description, system_id)
VALUES ($1, $2, $3, $4)
RETURNING id, name, description, system_id, created_at, updated_at
`
_, err := s.testDb.Exec(s.T().Context(), q, 1, fake.It[string](), fake.It[string](), 1)
s.Require().NoError(err)
}
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](),
"",
1,
)
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](),
1,
)
s.Require().NoError(err)
return appGroup
}
+292
View File
@@ -0,0 +1,292 @@
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 TestApplicationSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &ApplicationSuite{})
}
type ApplicationSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
domainRepo repository.Domain
appRepo repository.Application
appGroupRepo repository.AppGroup
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.domainRepo = repository.NewDomain(s.testDb)
s.appRepo = repository.NewApplication(s.testDb)
s.appGroupRepo = repository.NewAppGroup(s.testDb)
}
func (s *ApplicationSuite) TestGetAllApplications() {
toInsert := fake.It[[]domain.Application](fake.MaxSliceSize(2), fake.MinSliceSize(2))
expectedApps := s.insertApps(toInsert)
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) TestCreate_HappyPath() {
result := domain.ApplicationWithTokens{}
apiReq := fake.It[domain.CreateApplicationRequest]()
apiReq.Type = domain.ApplicationSystemType
appGroup := s.createAppGroup()
apiReq.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.App.CreatedAt)
result.App.CreatedAt = time.Time{}
s.Require().NotEmpty(result.App.UpdatedAt)
result.App.UpdatedAt = time.Time{}
expectedApp := domain.Application{
Id: apiReq.Id,
Name: apiReq.Name,
Description: apiReq.Description,
Type: apiReq.Type,
ServiceId: apiReq.ApplicationGroupId,
}
s.Require().Equal(expectedApp, result.App)
s.Require().Empty(result.Tokens)
}
func (s *ApplicationSuite) TestCreate_AppGroupNotFound() {
apiReq := fake.It[domain.CreateApplicationRequest]()
apiReq.Type = domain.ApplicationSystemType
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() {
apiReq := fake.It[domain.CreateApplicationRequest]()
apiReq.Type = domain.ApplicationSystemType
inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(1), fake.MaxSliceSize(1)))
apiReq.ApplicationGroupId = inserted[0].ServiceId
apiReq.Name = inserted[0].Name
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() {
apiReq := fake.It[domain.CreateApplicationRequest]()
apiReq.Type = "SYSTEM"
appGroup := s.createAppGroup()
apiReq.ApplicationGroupId = appGroup.Id
inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(1), fake.MaxSliceSize(1)))
apiReq.Id = inserted[0].Id
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(fake.It[[]domain.Application](fake.MinSliceSize(1), fake.MaxSliceSize(1)))
apiReq := domain.UpdateApplicationRequest{
OldId: inserted[0].Id,
NewId: fake.It[int](),
Name: fake.It[string](),
Description: fake.It[string](),
}
var result domain.ApplicationWithTokens
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().NotEmpty(result.App.CreatedAt)
result.App.CreatedAt = time.Time{}
s.Require().NotEmpty(result.App.UpdatedAt)
result.App.UpdatedAt = time.Time{}
expectedApp := domain.Application{
Id: apiReq.NewId,
Name: apiReq.Name,
Description: apiReq.Description,
Type: inserted[0].Type,
ServiceId: inserted[0].ServiceId,
}
s.Require().Equal(expectedApp, result.App)
s.Require().Empty(result.Tokens)
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].ServiceId,
}
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(fake.It[[]domain.Application](fake.MinSliceSize(2), fake.MaxSliceSize(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(fake.It[[]domain.Application](fake.MinSliceSize(2), fake.MaxSliceSize(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) createAppGroup() *entity.AppGroup {
createdDomain, err := s.domainRepo.CreateDomain(
s.T().Context(),
fake.It[string](),
fake.It[string](),
1,
)
s.Require().NoError(err)
appGroup, err := s.appGroupRepo.CreateAppGroup(
s.T().Context(),
fake.It[string](),
fake.It[string](),
createdDomain.Id,
)
s.Require().NoError(err)
return appGroup
}
func (s *ApplicationSuite) insertApps(toInsert []domain.Application) []domain.Application {
appGroup := s.createAppGroup()
toExpect := make([]domain.Application, 0, len(toInsert))
for _, app := range toInsert {
createdApp, err := s.appRepo.CreateApplication(
s.T().Context(),
app.Id,
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,
ServiceId: createdApp.ApplicationGroupId,
Type: createdApp.Type,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
}
return toExpect
}
+52
View File
@@ -0,0 +1,52 @@
package tests_test
import (
"context"
"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(context.Background())
s.Require().NoError(err)
err = s.baseline.Do(context.Background())
s.Require().NoError(err)
}
+57
View File
@@ -0,0 +1,57 @@
package tests_test
import (
"isp-system-service/entity"
"github.com/txix-open/isp-kit/test/dbt"
)
func InsertDomain(db *dbt.TestDb, value entity.Domain) {
q := `
INSERT INTO domain
(id, name, description, system_id, created_at, updated_at)
VALUES
(:id, :name, :description, 1, :created_at, :updated_at)
`
db.Must().ExecNamed(q, value)
}
func InsertAppGroup(db *dbt.TestDb, value entity.AppGroup) {
q := `
INSERT INTO application_group
(id, name, description, domain_id, created_at, updated_at)
VALUES
(:id, :name, :description, :domain_id, :created_at, :updated_at)
`
db.Must().ExecNamed(q, value)
}
func InsertApplication(db *dbt.TestDb, value entity.Application) {
q := `
INSERT INTO application
(id, name, description, application_group_id, created_at, updated_at)
VALUES
(:id, :name, :description, :application_group_id, :created_at, :updated_at)
`
db.Must().ExecNamed(q, value)
}
func InsertToken(db *dbt.TestDb, value entity.Token) {
q := `
INSERT INTO token
(token, created_at, app_id, expire_time)
VALUES
(:token, :created_at, :app_id, :expire_time)
`
db.Must().ExecNamed(q, value)
}
func InsertAccessList(db *dbt.TestDb, value entity.AccessList) {
q := `
INSERT INTO access_list
(app_id, method, value)
VALUES
(:app_id, :method, :value)
`
db.Must().ExecNamed(q, value)
}
+198
View File
@@ -0,0 +1,198 @@
package tests_test
import (
"context"
"testing"
"time"
"github.com/txix-open/isp-kit/dbx"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/stretchr/testify/require"
"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) {
t.Parallel()
suite.Run(t, &SecureSuite{})
}
type SecureSuite struct {
suite.Suite
test *test.Test
require *require.Assertions
testDb *dbt.TestDb
api *client.Client
}
func (s *SecureSuite) SetupSuite() {
s.test, s.require = 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)
createdTime := time.Now().UTC()
InsertDomain(s.testDb, entity.Domain{
Id: 3, Name: "test_domain", SystemId: 1, CreatedAt: createdTime, UpdatedAt: createdTime,
})
InsertAppGroup(s.testDb, entity.AppGroup{
Id: 5, Name: "test_application_group", DomainId: 3, CreatedAt: createdTime, UpdatedAt: createdTime,
})
InsertApplication(s.testDb, entity.Application{
Id: 7, Name: "test_application", ApplicationGroupId: 5, CreatedAt: createdTime, UpdatedAt: createdTime,
})
}
func (s *SecureSuite) TestAuthenticate_Success() {
InsertToken(s.testDb, entity.Token{
Token: "test_token_success", AppId: 7, ExpireTime: -1, CreatedAt: time.Now().UTC(),
})
result := domain.AuthenticateResponse{}
err := s.api.Invoke("system/secure/authenticate").
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_success",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
SystemId: 1,
DomainId: 3,
ServiceId: 5,
ApplicationId: 7,
},
}, result)
}
func (s *SecureSuite) TestAuthenticate_NotFound() {
result := domain.AuthenticateResponse{}
err := s.api.Invoke("system/secure/authenticate").
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_not_found",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenNotFound.Error(),
AuthData: nil,
}, result)
}
func (s *SecureSuite) TestAuthenticate_NotExpired() {
InsertToken(s.testDb, entity.Token{
Token: "test_token_not_expired", AppId: 7, ExpireTime: int((time.Hour).Milliseconds()), CreatedAt: time.Now().UTC(),
})
result := domain.AuthenticateResponse{}
err := s.api.Invoke("system/secure/authenticate").
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_not_expired",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
SystemId: 1,
DomainId: 3,
ServiceId: 5,
ApplicationId: 7,
},
}, result)
}
func (s *SecureSuite) TestAuthenticate_Expired() {
InsertToken(s.testDb, entity.Token{
Token: "test_token_expired", AppId: 7, ExpireTime: 0, CreatedAt: time.Now().UTC(),
})
result := domain.AuthenticateResponse{}
err := s.api.Invoke("system/secure/authenticate").
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_expired",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenExpired.Error(),
AuthData: nil,
}, result)
}
func (s *SecureSuite) TestAuthorize_Success_True() {
InsertAccessList(s.testDb, entity.AccessList{
AppId: 7,
Method: "endpoint/available",
Value: true,
})
result := domain.AuthorizeResponse{}
err := s.api.Invoke("system/secure/authorize").
JsonRequestBody(domain.AuthorizeRequest{
ApplicationId: 7,
Endpoint: "endpoint/available",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: true,
}, result)
}
func (s *SecureSuite) TestAuthorize_Success_False() {
InsertAccessList(s.testDb, entity.AccessList{
AppId: 7,
Method: "endpoint/not_available",
Value: false,
})
result := domain.AuthorizeResponse{}
err := s.api.Invoke("system/secure/authorize").
JsonRequestBody(domain.AuthorizeRequest{
ApplicationId: 7,
Endpoint: "endpoint/not_available",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: false,
}, result)
}
func (s *SecureSuite) TestAuthorize_NotFound() {
result := domain.AuthorizeResponse{}
err := s.api.Invoke("system/secure/authorize").
JsonRequestBody(domain.AuthorizeRequest{
ApplicationId: 7,
Endpoint: "endpoint/not_found",
}).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: false,
}, result)
}
+108
View File
@@ -0,0 +1,108 @@
package transaction
import (
"context"
"isp-system-service/service/baseline"
"isp-system-service/repository"
"isp-system-service/service"
"github.com/txix-open/isp-kit/db"
)
type Manager struct {
db db.Transactional
}
func NewManager(db db.Transactional) *Manager {
return &Manager{
db: db,
}
}
type accessListSetOneTx struct {
repository.AccessList
}
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 {
accessListRepository := repository.NewAccessList(tx)
return msgTx(ctx, accessListSetOneTx{
AccessList: accessListRepository,
})
})
}
type accessListSetListTx struct {
repository.AccessList
}
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 {
accessListRep := repository.NewAccessList(tx)
return msgTx(ctx, accessListSetListTx{
AccessList: accessListRep,
})
})
}
type applicationDeleteTx struct {
repository.Application
}
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 {
applicationRep := repository.NewApplication(tx)
return msgTx(ctx, applicationDeleteTx{
Application: applicationRep,
})
})
}
type tokenCreateTx struct {
repository.Token
}
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 {
tokenRep := repository.NewToken(tx)
return msgTx(ctx, tokenCreateTx{
Token: tokenRep,
})
})
}
type tokenRevokeTx struct {
repository.Token
}
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 {
tokenRep := repository.NewToken(tx)
return msgTx(ctx, tokenRevokeTx{
Token: tokenRep,
})
})
}
type baselineTx struct {
repository.Locker
repository.Domain
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),
Domain: repository.NewDomain(tx),
AppGroup: repository.NewAppGroup(tx),
Application: repository.NewApplication(tx),
AccessList: repository.NewAccessList(tx),
Token: repository.NewToken(tx),
})
})
}