22 Commits
Author SHA1 Message Date
txix e9a861b61a 2026-09-25 14:15:10: merge [main:482ec50c7d3bff1587c869331a9e0fe92d110325];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-09-25 14:15:11 +03:00
txix f6856202c4 2026-07-27 16:34:11: merge [main:ce4e04c801188b7586e9628847cb650d6c61fe5a];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-07-27 16:34:11 +03:00
txix be5ce45d17 2026-07-07 10:23:56: merge [main:172c90b0e5097baa84d498b93d1bd705834bf9f0];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-07-07 10:23:56 +03:00
txix 53fc40efe4 2026-03-04 17:51:09: merge [main:43703e570dc29ccc2c208e50bf41d48c694874f5];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-03-04 17:51:09 +03:00
txix e4445eca46 2026-02-11 16:48:41: merge [main:c304645d60621efc82700d4c7e501c49a2b2935b];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-02-11 16:48:42 +03:00
txix 1651a1fc3c 2025-11-26 10:06:04: merge [main:924c6ad2c9a493beb1cc9a0762a1c1fe11cf7b12];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-11-26 10:06:04 +03:00
txix 882e5c67a7 2025-09-17 18:08:10: merge [main:7652dd1205feaea22b42541290b3a7b021960a3e];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-09-17 18:08:10 +03:00
txix d7a7e4ee0d 2025-08-21 15:03:50: merge [main:135c25ca951814b87d4ee6a93bfd35ce5aef95f1]; 2025-08-21 15:03:50 +03:00
txix ec0f1a02d1 2025-05-27 15:03:30: merge [master:f7d84c21ab1049a1f10eacacc773ddeead8d619b];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-05-27 15:03:30 +03:00
txix 65cfb65f8e 2025-05-26 17:34:40: merge [master:d02a58345e9261c6f2b75cea3d6c36e07d9a7cfc]; 2025-05-26 17:34:40 +03:00
txix c0687a264e 2025-05-26 17:31:46: merge [master:4b0510d2764306aa9a1a7375512e74d7d7876cef]; 2025-05-26 17:31:46 +03:00
txix c5b82152e0 2025-05-14 11:54:07: merge [master:138dde59487c426482ca2f7c3e9db90630787f98]; 2025-05-14 11:54:07 +03:00
txix a648f4f9a7 2025-04-23 12:39:23: merge [master:08627f9069bb4e5a17fb658daa0e12289b08c6d9]; 2025-04-23 12:39:23 +03:00
txix 454526d047 2025-04-18 15:29:00: merge [master:11648341f1bba6069d007a4983fa808fda526d63]; 2025-04-18 15:29:00 +03:00
txix 6d3e1cbccd 2025-04-18 12:18:23: merge [master:415e2986118a77a6a1a7ae736f4c2b3950f0afa3]; 2025-04-18 12:18:23 +03:00
txix b9dcfec926 2025-04-16 17:21:18: merge [master:5a989728053866e65daaecd0956da5df565d0407]; 2025-04-16 17:21:19 +03:00
txix dff580b252 2025-03-03 11:15:00: merge [master:ffa5e100db14af4081d6d3f2ff6c00ff4c9c07fc]; 2025-03-03 11:15:00 +03:00
txix 24e21beee2 2024-12-27 18:02:08: merge [master:9e2bf02f3d5fb8d0750e33de53c3824f66b3c441]; 2024-12-27 18:02:08 +03:00
txix c11d09b992 2024-11-15 12:33:23: merge [master:8e2cec1f118c6f4d00fa843811441031b8c0b843]; 2024-11-15 12:33:23 +03:00
txix 02df1a6546 2024-09-08 15:28:22: merge [master:33b4e2d9651dc592eae18e258984b11b35cc0a5e]; 2024-09-08 15:28:22 +03:00
txix 6f45b1861f 2024-03-26 14:27:42: merge [master:f062aada4265df032155d6b731c80c09d8cbd3d6]; 2024-03-26 14:27:42 +03:00
txix 22a34dbb86 2024-03-26 12:21:52: merge [master:81c5af7538f121910d74b369acc5d0d02259250b]; 2024-03-26 12:21:52 +03:00
79 changed files with 6934 additions and 2081 deletions

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
name: Create and publish a Docker image
on:
push:
tags:
- 'v*'
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
APP_NAME: ${{ github.event.repository.name }}
jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
attestations: write
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Get version from tag
id: version_reader
run: |
VERSION=${GITHUB_REF_NAME#v}
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: docker-container
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
id: push
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version_reader.outputs.version }}
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
labels: |
org.opencontainers.image.title=${{ env.IMAGE_NAME }}
org.opencontainers.image.version=${{ steps.version_reader.outputs.version }}
build-args: |
app_name=${{ env.APP_NAME }}
version=${{ steps.version_reader.outputs.version }}
- name: Generate artifact attestation
uses: actions/attest-build-provenance@v2
with:
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true
+2 -1
View File
@@ -71,5 +71,6 @@ fabric.properties
/vendor/
google/
package.json
structure/
yarn.lock
conf/config_dev.yml
+3
View File
@@ -0,0 +1,3 @@
include:
- project: '$CI_PROJECT_PATH'
file: '/ci-isp-go-service.yml'
+69
View File
@@ -0,0 +1,69 @@
version: "2"
run:
allow-parallel-runners: true
linters:
default: all
disable:
- contextcheck # не имеет смысла
- depguard # не всегда имеет смысл
- dupword # не имеет смысла
- exhaustruct # не имеет смысла
- godot # не актуально для swagger
- godox # не позволяет оставлять todo
- musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур
- nlreturn # не всегда имеет смысл
- nolintlint # Goland все равно форматирует с отступом
- perfsprint # мнимая производительность в угоду читаемости
- tagalign # не всегда имеет смысл
- varnamelen # очень индивидуально (db)
- wsl # расставление пробелов очень индивидуально
- wsl_v5 # расставление пробелов очень индивидуально
settings:
cyclop:
max-complexity: 15 # по умолчанию 10 мало
funlen:
lines: 80
lll:
line-length: 150
revive:
rules:
- name: var-naming # отключаем Id -> ID
disabled: true
staticcheck:
checks: # отключаем Id -> ID
- -ST1000
- -ST1016
- -ST1020
- -ST1021
- -ST1022
testifylint:
disable:
- compares
- equal-values
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules:
- linters:
- wrapcheck
path: controller # достаточное кол-во контекста на уровне контроллеров
- linters:
- wrapcheck
path: transaction # транзакции прозрачны
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gofmt
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$
+1 -1
View File
@@ -1 +1 @@
0.3.0
6.0.0
+106
View File
@@ -0,0 +1,106 @@
### v6.0.0
* Удалены таблицы `domain` и `system`
* Удалены `deprecated` endpoint'ы
* Изменены контракты для `application` endpoint'ов
* Добавлены `admin` permission к endpoint'ам
### v5.7.3
* обновлены зависимости
### v5.7.2
* Обновлен isp-kit
### v5.7.1
* Методы `/access_list/get_by_id`, `/access_list/set_list` теперь возвращают `httpMethod`
### v5.7.0
* Обновлены зависимости
* Добавлено поле `http_method` в `access_list`
### v5.6.0
* Для endpoint'а `system/secure/authenticate` в ответ добавлено поле `appName` (название приложения)
* Обновлена версия `go` до `1.25`
* Обновлены зависимости
### v5.5.0
* Обновлены зависимости
### v5.4.0
* Добавлен новый endpoint: `/access_list/delete_list` для удаления методов из списка доступов у приложений
### v5.3.1
* добавлен `Dockerfile` и скрипт для сборки и публикации образа в `GitHub Contaier Registry`
* обновлены зависимости
### v5.3.0
* Добавлен новый endpoint: `/application/get_application_by_token`
### v5.2.1
* обновлены зависимости
### v5.2.0
* Обновлены зависимости
* Добавлены новые endpoint'ы: `/application/update_application`, `/application/create_application`, `/application_group/create`, `/application_group/update`, `/application_group/delete_list`, `/application_group/get_by_id_list`, `/application_group/get_all`
### v5.1.1
* обновлены зависимости
### v5.1.0
* все сервисы (группы приложений) перенесены в домен с id = 1
* при создании/изменении сервисов (групп приложений) будет использоваться только домен с id = 1
### v5.0.0
* изменен механизм инициализации токена панели администратора
* для механизма инициализации используется поле `baseline.initialAdminUiToken` в конфигурации
* если поле не заполнено, механизм не запускается
* иначе проверяется существование токена в базе, если токен уже создан, механизм не запускается
* иначе создаются все сущности и выпускается бессрочный токен, приложению выдается доступ к методу `admin/auth/login`
* механизм запускается при получении конфигурации
* при конкурентном запуске модуля, механизм запускается только на одном инстансе
* логи механизма маркируются полем "worker": "baseline"
* обновлена зависимости
### v4.0.0
* Удален `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
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
+87
View File
@@ -0,0 +1,87 @@
package assembly
import (
"context"
"github.com/txix-open/isp-kit/rc"
"isp-system-service/conf"
"github.com/txix-open/isp-kit/app"
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/dbrx"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/log"
)
type Assembly struct {
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,
}
}
+84
View File
@@ -0,0 +1,84 @@
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)
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, appGroupRep, tokenRep)
jwtService := service.NewTokenSource()
tokenService := service.NewToken(
jwtService,
applicationService,
txManager,
applicationRep,
tokenRep,
)
secureController := controller.NewSecure(secureService)
accessListController := controller.NewAccessList(accessListService)
applicationController := controller.NewApplication(applicationService)
tokenController := controller.NewToken(tokenService)
appGroupService := service.NewAppGroup(appGroupRep)
appGroupController := controller.NewAppGroup(appGroupService)
c := routes.Controllers{
Secure: secureController,
AccessList: accessListController,
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:
ip: 0.0.0.0
port: 9005
moduleName: system
instanceUuid: 3f4faf30-8482-48ef-931a-b15575a3af1d
moduleName: isp-system-service
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 = []any{"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{})
}
+171
View File
@@ -0,0 +1,171 @@
package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
)
type 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)
DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error
DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) 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
}
}
// DeleteList godoc
//
// @Tags accessList
// @Summary Удалить список доступных методов для приложения
// @Description Удаляет заданный список методов для приложения
// @Accept json
// @Produce json
// @Param body body domain.AccessListDeleteListRequest false "тело запроса"
// @Success 200 {object} any
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/delete_list [POST]
func (c AccessList) DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error {
err := c.service.DeleteList(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.AppId),
err,
)
default:
return err
}
}
// DeleteListWithMethods godoc
//
// @Tags accessList
// @Summary Удалить список доступных методов для приложения
// @Description Удаляет заданный список методов для приложения
// @Accept json
// @Produce json
// @Param body body domain.AccessListDeleteV2ListRequest false "тело запроса"
// @Success 200 {object} any
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/delete_list_with_methods [POST]
func (c AccessList) DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error {
err := c.service.DeleteListWithMethods(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.AppId),
err,
)
default:
return err
}
}
+139
View File
@@ -0,0 +1,139 @@
package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
)
type AppGroupService interface {
Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error)
Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error)
DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error)
GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error)
GetAll(ctx context.Context) ([]domain.AppGroup, error)
}
type AppGroup struct {
service AppGroupService
}
func NewAppGroup(service AppGroupService) AppGroup {
return AppGroup{
service: service,
}
}
// Create godoc
//
// @Tags application_group
// @Summary Создать группу приложений
// @Description Если группа приложений таким именем существует, возвращает ошибку
// @Accept json
// @Produce json
// @Param body body domain.CreateAppGroupRequest true "Объект группы приложений"
// @Success 200 {object} domain.AppGroup
// @Failure 400 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application_group/create [POST]
func (c AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) {
result, err := c.service.Create(ctx, req)
switch {
case errors.Is(err, domain.ErrAppGroupDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeAppGroupDuplicateName,
fmt.Sprintf("application group with name %s already exists", req.Name),
err,
)
default:
return result, err
}
}
// Update godoc
//
// @Tags application_group
// @Summary Обновить группу приложений
// @Description Если группа приложений таким именем существует или группы приложений с указанным id не существует, возвращает ошибку
// @Accept json
// @Produce json
// @Param body body domain.UpdateAppGroupRequest true "Объект группы приложений"
// @Success 200 {object} domain.AppGroup
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application_group/update [POST]
func (c AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) {
result, err := c.service.Update(ctx, req)
switch {
case errors.Is(err, domain.ErrAppGroupDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeAppGroupDuplicateName,
fmt.Sprintf("application group with name %s already exists", req.Name),
err,
)
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("application group with id %d not found", req.Id),
err,
)
default:
return result, err
}
}
// DeleteList godoc
//
// @Tags application_group
// @Summary Удалить группы приложений
// @Description Удаляет группы приложений по списку их идентификаторов, возвращает количество удаленных групп приложений
// @Accept json
// @Produce json
// @Param body body domain.IdListRequest true "список идентификаторов групп приложений"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application_group/delete_list [POST]
func (c AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) {
return c.service.DeleteList(ctx, req)
}
// GetByIdList godoc
//
// @Tags application_group
// @Summary Получить группы приложений по списку идентификаторов
// @Description Возвращает группы приложений с указанными идентификаторами
// @Accept json
// @Produce json
// @Param body body domain.IdListRequest true "список идентификаторов групп приложений"
// @Success 200 {array} domain.AppGroup
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application_group/get_by_id_list [POST]
func (c AppGroup) GetByIdList(ctx context.Context, req domain.IdListRequest) ([]domain.AppGroup, error) {
return c.service.GetByIdList(ctx, req.IdList)
}
// GetAll godoc
//
// @Tags application_group
// @Summary Получить группы приложений
// @Description Возвращает все группы приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.AppGroup
// @Failure 500 {object} apierrors.Error
// @Router /application_group/get_all [POST]
func (c AppGroup) GetAll(ctx context.Context) ([]domain.AppGroup, error) {
return c.service.GetAll(ctx)
}
+281 -161
View File
@@ -1,191 +1,311 @@
package controller
import (
"isp-system-service/entity"
"isp-system-service/model"
"context"
"fmt"
"github.com/integration-system/isp-lib/database"
"github.com/integration-system/isp-lib/utils"
"isp-system-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func GetApplications(list []int32) ([]*AppWithToken, error) {
res, err := model.AppRep.GetApplications(list)
if err != nil {
return nil, err
}
return enrichWithTokens(res...)
//nolint:interfacebloat
type ApplicationService interface {
GetById(ctx context.Context, appId int) (*domain.Application, error)
GetByToken(ctx context.Context, token string) (*domain.GetApplicationByTokenResponse, error)
GetByIdList(ctx context.Context, idList []int) ([]domain.Application, error)
GetByAppGroup(ctx context.Context, appGroupId int) ([]domain.Application, error)
CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, error)
Delete(ctx context.Context, idList []int) (int, error)
NextId(ctx context.Context) (int, error)
GetAll(ctx context.Context) ([]domain.Application, error)
Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.Application, error)
Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error)
}
func GetApplicationsByServiceId(identity Identity) ([]*AppWithToken, error) {
arr, err := model.AppRep.GetApplicationsByServiceId(identity.Id)
if err != nil {
return nil, err
}
return enrichWithTokens(arr...)
type Application struct {
service ApplicationService
}
func CreateUpdateApplication(app entity.Application) (*AppWithToken, error) {
existed, err := model.AppRep.GetApplicationByNameAndServiceId(app.Name, app.ServiceId)
if err != nil {
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 NewApplication(service ApplicationService) Application {
return Application{
service: service,
}
}
func GetApplicationById(identity Identity) (*AppWithToken, error) {
application, err := model.AppRep.GetApplicationById(identity.Id)
if err != nil {
// GetById godoc
//
// @Tags application
// @Summary Получить приложение по идентификатору
// @Description Возвращает описание приложения по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {object} domain.Application
// @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.Application, 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
}
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) {
if len(list) == 0 {
return DeleteResponse{}, status.Errorf(codes.InvalidArgument, "At least one id are required")
// GetByToken godoc
//
// @Tags application
// @Summary Получить идентификатор приложения и группы по токену
// @Description Возвращает идентификатор приложения и группы по токену
// @Accept json
// @Produce json
// @Param body body domain.GetApplicationByTokenRequest true "Тело запроса"
// @Success 200 {object} domain.GetApplicationByTokenResponse
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/get_application_by_token [POST]
func (c Application) GetByToken(ctx context.Context, req domain.GetApplicationByTokenRequest) (*domain.GetApplicationByTokenResponse, error) {
result, err := c.service.GetByToken(ctx, req.Token)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with token '%s' not found", req.Token),
err,
)
case err != nil:
return nil, err
default:
return result, nil
}
var count = 0
err := database.RunInTransaction(func(appRep model.AppRepository, tokenRep model.TokenRepository) error {
for _, appId := range list {
_, err := revokeTokensForApp(Identity{appId}, &tokenRep)
if err != nil {
return err
}
}
res, err := appRep.DeleteApplications(list)
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) {
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
if err != nil {
return nil, err
}
domains, err := model.DomainRep.GetDomainsBySystemId(int32(sysId))
if err != nil {
return nil, err
}
l := len(domains)
if l == 0 {
return []*DomainWithServices{}, nil
}
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
// GetByIdList godoc
//
// @Tags application
// @Summary Получить список приложений
// @Description Возвращает массив приложений их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {array} domain.Application
// @Failure 500 {object} apierrors.Error
// @Router /application/get_applications [POST]
func (c Application) GetByIdList(ctx context.Context, req []int) ([]domain.Application, error) {
return c.service.GetByIdList(ctx, req)
}
func enrichWithTokens(apps ...entity.Application) ([]*AppWithToken, error) {
l := len(apps)
if len(apps) == 0 {
return []*AppWithToken{}, nil
// GetByAppGroup godoc
//
// @Tags application
// @Summary Получить список приложений по идентификатору группы
// @Description Возвращает список приложений по идентификатору группы
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Тело запроса"
// @Success 200 {array} domain.Application
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/get_by_app_group [POST]
func (c Application) GetByAppGroup(ctx context.Context, req domain.Identity) ([]domain.Application, error) {
return c.service.GetByAppGroup(ctx, req.Id)
}
// CreateUpdate godoc
//
// @Tags application
// @Summary Создать/обновить приложение
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
// @Success 200 {object} domain.Application
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/create_update_application [POST]
func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, 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.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.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)
for i, a := range apps {
idList[i] = a.Id
awt := &AppWithToken{App: a}
appMap[a.Id] = awt
enriched[i] = awt
}
// Delete godoc
//
// @Tags application
// @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 /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 {
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.Application
// @Failure 400 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/create_application [POST]
func (c Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.Application, error) {
result, err := c.service.Create(ctx, req)
switch {
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("application group with id %d not found", req.ApplicationGroupId),
err,
)
case errors.Is(err, domain.ErrApplicationDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateName,
fmt.Sprintf("application with name %s already exists", req.Name),
err,
)
case errors.Is(err, domain.ErrApplicationDuplicateId):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateId,
fmt.Sprintf("application with id %d already exists", req.Id),
err,
)
default:
return result, err
}
}
// Update godoc
//
// @Tags application
// @Summary Обновить приложение
// @Description Если приложение с связкой `applicationGroupId`-`name` существует или приложение не найдено, то возвращает ошибку
// @Accept json
// @Produce json
// @Param body body domain.UpdateApplicationRequest true "Объект приложения"
// @Success 200 {object} domain.Application
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/update_application [POST]
func (c Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error) {
result, err := c.service.Update(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.OldId),
err,
)
case errors.Is(err, domain.ErrApplicationDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateName,
fmt.Sprintf("application with name %s already exists", req.Name),
err,
)
case errors.Is(err, domain.ErrApplicationDuplicateId):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateId,
fmt.Sprintf("application with id %d already exists", req.NewId),
err,
)
default:
return result, err
}
}
-87
View File
@@ -1,87 +0,0 @@
package controller
import (
"isp-system-service/entity"
"isp-system-service/model"
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
/*func GetDomains(list []int32) ([]entity.Domain, error) {
res, err := model.DomainRep.GetDomains(list)
if err != nil {
return res, err
}
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) {
existed, err := model.DomainRep.GetDomainByNameAndSystemId(domain.Name, domain.SystemId)
if err != nil {
return nil, err
}
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
if err != nil {
return nil, err
}
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) {
domain, err := model.DomainRep.GetDomainById(identity.Id)
if err != nil {
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) {
if len(list) == 0 {
return DeleteResponse{Deleted: 0}, status.Errorf(codes.InvalidArgument, "At least one id are required")
}
res, err := model.DomainRep.DeleteDomains(list)
return DeleteResponse{Deleted: res}, err
}
+85
View File
@@ -0,0 +1,85 @@
package controller
import (
"context"
"isp-system-service/domain"
"github.com/txix-open/isp-kit/errors"
)
type SecureService interface {
Authenticate(ctx context.Context, token string) (*domain.AuthData, error)
Authorize(ctx context.Context, req domain.AuthorizeRequest) (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)
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
}
}
-74
View File
@@ -1,74 +0,0 @@
package controller
import (
"isp-system-service/entity"
"isp-system-service/model"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func GetService(list []int32) ([]entity.Service, error) {
res, err := model.ServiceRep.GetServices(list)
if err != nil {
return res, err
}
return res, nil
}
func GetServicesByDomainId(identity Identity) ([]entity.Service, error) {
return model.ServiceRep.GetServicesByDomainId(identity.Id)
}
func CreateUpdateService(service entity.Service) (*entity.Service, error) {
existed, err := model.ServiceRep.GetServiceByNameAndDomainId(service.Name, service.DomainId)
if err != nil {
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) {
service, err := model.ServiceRep.GetServiceById(identity.Id)
if err != 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
}
+86 -190
View File
@@ -1,206 +1,102 @@
package controller
import (
"time"
"isp-system-service/conf"
"isp-system-service/entity"
"isp-system-service/model"
"context"
"fmt"
"github.com/go-redis/redis"
"github.com/integration-system/isp-lib/config"
"github.com/integration-system/isp-lib/redis"
"github.com/integration-system/isp-lib/token-gen"
"isp-system-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
SystemIdentityFieldInDb = "1"
DomainIdentityFieldInDb = "2"
ServiceIdentityFieldInDb = "3"
ApplicationIdentityFieldInDb = "4"
)
var (
generator = tg.NewGenerator(tg.DefaultAlphabet)
)
type BoolResponse struct {
Ok bool
type TokenService interface {
GetByAppId(ctx context.Context, appId int) ([]domain.Token, error)
Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error)
Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error)
RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error)
}
func CreateToken(req CreateTokenRequest) (*AppWithToken, error) {
m, err, app := GetIdMap(req.AppId)
if err != nil {
type Token struct {
service TokenService
}
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 err != nil:
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) {
app, err := model.AppRep.GetApplicationById(req.AppId)
if err != nil {
return nil, err
}
_, err = revokeTokens(req.Tokens, &model.TokenRep)
if err != nil {
return nil, err
}
res, err := enrichWithTokens(*app)
if err != nil {
return nil, err
}
return res[0], nil
// Revoke godoc
//
// @Tags token
// @Summary Отозвать токены
// @Description Отвязывает токены от приложений и удаляет их
// @Accept json
// @Produce json
// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 500 {object} apierrors.Error
// @Router /token/revoke_tokens [POST]
func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
return c.service.Revoke(ctx, req)
}
func RevokeTokensForApp(identity Identity) (*DeleteResponse, error) {
return revokeTokensForApp(identity, &model.TokenRep)
}
func GetTokensByAppId(identity Identity) ([]entity.Token, error) {
return model.TokenRep.GetTokensByAppId(identity.Id)
}
func SetIdentityMapForTokenV2(token string, expireTime int64, idMap map[string]interface{}) error {
c := rd.GetClient()
cfg := config.Get().(*conf.Configuration)
_, e := c.UseDbTx(rd.ApplicationTokenDb, func(p redis.Pipeliner) error {
t := fmt.Sprintf("%s|%s", token, cfg.InstanceUuid)
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
// RevokeForApp godoc
//
// @Tags token
// @Summary Отозвать токены для приложения
// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} apierrors.Error
// @Router /token/revoke_tokens_for_app [POST]
func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) {
return c.service.RevokeByAppId(ctx, req.Id)
}
+9
View File
@@ -0,0 +1,9 @@
package docs
import _ "embed"
// Embedded swagger files.
var (
//go:embed swagger.json
SwaggerJson []byte
)
+1693
View File
File diff suppressed because it is too large. Load diff
+39
View File
@@ -0,0 +1,39 @@
package domain
type AccessListSetOneRequest struct {
AppId int `validate:"required"`
HttpMethod string
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 {
HttpMethod string
Method string
Value bool
}
type AccessListDeleteListRequest struct {
AppId int `validate:"required"`
Methods []string `validate:"required,min=1"`
}
type AccessListDeleteV2ListRequest struct {
AppId int `validate:"required"`
Methods []Method `validate:"required,min=1"`
}
type Method struct {
HttpMethod string
Method string `validate:"required"`
}
+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"`
}
+57
View File
@@ -0,0 +1,57 @@
package domain
import (
"time"
)
const (
ApplicationSystemType = "SYSTEM"
ApplicationMobileType = "MOBILE"
)
type Application struct {
Id int
Name string
Description string
ApplicationGroupId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
}
type ApplicationCreateUpdateRequest struct {
Id int
Name string `validate:"required"`
Description string
ApplicationGroupId int `validate:"required"`
Type string `validate:"required,oneof=SYSTEM MOBILE"`
}
type ApplicationWithTokens struct {
App Application
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
}
type GetApplicationByTokenRequest struct {
Token string `validate:"required"`
}
type GetApplicationByTokenResponse struct {
ApplicationId int
ApplicationGroupId int
}
+11
View File
@@ -0,0 +1,11 @@
package domain
type (
Identity struct {
Id int `validate:"required"`
}
DeleteResponse struct {
Deleted int
}
)
+30
View File
@@ -0,0 +1,30 @@
package domain
import (
"github.com/txix-open/isp-kit/errors"
)
const (
ErrCodeInvalidRequest = 600
ErrCodeApplicationNotFound = 602
ErrCodeApplicationDuplicateName = 603
ErrCodeApplicationDuplicateId = 604
ErrCodeAppGroupNotFound = 605
ErrCodeAppGroupDuplicateName = 606
)
var (
ErrAppGroupNotFound = errors.New("application group not found")
ErrAppGroupDuplicateName = errors.New("application group name already exist")
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")
)
+26
View File
@@ -0,0 +1,26 @@
package domain
type AuthenticateRequest struct {
Token string `validate:"required"`
}
type AuthenticateResponse struct {
Authenticated bool
ErrorReason string
AuthData *AuthData
}
type AuthData struct {
AppName string
ApplicationId int
}
type AuthorizeRequest struct {
ApplicationId int `validate:"required"`
HttpMethod string
Endpoint string `validate:"required"`
}
type AuthorizeResponse struct {
Authorized bool
}
+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"`
}
+13
View File
@@ -0,0 +1,13 @@
package entity
type AccessList struct {
AppId int
HttpMethod string
Method string
Value bool
}
type Method struct {
HttpMethod string
Method string
}
+14
View File
@@ -0,0 +1,14 @@
package entity
import (
"database/sql"
"time"
)
type AppGroup struct {
Id int
Name string
Description sql.NullString
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
}
-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
}
+19
View File
@@ -0,0 +1,19 @@
package entity
import (
"time"
)
type Token struct {
Token string
AppId int
ExpireTime int
CreatedAt time.Time
}
type AuthData struct {
AppName string
AppId int
ExpireTime int
CreatedAt time.Time
}
+81
View File
@@ -0,0 +1,81 @@
module isp-system-service
go 1.26.0
require (
github.com/Masterminds/squirrel v1.5.4
github.com/jackc/pgx/v5 v5.10.0
github.com/stretchr/testify v1.11.1
github.com/txix-open/isp-kit v1.74.0
github.com/txix-open/jsonschema v1.3.0
google.golang.org/grpc v1.83.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.6.0 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.15 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/getsentry/sentry-go v0.48.0 // indirect
github.com/go-faker/faker/v4 v4.10.1 // indirect
github.com/go-logr/logr v1.4.4 // 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.29.0 // 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.19.1 // 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.5.0 // indirect
github.com/mailru/easyjson v0.9.2 // 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.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/pressly/goose/v3 v3.27.3 // indirect
github.com/prometheus/client_golang v1.24.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/sethvargo/go-retry v0.4.0 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/etp/v4 v4.1.3 // indirect
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // 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.2.1 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
golang.org/x/crypto v0.54.0 // indirect
golang.org/x/net v0.57.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.40.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+232
View File
@@ -0,0 +1,232 @@
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
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.6.0 h1:IHTgLjkgckOjAp8p0aYfXkv+cqC+zrzALg/JywnPjxY=
github.com/buger/jsonparser v1.6.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
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.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/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.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/getsentry/sentry-go v0.48.0 h1:FRZNr7Uk1C86ev1bSJmYlUkL9oyivQA6YOcdYfaaMmY=
github.com/getsentry/sentry-go v0.48.0/go.mod h1:E5UkA5wp1qR2+MDydNYlVeUiNN2xEdjYMidkgf0Qoss=
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.10.1 h1:mGH3y0X8AfrXsfgPsPuTkWBYIebomvdkWEN1uDLoFFg=
github.com/go-faker/faker/v4 v4.10.1/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/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.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/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.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/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.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
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.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
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.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
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.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
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 v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/rabbitmq/amqp091-go v1.13.0 h1:L8NA1WtF76C6KA3LAoufjfLgbist/If1UQYcsOjtxXA=
github.com/rabbitmq/amqp091-go v1.13.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.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo=
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.74.0 h1:Gi1X8Jnf9ppV4TXq4kMCBgBjJjqSKh57X8038I+tQFw=
github.com/txix-open/isp-kit v1.74.0/go.mod h1:Kob233jk1j/Js7UmopJ5b7JpVZrpWbagEAjasgfqTdk=
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/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.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 h1:MCcYL7J6Vt/X0kjqbMZkekCmwsurbQRbL69vkiye2lk=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0/go.mod h1:3jnStNwSufK+f5ktjL4EPcwtig4rtd81NS70lqHuXl8=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
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.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 h1:ybvH/ZpOcpCrjtkb7oW/fdlzbEmRVeumw19SRQmNFKU=
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0/go.mod h1:HJ9MpJLeDSstBkx1LILTpd5f41ADSMZcTPypw02qEGw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 h1:mJiOtnGp0k/BcSgdu03G2NwnscCfCH+h2QKUBZr18KI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 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.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
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.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
-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 -90
View File
@@ -1,107 +1,49 @@
package main
import (
"os"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/helper"
"isp-system-service/model"
"isp-system-service/routes"
_ "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"
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/shutdown"
)
var (
version = "0.1.0"
date = "undefined"
version = "1.0.0"
)
// @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 -pd -ot json -eot json
func main() {
bootstrap.
ServiceBootstrap(&conf.Configuration{}, &conf.RemoteConfig{}).
OnLocalConfigLoad(onLocalConfigLoad).
SocketConfiguration(socketConfiguration).
DeclareMe(routesData).
OnRemoteConfigReceive(onRemoteConfigReceive).
OnShutdown(onShutdown).
Run()
}
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport)
app := boot.App
logger := app.Logger()
/*func ensureRootToken() {
tokens, err := model.TokenRep.GetTokensByAppId(entity.RootAdminApplicationId)
assembly, err := assembly.New(boot)
if err != nil {
logger.Error(err)
return
logger.Fatal(app.Context(), err)
}
if len(tokens) > 0 {
m, err, _ := controller.GetIdMap(entity.RootAdminApplicationId)
if err != nil {
logger.Error(err)
return
}
for _, token := range tokens {
err = controller.SetIdentityMapForToken(token, m)
if err != nil {
logger.Error(err)
continue
}
}
}
}*/
app.AddRunners(assembly.Runners()...)
app.AddClosers(assembly.Closers()...)
func socketConfiguration(cfg interface{}) socket.SocketConfiguration {
appConfig := cfg.(*conf.Configuration)
return socket.SocketConfiguration{
Host: appConfig.ConfigServiceAddress.IP,
Port: appConfig.ConfigServiceAddress.Port,
Secure: false,
UrlParams: map[string]string{
"module_name": appConfig.ModuleName,
"instance_uuid": appConfig.InstanceUuid,
},
}
}
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(),
shutdown.On(func() {
logger.Info(app.Context(), "starting shutdown")
app.Shutdown()
logger.Info(app.Context(), "shutdown completed")
})
err = app.Run()
if err != nil {
boot.Fatal(err)
}
}
@@ -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
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
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');
@@ -0,0 +1,36 @@
-- +goose Up
CREATE TABLE access_list_new
(
app_id INT,
http_method VARCHAR(255) NOT NULL DEFAULT '',
method VARCHAR(255),
value BOOLEAN NOT NULL,
PRIMARY KEY (app_id, http_method, method),
CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO access_list_new (app_id, method, value)
SELECT app_id, method, value
FROM access_list
WHERE value = true;
DROP TABLE access_list;
ALTER TABLE access_list_new RENAME TO access_list;
-- +goose Down
CREATE TABLE access_list_old
(
app_id INT,
method VARCHAR(255),
value BOOLEAN NOT NULL,
PRIMARY KEY (app_id, method),
CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO access_list_old (app_id, method, value)
SELECT app_id, method, value
FROM access_list
WHERE value = true;
DROP TABLE access_list;
ALTER TABLE access_list_old RENAME TO access_list;
@@ -0,0 +1,90 @@
-- +goose Up
ALTER TABLE application_group
DROP CONSTRAINT fk_domain_id__domain_id;
ALTER TABLE application_group
DROP CONSTRAINT uq_name_domain_name;
ALTER TABLE application_group
DROP COLUMN domain_id;
ALTER TABLE application_group
ADD CONSTRAINT uq_application_group_name UNIQUE ("name");
ALTER TABLE domain
DROP CONSTRAINT fk_system_id__system_id;
ALTER TABLE domain
DROP CONSTRAINT uq_name_system_id;
DROP TABLE domain;
DROP TABLE system;
-- +goose Down
CREATE TABLE system (
id SERIAL4 NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
created_at TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
updated_at TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
CONSTRAINT UQ_name UNIQUE (name)
);
CREATE TABLE domain (
id SERIAL4 NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
system_id INTEGER NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
updated_at TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
CONSTRAINT FK_system_id__system_id
FOREIGN KEY (system_id)
REFERENCES system (id)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT UQ_name_system_id UNIQUE (name, system_id)
);
-- Восстанавливаем root system/domain.
INSERT INTO system (id, name)
VALUES (1, 'rootSystem');
SELECT setval(
'system_id_seq',
GREATEST((SELECT COALESCE(MAX(id), 1) FROM system), 1)
);
INSERT INTO domain (id, name, system_id)
VALUES (1, 'root', 1);
SELECT setval(
'domain_id_seq',
GREATEST((SELECT COALESCE(MAX(id), 1) FROM domain), 1)
);
ALTER TABLE application_group
DROP CONSTRAINT uq_application_group_name;
ALTER TABLE application_group
ADD COLUMN domain_id INTEGER DEFAULT 1;
ALTER TABLE application_group
ALTER COLUMN domain_id SET NOT NULL;
ALTER TABLE application_group
ADD CONSTRAINT FK_domain_id__domain_id
FOREIGN KEY (domain_id)
REFERENCES domain (id)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE application_group
ADD CONSTRAINT UQ_name_domain_name
UNIQUE (name, domain_id);
CREATE TRIGGER modify_system
BEFORE UPDATE OR INSERT ON system
FOR EACH ROW EXECUTE PROCEDURE update_created_modified_column_date();
CREATE TRIGGER modify_domain
BEFORE UPDATE OR INSERT ON domain
FOR EACH ROW EXECUTE PROCEDURE update_created_modified_column_date();
-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
}
+182
View File
@@ -0,0 +1,182 @@
package repository
import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
type AccessList struct {
db db.DB
}
func NewAccessList(db db.DB) AccessList {
return AccessList{
db: db,
}
}
func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, httpMethod string, method string) (*entity.AccessList, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppIdAndMethod")
q := `
SELECT app_id, http_method, method, value
FROM access_list
WHERE app_id = $1
AND method = $2
AND http_method IN ($3, '')
ORDER BY (http_method = $3) DESC
LIMIT 1;
`
result := entity.AccessList{}
err := r.db.SelectRow(ctx, &result, q, appId, method, httpMethod)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAccessListNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppId")
q := `
SELECT app_id, http_method, 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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppIdList")
q, args, err := query.New().
Select("app_id", "http_method", "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 {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.InsertArrayAccessList")
qBuilder := query.New().
Insert("access_list").
Columns("app_id", "http_method", "method", "value")
for _, e := range entity {
qBuilder = qBuilder.Values(e.AppId, e.HttpMethod, 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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.UpsertAccessList")
q := `
INSERT INTO access_list
(app_id, http_method, method, value)
VALUES ($1, $2, $3, $4)
ON CONFLICT (app_id, http_method, method)
DO UPDATE
SET (value) = (SELECT EXCLUDED.value)
`
result, err := r.db.Exec(ctx, q, e.AppId, e.HttpMethod, 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 []entity.Method) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.DeleteAccessList")
methodsClause := make(squirrel.Or, 0, len(methods))
for _, method := range methods {
methodsClause = append(methodsClause, squirrel.And{
squirrel.Eq{"method": method.Method},
squirrel.Eq{"http_method": method.HttpMethod},
})
}
q, args, err := query.New().
Delete("access_list").
Where(squirrel.And{
squirrel.Eq{
"app_id": appId,
},
methodsClause,
}).
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.DeleteAccessListByAppId")
q := `
DELETE FROM access_list
WHERE app_id = $1
RETURNING app_id, http_method, 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
}
+183
View File
@@ -0,0 +1,183 @@
package repository
import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5/pgconn"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
const (
applicationGroupUniqueNameConstraint = "uq_application_group_name"
)
type AppGroup struct {
db db.DB
}
func NewAppGroup(db db.DB) AppGroup {
return AppGroup{
db: db,
}
}
func (r AppGroup) GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupById")
q := `
SELECT id, name, description, created_at, updated_at
FROM application_group
WHERE id = $1
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, id)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAppGroupNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByIdList")
q, arg, err := query.New().
Select("id", "name", "description", "created_at", "updated_at").
From("application_group").
Where(squirrel.Eq{"id": idList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.AppGroup, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
return result, nil
}
func (r AppGroup) GetAppGroupByName(ctx context.Context, name string) (*entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByName")
q := `
SELECT id, name, description, created_at, updated_at
FROM application_group
WHERE name = $1
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, name)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAppGroupNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.CreateAppGroup")
q := `
INSERT INTO application_group
(name, description)
VALUES ($1, $2)
ON CONFLICT (name) DO NOTHING
RETURNING id, name, description, created_at, updated_at
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, name, desc)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAppGroupDuplicateName
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.UpdateAppGroup")
q := `
UPDATE application_group
SET name = $1, description = $2
WHERE id = $3
RETURNING id, name, description, created_at, updated_at
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
var pgErr *pgconn.PgError
switch {
case errors.As(err, &pgErr) && pgErr.ConstraintName == applicationGroupUniqueNameConstraint:
return nil, domain.ErrAppGroupDuplicateName
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAppGroupNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.DeleteAppGroup")
q, args, err := query.New().
Delete("application_group").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec query %s", q)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
func (r AppGroup) GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAllAppGroups")
q, arg, err := query.New().
Select("id", "name", "description", "created_at", "updated_at").
From("application_group").
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.AppGroup, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
return result, nil
}
+261
View File
@@ -0,0 +1,261 @@
package repository
import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5/pgconn"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
const (
applicationPkConstraintName = "application_pkey"
applicationUniqueNameConstraintName = "uq_name_application_group_id"
applicationFkAppGroupConstraintName = "fk_application_group_id"
)
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationById")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByIdList")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByAppGroupIdList")
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) CreateApplication(
ctx context.Context,
id int,
name string,
desc string,
appGroupId int,
appType string,
) (*entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.CreateApplication")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.UpdateApplication")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.UpdateApplicationWithNewId")
q := `
UPDATE application
SET id = $2,
name = $3,
description = $4
WHERE id = $1
RETURNING id, name, description, application_group_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, oldId, newId, name, description)
if err != nil {
return nil, r.handleUpdateError(err, q)
}
return &result, nil
}
func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.DeleteApplicationByIdList")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.NextApplicationId")
q := `SELECT COALESCE(MAX(id)+1, 1) FROM application;`
nextAppId := 0
err := r.db.SelectRow(ctx, &nextAppId, q)
if err != nil {
return -1, errors.WithMessagef(err, "exec query %s", q)
}
return nextAppId, nil
}
func (r Application) GetAllApplications(ctx context.Context) ([]entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetAllApplications")
q, args, err := query.New().
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
From("application").
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
result := make([]entity.Application, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
return result, nil
}
func (r Application) handleCreateError(err error, q string) error {
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return errors.WithMessagef(err, "exec query %s", q)
}
switch pgErr.ConstraintName {
case applicationPkConstraintName:
return domain.ErrApplicationDuplicateId
case applicationUniqueNameConstraintName:
return domain.ErrApplicationDuplicateName
case applicationFkAppGroupConstraintName:
return domain.ErrAppGroupNotFound
}
return errors.WithMessagef(err, "exec query %s", q)
}
func (r Application) handleUpdateError(err error, q string) error {
if errors.Is(err, sql.ErrNoRows) {
return domain.ErrApplicationNotFound
}
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return errors.WithMessagef(err, "exec query %s", q)
}
switch pgErr.ConstraintName {
case applicationPkConstraintName:
return domain.ErrApplicationDuplicateId
case applicationUniqueNameConstraintName:
return domain.ErrApplicationDuplicateName
default:
return errors.WithMessagef(err, "exec query %s", q)
}
}
+40
View File
@@ -0,0 +1,40 @@
package repository
import (
"context"
"hash/fnv"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
const (
prefix = "msp-service-template"
)
type Locker struct {
db db.DB
}
func NewLocker(db db.DB) Locker {
return Locker{db: db}
}
func (l Locker) TryLock(ctx context.Context, key string) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Locker.TryLock")
hash := fnv.New32a()
_, err := hash.Write([]byte(prefix + key))
if err != nil {
return false, errors.WithMessage(err, "generate hash")
}
sum := hash.Sum32()
acquired := false
err = l.db.SelectRow(ctx, &acquired, "SELECT pg_try_advisory_xact_lock($1)", sum)
if err != nil {
return false, errors.WithMessage(err, "pg try acquire advisory lock")
}
return acquired, nil
}
+131
View File
@@ -0,0 +1,131 @@
package repository
import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
type Token struct {
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.SaveToken")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.GetTokenById")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.GetTokenByAppIdList")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.DeleteToken")
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) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.AuthDataByToken")
q := `
SELECT app_id, application.name AS app_name , token.expire_time, token.created_at
FROM token
LEFT JOIN application
ON token.app_id = application.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
}
}
+230
View File
@@ -0,0 +1,230 @@
package routes
import (
"isp-system-service/controller"
"isp-system-service/docs"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/common_endpoints"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
)
type Controllers struct {
AccessList controller.AccessList
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 concatEndpoints(
secureCluster(c),
accessListCluster(c),
applicationCluster(c),
tokenCluster(c),
applicationGroupCluster(c),
commonEndpoints(),
)
}
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,
Extra: cluster.RequireAdminPermission("app_access_view"),
Handler: c.AccessList.GetById,
},
{
Path: "system/access_list/set_one",
Inner: true,
Extra: cluster.RequireAdminPermission("app_access_edit"),
Handler: c.AccessList.SetOne,
},
{
Path: "system/access_list/set_list",
Inner: true,
Extra: cluster.RequireAdminPermission("app_access_edit"),
Handler: c.AccessList.SetList,
},
{
Path: "system/access_list/delete_list",
Inner: true,
Extra: cluster.RequireAdminPermission("app_access_edit"),
Handler: c.AccessList.DeleteList,
},
{
Path: "system/access_list/delete_list_with_methods",
Inner: true,
Extra: cluster.RequireAdminPermission("app_access_edit"),
Handler: c.AccessList.DeleteListWithMethods,
},
}
}
func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/application/get_applications",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_view"),
Handler: c.Application.GetByIdList,
},
{
Path: "system/application/get_by_app_group",
Extra: cluster.RequireAdminPermission("application_group_view"),
Inner: true,
Handler: c.Application.GetByAppGroup,
},
{
Path: "system/application/create_update_application",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_app_edit"),
Handler: c.Application.CreateUpdate,
},
{
Path: "system/application/get_application_by_id",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_view"),
Handler: c.Application.GetById,
},
{
Path: "system/application/get_application_by_token",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_view"),
Handler: c.Application.GetByToken,
},
{
Path: "system/application/delete_applications",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_app_delete"),
Handler: c.Application.Delete,
},
{
Path: "system/application/next_id",
Inner: true,
Handler: c.Application.NextId,
},
{
Path: "system/application/get_all",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_view"),
Handler: c.Application.GetAll,
},
{
Path: "system/application/create_application",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_app_add"),
Handler: c.Application.Create,
}, {
Path: "system/application/update_application",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_app_edit"),
Handler: c.Application.Update,
},
}
}
func tokenCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/token/create_token",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_token_add"),
Handler: c.Token.Create,
},
{
Path: "system/token/revoke_tokens",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_token_delete"),
Handler: c.Token.Revoke,
},
{
Path: "system/token/revoke_tokens_for_app",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_token_delete"),
Handler: c.Token.RevokeForApp,
},
{
Path: "system/token/get_tokens_by_app_id",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_token_view"),
Handler: c.Token.GetByAppId,
},
}
}
func applicationGroupCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/application_group/create",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_add"),
Handler: c.AppGroup.Create,
}, {
Path: "system/application_group/update",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_edit"),
Handler: c.AppGroup.Update,
}, {
Path: "system/application_group/delete_list",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_delete"),
Handler: c.AppGroup.DeleteList,
}, {
Path: "system/application_group/get_by_id_list",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_view"),
Handler: c.AppGroup.GetByIdList,
}, {
Path: "system/application_group/get_all",
Inner: true,
Extra: cluster.RequireAdminPermission("application_group_view"),
Handler: c.AppGroup.GetAll,
},
}
}
func commonEndpoints() []cluster.EndpointDescriptor {
return common_endpoints.CommonEndpoints(
"system",
common_endpoints.WithSwaggerEndpoint(docs.SwaggerJson),
)
}
func concatEndpoints(endpoints ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
var result []cluster.EndpointDescriptor
for _, c := range endpoints {
result = append(result, c...)
}
return result
}
+193
View File
@@ -0,0 +1,193 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/txix-open/isp-kit/errors"
)
type AccessListRepo interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) 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 []entity.Method) 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{
HttpMethod: access.HttpMethod,
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,
HttpMethod: request.HttpMethod,
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([]entity.Method, len(req.Methods))
for i, m := range req.Methods {
updateMethods[i] = entity.Method{
HttpMethod: m.HttpMethod,
Method: m.Method,
}
newAccessList[i] = entity.AccessList{
AppId: req.AppId,
HttpMethod: m.HttpMethod,
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{
HttpMethod: access.HttpMethod,
Method: access.Method,
Value: access.Value,
}
}
return methodInfos, nil
}
func (s AccessList) DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error {
methods := make([]domain.Method, 0, len(req.Methods))
for _, method := range req.Methods {
methods = append(methods, domain.Method{Method: method})
}
return s.DeleteListWithMethods(ctx, domain.AccessListDeleteV2ListRequest{
AppId: req.AppId,
Methods: methods,
})
}
func (s AccessList) DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error {
_, err := s.appRepo.GetApplicationById(ctx, req.AppId)
if err != nil {
return errors.WithMessage(err, "get application by id")
}
methods := make([]entity.Method, 0, len(req.Methods))
for _, method := range req.Methods {
methods = append(methods, entity.Method{Method: method.Method, HttpMethod: method.HttpMethod})
}
err = s.accessListRepo.DeleteAccessList(ctx, req.AppId, methods)
if err != nil {
return errors.WithMessage(err, "delete access_list")
}
return nil
}
+81
View File
@@ -0,0 +1,81 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/txix-open/isp-kit/errors"
)
type AppGroup struct {
repo AppGroupRepo
}
func NewAppGroup(repo AppGroupRepo) AppGroup {
return AppGroup{
repo: repo,
}
}
func (s AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) {
appGroup, err := s.repo.CreateAppGroup(ctx, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "create appGroup")
}
converted := s.convertAppGroup(*appGroup)
return &converted, nil
}
func (s AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) {
appGroup, err := s.repo.UpdateAppGroup(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update appGroup")
}
converted := s.convertAppGroup(*appGroup)
return &converted, nil
}
func (s AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) {
deleted, err := s.repo.DeleteAppGroup(ctx, req.IdList)
if err != nil {
return nil, errors.WithMessage(err, "delete appGroup")
}
return &domain.DeleteResponse{
Deleted: deleted,
}, nil
}
func (s AppGroup) GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error) {
appGroups, err := s.repo.GetAppGroupByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get appGroups by id list")
}
result := make([]domain.AppGroup, 0, len(appGroups))
for _, appGroup := range appGroups {
result = append(result, s.convertAppGroup(appGroup))
}
return result, nil
}
func (s AppGroup) GetAll(ctx context.Context) ([]domain.AppGroup, error) {
appGroups, err := s.repo.GetAllAppGroups(ctx)
if err != nil {
return nil, errors.WithMessage(err, "get all appGroups")
}
result := make([]domain.AppGroup, 0, len(appGroups))
for _, appGroup := range appGroups {
result = append(result, s.convertAppGroup(appGroup))
}
return result, nil
}
func (s AppGroup) convertAppGroup(appGroup entity.AppGroup) domain.AppGroup {
return domain.AppGroup{
Id: appGroup.Id,
Name: appGroup.Name,
Description: appGroup.Description.String,
CreatedAt: appGroup.CreatedAt,
UpdatedAt: appGroup.UpdatedAt,
}
}
+216
View File
@@ -0,0 +1,216 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/txix-open/isp-kit/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
serviceRepo AppGroupRepo
tokenRepo TokenRepo
}
func NewApplication(
txRunner ApplicationTxRunner,
applicationRepo ApplicationRepo,
appGroupRepo AppGroupRepo,
tokenRepo TokenRepo,
) Application {
return Application{
txRunner: txRunner,
appRepo: applicationRepo,
serviceRepo: appGroupRepo,
tokenRepo: tokenRepo,
}
}
func (s Application) GetById(ctx context.Context, appId int) (*domain.Application, error) {
app, err := s.appRepo.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
return new(s.convertApplication(*app)), nil
}
func (s Application) GetByToken(ctx context.Context, tokenStr string) (*domain.GetApplicationByTokenResponse, error) {
token, err := s.tokenRepo.GetTokenById(ctx, tokenStr)
if err != nil {
return nil, errors.WithMessage(err, "get token by id")
}
if token == nil {
return nil, domain.ErrApplicationNotFound
}
app, err := s.appRepo.GetApplicationById(ctx, token.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get app by id")
}
return &domain.GetApplicationByTokenResponse{
ApplicationId: app.Id,
ApplicationGroupId: app.ApplicationGroupId,
}, nil
}
func (s Application) GetByIdList(ctx context.Context, idList []int) ([]domain.Application, error) {
apps, err := s.appRepo.GetApplicationByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get application by id list")
}
result := make([]domain.Application, len(apps))
for i, a := range apps {
result[i] = s.convertApplication(a)
}
return result, nil
}
func (s Application) GetByAppGroup(ctx context.Context, appGroupId int) ([]domain.Application, error) {
apps, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, []int{appGroupId})
if err != nil {
return nil, errors.WithMessage(err, "get apps by app group ids")
}
result := make([]domain.Application, len(apps))
for i, a := range apps {
result[i] = s.convertApplication(a)
}
return result, nil
}
func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, error) {
if req.Id != 0 {
app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update application")
}
return new(s.convertApplication(*app)), nil
}
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.ApplicationGroupId, req.Type)
if err != nil {
return nil, errors.WithMessage(err, "create application")
}
return new(s.convertApplication(*app)), 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.Application, error) {
app, err := s.appRepo.CreateApplication(ctx, req.Id, req.Name, req.Description, req.ApplicationGroupId, req.Type)
if err != nil {
return nil, errors.WithMessage(err, "create application")
}
return new(s.convertApplication(*app)), nil
}
func (s Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error) {
app, err := s.appRepo.UpdateApplicationWithNewId(ctx, req.OldId, req.NewId, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update application")
}
return new(s.convertApplication(*app)), nil
}
func (s Application) convertApplication(req entity.Application) domain.Application {
return domain.Application{
Id: req.Id,
Name: req.Name,
Description: req.Description.String,
ApplicationGroupId: req.ApplicationGroupId,
Type: req.Type,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
}
+104
View File
@@ -0,0 +1,104 @@
package baseline
import (
"context"
"isp-system-service/conf"
"isp-system-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
const adminAppId = 1
type Transaction interface {
CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error)
CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error)
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
GetTokenById(ctx context.Context, token string) (*entity.Token, error)
TryLock(ctx context.Context, key string) (bool, error)
}
type TxRunner interface {
BaselineTx(ctx context.Context, tx func(ctx context.Context, tx Transaction) error) error
}
type Service struct {
cfg conf.Baseline
txRunner TxRunner
logger log.Logger
}
func NewService(cfg conf.Baseline, txRunner TxRunner, logger log.Logger) Service {
return Service{
cfg: cfg,
txRunner: txRunner,
logger: logger,
}
}
func (s Service) Do(ctx context.Context) error {
ctx = log.ToContext(ctx, log.String("worker", "baseline"))
if s.cfg.InitialAdminUiToken == "" {
s.logger.Info(ctx, "initial admin ui token is empty, skip baseline")
return nil
}
err := s.txRunner.BaselineTx(ctx, s.transaction)
if err != nil {
return errors.WithMessage(err, "run baseline transaction")
}
return nil
}
func (s Service) transaction(ctx context.Context, tx Transaction) error {
locked, err := tx.TryLock(ctx, "isp-system-service.baseline")
if err != nil {
return errors.WithMessage(err, "try lock isp-system-service.baseline")
}
if !locked {
s.logger.Info(ctx, "baseline is locked, skip baseline")
return nil
}
token, err := tx.GetTokenById(ctx, s.cfg.InitialAdminUiToken)
if err != nil {
return errors.WithMessage(err, "get token by id")
}
if token != nil {
s.logger.Info(ctx, "initial admin ui token is exist, skip baseline")
return nil
}
s.logger.Info(ctx, "initial admin ui token is empty, run baseline")
service, err := tx.CreateAppGroup(ctx, "rootService", "")
if err != nil {
return errors.WithMessage(err, "create service")
}
app, err := tx.CreateApplication(ctx, adminAppId, "admin", "", service.Id, "SYSTEM")
if err != nil {
return errors.WithMessage(err, "create application")
}
_, err = tx.SaveToken(ctx, s.cfg.InitialAdminUiToken, app.Id, -1)
if err != nil {
return errors.WithMessage(err, "save token")
}
_, err = tx.UpsertAccessList(ctx, entity.AccessList{
AppId: app.Id,
Method: "admin/auth/login",
Value: true,
})
if err != nil {
return errors.WithMessage(err, "upsert access list")
}
s.logger.Info(ctx, "baseline done")
return nil
}
+32
View File
@@ -0,0 +1,32 @@
package service
import (
"context"
"isp-system-service/entity"
)
type TokenRepo interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
GetTokenById(ctx context.Context, token string) (*entity.Token, error)
}
type ApplicationRepo interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error)
GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error)
CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error)
UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error)
UpdateApplicationWithNewId(ctx context.Context, oldId int, newId int, name string, description string) (*entity.Application, error)
NextApplicationId(ctx context.Context) (int, error)
GetAllApplications(ctx context.Context) ([]entity.Application, error)
}
type AppGroupRepo interface {
GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error)
GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error)
GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error)
GetAppGroupByName(ctx context.Context, name string) (*entity.AppGroup, error)
CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error)
UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error)
DeleteAppGroup(ctx context.Context, idList []int) (int, error)
}
+65
View File
@@ -0,0 +1,65 @@
package secure
import (
"context"
"time"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/txix-open/isp-kit/errors"
)
type TokenRep interface {
AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error)
}
type AccessListRep interface {
GetAccessListByAppIdAndMethod(ctx context.Context, appId int, httpMethod string, 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{
AppName: authData.AppName,
ApplicationId: authData.AppId,
}, nil
}
func (s Service) Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error) {
accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod(
ctx,
req.ApplicationId,
req.HttpMethod,
req.Endpoint,
)
if err != nil {
return false, errors.WithMessage(err, "get access list by app_id and method")
}
return accessList.Value, nil
}
+157
View File
@@ -0,0 +1,157 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/txix-open/isp-kit/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
tokenRepo TokenRepo
}
func NewToken(
jwtGenerate ApplicationTokenCreator,
appEnricher AppEnricher,
tx TokenTxRunner,
appRepo ApplicationRepo,
tokenRepo TokenRepo,
) Token {
return Token{
appEnricher: appEnricher,
jwt: jwtGenerate,
tx: tx,
appRepo: appRepo,
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")
}
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/txix-open/isp-kit/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
}
+223
View File
@@ -0,0 +1,223 @@
package tests_test
import (
"testing"
"github.com/txix-open/isp-kit/dbx"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/repository"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
)
func TestAccessListSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &AccessListSuite{})
}
type AccessListSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
api *client.Client
accessListRepo repository.AccessList
appId int
}
func (s *AccessListSuite) SetupTest() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{})
_, s.api = grpct.TestServer(s.test, config.Handler)
s.accessListRepo = repository.NewAccessList(s.testDb)
appGroup, err := repository.NewAppGroup(s.testDb).CreateAppGroup(
s.T().Context(),
fake.It[string](),
fake.It[string](),
)
s.Require().NoError(err)
s.appId = fake.It[int]()
_, err = repository.NewApplication(s.testDb).CreateApplication(
s.T().Context(),
s.appId,
fake.It[string](),
fake.It[string](),
appGroup.Id,
domain.ApplicationSystemType,
)
s.Require().NoError(err)
}
func (s *AccessListSuite) TestGetById_HappyPath() {
expectedAccessList := []entity.AccessList{
{
AppId: s.appId,
Method: fake.It[string](),
Value: false,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
}
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), expectedAccessList)
s.Require().NoError(err)
req := domain.Identity{
Id: s.appId,
}
var accessList []domain.MethodInfo
err = s.api.Invoke("system/access_list/get_by_id").
JsonRequestBody(&req).
JsonResponseBody(&accessList).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Len(accessList, len(expectedAccessList))
actualAccessList := s.convertAccessList(accessList)
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
}
func (s *AccessListSuite) TestSetOne_HappyPath() {
expectedAccessList := []entity.AccessList{
{
AppId: s.appId,
Method: fake.It[string](),
Value: false,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
}
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), expectedAccessList)
s.Require().NoError(err)
req := domain.AccessListSetOneRequest{
AppId: s.appId,
Method: expectedAccessList[0].Method,
Value: true,
}
err = s.api.Invoke("system/access_list/set_one").
JsonRequestBody(&req).
Do(s.T().Context())
s.Require().NoError(err)
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
s.Require().NoError(err)
for i := range expectedAccessList {
expectedAccessList[i].Value = true
}
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
}
func (s *AccessListSuite) TestSetList_HappyPath() {
req := domain.AccessListSetListRequest{
AppId: s.appId,
Methods: []domain.MethodInfo{
{
Method: fake.It[string](),
Value: true,
},
{
Method: fake.It[string](),
Value: true,
},
},
}
err := s.api.Invoke("system/access_list/set_list").
JsonRequestBody(&req).
Do(s.T().Context())
s.Require().NoError(err)
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
s.Require().NoError(err)
s.Require().Len(actualAccessList, len(req.Methods))
expectedAccessList := s.convertAccessList(req.Methods)
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
}
func (s *AccessListSuite) TestDeleteList_HappyPath() {
accessList := []entity.AccessList{
{
AppId: s.appId,
Method: fake.It[string](),
Value: false,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
}
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), accessList)
s.Require().NoError(err)
req := domain.AccessListDeleteListRequest{
AppId: s.appId,
Methods: []string{
accessList[0].Method,
accessList[1].Method,
},
}
err = s.api.Invoke("system/access_list/delete_list").
JsonRequestBody(&req).
Do(s.T().Context())
s.Require().NoError(err)
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
s.Require().NoError(err)
s.Require().Len(actualAccessList, 1)
s.Require().Equal(accessList[2], actualAccessList[0])
}
func (s *AccessListSuite) convertAccessList(methods []domain.MethodInfo) []entity.AccessList {
converted := make([]entity.AccessList, 0, len(methods))
for _, method := range methods {
converted = append(converted, entity.AccessList{
AppId: s.appId,
Method: method.Method,
Value: method.Value,
})
}
return converted
}
+275
View File
@@ -0,0 +1,275 @@
package tests_test
import (
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/repository"
"testing"
"time"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/apierrors"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
)
func TestApplicationGroupSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &AppGroupSuite{})
}
type AppGroupSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
appGroupRepo repository.AppGroup
api *client.Client
}
func (s *AppGroupSuite) SetupTest() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{})
_, s.api = grpct.TestServer(s.test, config.Handler)
s.appGroupRepo = repository.NewAppGroup(s.testDb)
}
func (s *AppGroupSuite) TestGetByIdList() {
toGenerate := 10
appGroups := make([]domain.AppGroup, 0, toGenerate)
ids := make([]int, 0, toGenerate)
for range 10 {
appGroup := s.createAppGroup()
appGroups = append(appGroups, domain.AppGroup{
Id: appGroup.Id,
Name: appGroup.Name,
Description: appGroup.Description.String,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
ids = append(ids, appGroup.Id)
}
result := []domain.AppGroup{}
apiReq := domain.IdListRequest{IdList: ids}
err := s.api.Invoke("system/application_group/get_by_id_list").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(appGroups, result)
}
func (s *AppGroupSuite) TestGetByIdList_EmptyDescription() {
toGenerate := 10
appGroups := make([]domain.AppGroup, 0, toGenerate)
ids := make([]int, 0, toGenerate)
for range 10 {
appGroup, err := s.appGroupRepo.CreateAppGroup(
s.T().Context(),
fake.It[string](),
"",
)
s.Require().NoError(err)
appGroups = append(appGroups, domain.AppGroup{
Id: appGroup.Id,
Name: appGroup.Name,
Description: "",
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
ids = append(ids, appGroup.Id)
}
result := []domain.AppGroup{}
apiReq := domain.IdListRequest{IdList: ids}
err := s.api.Invoke("system/application_group/get_by_id_list").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(appGroups, result)
}
func (s *AppGroupSuite) TestGetByIdList_NotFoundAppGroups() {
appGroup := s.createAppGroup()
result := []domain.AppGroup{}
apiReq := domain.IdListRequest{IdList: []int{appGroup.Id + 1}}
err := s.api.Invoke("system/application_group/get_by_id_list").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Empty(result)
}
func (s *AppGroupSuite) TestCreate_HappyPath() {
apiReq := domain.CreateAppGroupRequest{
Name: fake.It[string](),
Description: fake.It[string](),
}
var result domain.AppGroup
err := s.api.Invoke("system/application_group/create").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(apiReq.Name, result.Name)
s.Require().Equal(apiReq.Description, result.Description)
appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), result.Id)
s.Require().NoError(err)
s.Require().Equal(apiReq.Name, appGroup.Name)
s.Require().Equal(apiReq.Description, appGroup.Description.String)
}
func (s *AppGroupSuite) TestCreate_AppGroupNameNotUnique() {
appGroup := s.createAppGroup()
apiReq := domain.CreateAppGroupRequest{
Name: appGroup.Name,
Description: fake.It[string](),
}
var result domain.AppGroup
err := s.api.Invoke("system/application_group/create").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeAppGroupDuplicateName, apiError.ErrorCode)
}
func (s *AppGroupSuite) TestUpdate_HappyPath() {
appGroupToUpdate := s.createAppGroup()
apiReq := domain.UpdateAppGroupRequest{
Id: appGroupToUpdate.Id,
Name: fake.It[string](),
Description: fake.It[string](),
}
var result domain.AppGroup
err := s.api.Invoke("system/application_group/update").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(apiReq.Name, result.Name)
s.Require().Equal(apiReq.Description, result.Description)
appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), apiReq.Id)
s.Require().NoError(err)
s.Require().Equal(apiReq.Name, appGroup.Name)
s.Require().Equal(apiReq.Description, appGroup.Description.String)
}
func (s *AppGroupSuite) TestUpdate_AppGroupNameNotUnique() {
appGroupToUpdate := s.createAppGroup()
appGroup := s.createAppGroup()
apiReq := domain.UpdateAppGroupRequest{
Id: appGroupToUpdate.Id,
Name: appGroup.Name,
Description: fake.It[string](),
}
err := s.api.Invoke("system/application_group/update").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeAppGroupDuplicateName, apiError.ErrorCode)
}
func (s *AppGroupSuite) TestUpdate_AppGroupNotFound() {
apiReq := domain.UpdateAppGroupRequest{
Id: fake.It[int](),
Name: fake.It[string](),
Description: fake.It[string](),
}
err := s.api.Invoke("system/application_group/update").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeAppGroupNotFound, apiError.ErrorCode)
}
func (s *AppGroupSuite) TestDeleteList() {
appGroupToDelete := s.createAppGroup()
appGroup := s.createAppGroup()
var result domain.DeleteResponse
apiReq := domain.IdListRequest{IdList: []int{appGroupToDelete.Id}}
err := s.api.Invoke("system/application_group/delete_list").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(1, result.Deleted)
_, err = s.appGroupRepo.GetAppGroupById(s.T().Context(), appGroup.Id)
s.Require().NoError(err)
}
func (s *AppGroupSuite) TestGetAll() {
toGenerate := 10
appGroups := make([]domain.AppGroup, 0, toGenerate)
for range 10 {
appGroup := s.createAppGroup()
appGroups = append(appGroups, domain.AppGroup{
Id: appGroup.Id,
Name: appGroup.Name,
Description: appGroup.Description.String,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
}
result := []domain.AppGroup{}
err := s.api.Invoke("system/application_group/get_all").
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(appGroups, result)
}
func (s *AppGroupSuite) createAppGroup() *entity.AppGroup {
appGroup, err := s.appGroupRepo.CreateAppGroup(
s.T().Context(),
fake.It[string](),
fake.It[string](),
)
s.Require().NoError(err)
return appGroup
}
+366
View File
@@ -0,0 +1,366 @@
package tests_test
import (
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/repository"
"math"
"testing"
"time"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/apierrors"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
)
func TestApplicationSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &ApplicationSuite{})
}
type ApplicationSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
appRepo repository.Application
appGroupRepo repository.AppGroup
tokenRepo repository.Token
api *client.Client
}
func (s *ApplicationSuite) SetupTest() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{})
_, s.api = grpct.TestServer(s.test, config.Handler)
s.appRepo = repository.NewApplication(s.testDb)
s.appGroupRepo = repository.NewAppGroup(s.testDb)
s.tokenRepo = repository.NewToken(s.testDb)
}
func (s *ApplicationSuite) TestGetAllApplications() {
expectedApps := s.insertApps(2)
result := []domain.Application{}
err := s.api.Invoke("system/application/get_all").
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(expectedApps, result)
}
func (s *ApplicationSuite) Test_GetByAppId() {
expectedApps := s.insertApps(2)
result := []domain.Application{}
err := s.api.Invoke("system/application/get_by_app_group").
JsonRequestBody(domain.Identity{
Id: expectedApps[0].ApplicationGroupId,
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(expectedApps, result)
}
func (s *ApplicationSuite) Test_GetByAppId_NotFoundAny() {
_ = s.insertApps(2)
result := []domain.Application{}
err := s.api.Invoke("system/application/get_by_app_group").
JsonRequestBody(domain.Identity{
Id: math.MaxInt32,
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Empty(result)
}
func (s *ApplicationSuite) TestCreate_HappyPath() {
result := domain.Application{}
appGroup := s.createAppGroup()
apiReq := domain.CreateApplicationRequest{
Id: 1,
Name: fake.It[string](),
Type: domain.ApplicationSystemType,
ApplicationGroupId: appGroup.Id,
}
err := s.api.Invoke("system/application/create_application").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().NotEmpty(result.CreatedAt)
result.CreatedAt = time.Time{}
s.Require().NotEmpty(result.UpdatedAt)
result.UpdatedAt = time.Time{}
expectedApp := domain.Application{
Id: apiReq.Id,
Name: apiReq.Name,
Description: apiReq.Description,
Type: apiReq.Type,
ApplicationGroupId: apiReq.ApplicationGroupId,
}
s.Require().Equal(expectedApp, result)
}
func (s *ApplicationSuite) TestCreate_AppGroupNotFound() {
apiReq := domain.CreateApplicationRequest{
Id: 1,
Name: fake.It[string](),
Type: domain.ApplicationSystemType,
ApplicationGroupId: 1,
}
err := s.api.Invoke("system/application/create_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeAppGroupNotFound, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestCreate_ApplicationNameNotUniqueInAppGroup() {
inserted := s.insertApps(1)
apiReq := domain.CreateApplicationRequest{
Id: inserted[0].Id + 1,
Name: inserted[0].Name,
Type: domain.ApplicationSystemType,
ApplicationGroupId: inserted[0].ApplicationGroupId,
}
err := s.api.Invoke("system/application/create_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationDuplicateName, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() {
inserted := s.insertApps(1)
apiReq := domain.CreateApplicationRequest{
Id: inserted[0].Id,
Name: inserted[0].Name,
Type: domain.ApplicationSystemType,
ApplicationGroupId: inserted[0].ApplicationGroupId,
}
err := s.api.Invoke("system/application/create_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationDuplicateId, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestUpdate_HappyPath() {
inserted := s.insertApps(2)
apiReq := domain.UpdateApplicationRequest{
OldId: inserted[0].Id,
NewId: inserted[0].Id + inserted[1].Id,
Name: fake.It[string](),
Description: fake.It[string](),
}
var result domain.Application
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().NotEmpty(result.CreatedAt)
result.CreatedAt = time.Time{}
s.Require().NotEmpty(result.UpdatedAt)
result.UpdatedAt = time.Time{}
expectedApp := domain.Application{
Id: apiReq.NewId,
Name: apiReq.Name,
Description: apiReq.Description,
Type: inserted[0].Type,
ApplicationGroupId: inserted[0].ApplicationGroupId,
}
s.Require().Equal(expectedApp, result)
app, err := s.appRepo.GetApplicationById(s.T().Context(), apiReq.NewId)
s.Require().NoError(err)
expectedDbApp := entity.Application{
Id: apiReq.NewId,
Name: apiReq.Name,
Description: app.Description,
Type: inserted[0].Type,
ApplicationGroupId: inserted[0].ApplicationGroupId,
}
s.Require().NotEmpty(app.CreatedAt)
app.CreatedAt = time.Time{}
s.Require().NotEmpty(app.UpdatedAt)
app.UpdatedAt = time.Time{}
s.Require().Equal(expectedDbApp, *app)
}
func (s *ApplicationSuite) TestUpdate_ApplicationNameNotUniqueInAppGroup() {
inserted := s.insertApps(2)
apiReq := domain.UpdateApplicationRequest{
NewId: inserted[0].Id,
OldId: inserted[0].Id,
Name: inserted[1].Name,
Description: fake.It[string](),
}
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationDuplicateName, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestUpdate_AppIdNotUnique() {
inserted := s.insertApps(2)
apiReq := domain.UpdateApplicationRequest{
OldId: inserted[0].Id,
NewId: inserted[1].Id,
Name: fake.It[string](),
Description: fake.It[string](),
}
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationDuplicateId, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestUpdate_AppNotFound() {
apiReq := domain.UpdateApplicationRequest{
OldId: fake.It[int](),
NewId: fake.It[int](),
Name: fake.It[string](),
Description: fake.It[string](),
}
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationNotFound, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestGetByToken() {
insertedApps := s.insertApps(2)
token := fake.It[string]()
expectedApp := domain.GetApplicationByTokenResponse{
ApplicationId: insertedApps[0].Id,
ApplicationGroupId: insertedApps[0].ApplicationGroupId,
}
_, err := s.tokenRepo.SaveToken(s.T().Context(), token, expectedApp.ApplicationId, fake.It[int]())
s.Require().NoError(err)
result := domain.GetApplicationByTokenResponse{}
err = s.api.Invoke("system/application/get_application_by_token").
JsonRequestBody(domain.GetApplicationByTokenRequest{Token: token}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(expectedApp, result)
}
func (s *ApplicationSuite) TestGetByToken_NotFound() {
s.insertApps(2)
result := domain.GetApplicationByTokenResponse{}
err := s.api.Invoke("system/application/get_application_by_token").
JsonRequestBody(domain.GetApplicationByTokenRequest{Token: fake.It[string]()}).
JsonResponseBody(&result).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationNotFound, apiError.ErrorCode)
}
func (s *ApplicationSuite) createAppGroup() *entity.AppGroup {
appGroup, err := s.appGroupRepo.CreateAppGroup(
s.T().Context(),
fake.It[string](),
fake.It[string](),
)
s.Require().NoError(err)
return appGroup
}
func (s *ApplicationSuite) insertApps(appsCount uint) []domain.Application {
toInsert := fake.It[[]domain.Application](fake.MinSliceSize(appsCount), fake.MaxSliceSize(appsCount))
appGroup := s.createAppGroup()
toExpect := make([]domain.Application, 0, len(toInsert))
for _, app := range toInsert {
appId, err := s.appRepo.NextApplicationId(s.T().Context())
s.Require().NoError(err)
createdApp, err := s.appRepo.CreateApplication(
s.T().Context(),
appId,
app.Name,
app.Description,
appGroup.Id,
app.Type,
)
s.Require().NoError(err)
s.Require().NotEmpty(createdApp.CreatedAt)
s.Require().NotEmpty(createdApp.UpdatedAt)
toExpect = append(toExpect, domain.Application{
Id: createdApp.Id,
Name: createdApp.Name,
Description: createdApp.Description.String,
ApplicationGroupId: createdApp.ApplicationGroupId,
Type: createdApp.Type,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
}
return toExpect
}
+52
View File
@@ -0,0 +1,52 @@
package tests_test
import (
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/service/baseline"
"testing"
)
func TestBaselineSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &BaselineSuite{})
}
type BaselineSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
baseline baseline.Service
api *client.Client
}
func (s *BaselineSuite) SetupSuite() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{
Baseline: conf.Baseline{
InitialAdminUiToken: fake.It[string](),
},
})
s.baseline = config.Baseline
_, s.api = grpct.TestServer(s.test, config.Handler)
}
func (s *BaselineSuite) TestBaselineSuccess() {
err := s.baseline.Do(s.T().Context())
s.Require().NoError(err)
err = s.baseline.Do(s.T().Context())
s.Require().NoError(err)
}
+47
View File
@@ -0,0 +1,47 @@
package tests_test
import (
"isp-system-service/entity"
"github.com/txix-open/isp-kit/test/dbt"
)
func InsertAppGroup(db *dbt.TestDb, value entity.AppGroup) {
q := `
INSERT INTO application_group
(id, name, description, created_at, updated_at)
VALUES
(:id, :name, :description, :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)
}
+215
View File
@@ -0,0 +1,215 @@
package tests_test
import (
"net/http"
"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/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
testDb *dbt.TestDb
api *client.Client
}
func (s *SecureSuite) 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{})
_, s.api = grpct.TestServer(s.test, config.Handler)
createdTime := time.Now().UTC()
InsertAppGroup(s.testDb, entity.AppGroup{
Id: 5, Name: "test_application_group", CreatedAt: createdTime, UpdatedAt: createdTime,
})
InsertApplication(s.testDb, entity.Application{
Id: 7, Name: "test_application", ApplicationGroupId: 5, CreatedAt: createdTime, UpdatedAt: createdTime,
})
}
// nolint: gosec
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(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
AppName: "test_application",
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(s.T().Context())
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(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
AppName: "test_application",
ApplicationId: 7,
},
}, result)
}
// nolint: gosec
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(s.T().Context())
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(s.T().Context())
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(s.T().Context())
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(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthorizeResponse{
Authorized: false,
}, result)
}
func (s *SecureSuite) TestAuthorize_WithHttpMethod_Success_True() {
InsertAccessList(s.testDb, entity.AccessList{
AppId: 7,
HttpMethod: http.MethodGet,
Method: "endpoint/available_http",
Value: true,
})
result := domain.AuthorizeResponse{}
err := s.api.Invoke("system/secure/authorize").
JsonRequestBody(domain.AuthorizeRequest{
ApplicationId: 7,
HttpMethod: http.MethodGet,
Endpoint: "endpoint/available_http",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthorizeResponse{
Authorized: true,
}, result)
}
+106
View File
@@ -0,0 +1,106 @@
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.AppGroup
repository.Application
repository.AccessList
repository.Token
}
func (m Manager) BaselineTx(ctx context.Context, txTx func(ctx context.Context, tx baseline.Transaction) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
return txTx(ctx, baselineTx{
Locker: repository.NewLocker(tx),
AppGroup: repository.NewAppGroup(tx),
Application: repository.NewApplication(tx),
AccessList: repository.NewAccessList(tx),
Token: repository.NewToken(tx),
})
})
}