2024-03-26 12:21:52: merge [master:81c5af7538f121910d74b369acc5d0d02259250b];

This commit is contained in:
txix committed 2024-03-26 12:21:52 +03:00
1 parent e7ad092001
commit 22a34dbb86
73 files changed
+7649 -1965

No files matched your search

+2 -1
View File
@@ -71,5 +71,6 @@ fabric.properties
/vendor/
google/
package.json
structure/
yarn.lock
conf/config_dev.yml
+29
View File
@@ -0,0 +1,29 @@
docker-build:
image: docker:latest
stage: build
services:
- docker:dind
before_script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
script:
- set
- docker build -f Dockerfile.dit --force-rm --pull -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .
- |
if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
tag=""
echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = ':latest'"
#docker pull "$CI_REGISTRY_IMAGE${tag}"
#docker tag "$CI_REGISTRY_IMAGE${tag}" "$CI_REGISTRY_IMAGE:pre"
#docker rmi "$CI_REGISTRY_IMAGE${tag}"
#docker push "$CI_REGISTRY_IMAGE:pre"
#docker rmi -f "$CI_REGISTRY_IMAGE:pre"
docker tag "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" "$CI_REGISTRY_IMAGE${tag}"
docker rmi "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
docker push "$CI_REGISTRY_IMAGE${tag}"
docker rmi -f "$CI_REGISTRY_IMAGE${tag}"
else
tag=":$CI_COMMIT_BRANCH"
echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag"
fi
after_script:
- docker logout $CI_REGISTRY
+69
View File
@@ -0,0 +1,69 @@
run:
timeout: 2m
linters:
disable-all: true
enable:
- asciicheck
- bodyclose
- deadcode
- dogsled
- errcheck
- funlen
- goconst
- gocritic
- gocyclo
- gofmt
- gomnd
- goprintffuncname
- gosimple
- govet
- nakedret
- nestif
- nolintlint
- prealloc
- rowserrcheck
- staticcheck
- structcheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- gosec
- misspell
- whitespace
- exhaustive #смотрит на соответствие между элементами enum и swich кейсами
- exportloopref #for _,p := []int{1, 2, 3} { s.Bar(&p) /* If s stores the pointer, it will be bug.*/ }
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
linters-settings:
funlen:
lines: 80
statements: 40
prealloc:
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
# True by default.
simple: true
range-loops: true # Report preallocation suggestions on range loops, true by default
for-loops: true # Report preallocation suggestions on for loops, false by default
gocritic:
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- diagnostic
- performance
disabled-checks:
- hugeParam
- rangeValCopy
- ifElseChain
exhaustive:
default-signifies-exhaustive: true
issues:
exclude-rules:
- path: _test\.go # to exclude all test files for linter errcheck
linters:
- errcheck
- linters:
- gosec
text: "G101:"
+1 -1
View File
@@ -1 +1 @@
0.3.0
4.0.0
+58
View File
@@ -0,0 +1,58 @@
### 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
+19
View File
@@ -0,0 +1,19 @@
FROM dockerhub.mos.ru/golang:1.19-alpine3.16 as builder
WORKDIR /build
ARG version
ENV version_env=$version
ARG app_name
ENV app_name_env=$app_name
COPY . .
ENV GOPROXY=https://repo-mirror.mos.ru/repository/go-public
RUN go build -ldflags="-X 'main.version=$version_env'" -o /main .
FROM dockerhub.mos.ru/alpine:3.16.0
WORKDIR /app
ARG app_name
ENV app_name_env=$app_name
COPY --from=builder main /app/$app_name_env
COPY /conf/config.yml /app/config.yml
COPY /conf/default_remote_config.json* /app/default_remote_config.json
COPY /migrations /app/migrations
ENTRYPOINT /app/$app_name_env
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 @@
test
+85
View File
@@ -0,0 +1,85 @@
package assembly
import (
"context"
"github.com/integration-system/isp-kit/app"
"github.com/integration-system/isp-kit/bootstrap"
"github.com/integration-system/isp-kit/cluster"
"github.com/integration-system/isp-kit/dbrx"
"github.com/integration-system/isp-kit/dbx"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/log"
"github.com/pkg/errors"
"isp-system-service/conf"
"isp-system-service/migrations"
)
type Assembly struct {
boot *bootstrap.Bootstrap
db *dbrx.Client
server *grpc.Server
logger *log.Adapter
}
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
dbCli := dbrx.New(dbx.WithMigration(boot.MigrationsDir))
server := grpc.NewServer()
return &Assembly{
boot: boot,
db: dbCli,
server: server,
logger: boot.App.Logger(),
}, nil
}
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
var (
newCfg conf.Remote
prevCfg conf.Remote
)
err := a.boot.RemoteConfig.Upgrade(remoteConfig, &newCfg, &prevCfg)
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade remote config"))
}
migrations.Initialize.SetParams(a.boot.MigrationsDir, newCfg.Database.Schema)
a.logger.SetLevel(newCfg.LogLevel)
err = a.db.Upgrade(ctx, newCfg.Database)
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"), log.Any("config", newCfg.Database))
}
locator := NewLocator(a.db, a.logger)
handler := locator.Handler(newCfg)
a.server.Upgrade(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,
}
}
+71
View File
@@ -0,0 +1,71 @@
package assembly
import (
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/grpc/endpoint"
"github.com/integration-system/isp-kit/grpc/isp"
"github.com/integration-system/isp-kit/log"
"isp-system-service/conf"
"isp-system-service/controller"
"isp-system-service/repository"
"isp-system-service/routes"
"isp-system-service/service"
"isp-system-service/service/secure"
"isp-system-service/transaction"
)
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,
}
}
func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
txManager := transaction.NewManager(l.db)
accessListRep := repository.NewAccessList(l.db)
applicationRep := repository.NewApplication(l.db)
domainRep := repository.NewDomain(l.db)
serviceRep := repository.NewService(l.db)
tokenRep := repository.NewToken(l.db)
secureService := secure.NewService(tokenRep, accessListRep)
accessListService := service.NewAccessList(txManager, accessListRep, applicationRep)
applicationService := service.NewApplication(txManager, applicationRep, domainRep, serviceRep, tokenRep)
domainService := service.NewDomain(domainRep)
serviceService := service.NewService(domainRep, serviceRep)
jwtService := service.NewTokenSource()
tokenService := service.NewToken(jwtService, applicationService, txManager,
applicationRep, domainRep, serviceRep, tokenRep,
)
secureController := controller.NewSecure(secureService)
accessListController := controller.NewAccessList(accessListService)
applicationController := controller.NewApplication(applicationService)
domainController := controller.NewDomain(domainService)
serviceController := controller.NewService(serviceService)
tokenController := controller.NewToken(tokenService)
c := routes.Controllers{
Secure: secureController,
AccessList: accessListController,
Domain: domainController,
Service: serviceController,
Application: applicationController,
Token: tokenController,
}
mapper := endpoint.DefaultWrapper(l.logger, endpoint.BodyLogger(l.logger))
server := routes.Handler(mapper, c)
return server
}
+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
+11
View File
@@ -0,0 +1,11 @@
{
"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
}
}
-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"`
}
+22
View File
@@ -0,0 +1,22 @@
package conf
import (
"reflect"
"github.com/integration-system/isp-kit/dbx"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-kit/rc/schema"
"github.com/integration-system/jsonschema"
)
func init() {
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Type) {
t.Type = "string"
t.Enum = []interface{}{"debug", "info", "error", "fatal"}
})
}
type Remote struct {
Database dbx.Config `schema:"Настройка базы данных"`
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
}
-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"`
}
+95
View File
@@ -0,0 +1,95 @@
package controller
import (
"context"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
type AccessListService interface {
GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error)
SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error)
SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error)
}
type AccessList struct {
service AccessListService
}
func NewAccessList(service AccessListService) AccessList {
return AccessList{
service: service,
}
}
// GetById godoc
// @Tags accessList
// @Summary Получить список доступности методов для приложения
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
// @Accept json
// @Produce json
// @Param body body domain.Identity false "идентификатор приложения"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @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, status.Errorf(codes.NotFound, "application not found")
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} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @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, status.Errorf(codes.NotFound, "application not found")
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} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @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, status.Errorf(codes.NotFound, "application not found")
case err != nil:
return nil, err
default:
return result, nil
}
}
+119 -161
View File
@@ -1,191 +1,149 @@
package controller
import (
"isp-system-service/entity"
"isp-system-service/model"
"context"
"github.com/integration-system/isp-lib/database"
"github.com/integration-system/isp-lib/utils"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
func GetApplications(list []int32) ([]*AppWithToken, error) {
res, err := model.AppRep.GetApplications(list)
if err != nil {
return nil, err
}
return enrichWithTokens(res...)
type ApplicationService interface {
GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error)
GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error)
GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error)
SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error)
CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error)
Delete(ctx context.Context, idList []int) (int, 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.ApplicationWithTokens
// @Failure 400 {object} domain.GrpcError
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application/get_application_by_id [POST]
func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id)
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")
}
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
// GetByIdList godoc
// @Tags application
// @Summary Получить список приложений
// @Description Возвращает массив приложений с токенами по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} domain.GrpcError
// @Router /application/get_applications [POST]
func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) {
return c.service.GetByIdList(ctx, req)
}
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
// GetByServiceId godoc
// @Tags application
// @Summary Получить список приложений по идентификатору сервиса
// @Description Возвращает список приложений по запрошенному идентификатору сервиса
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор сервиса"
// @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} domain.GrpcError
// @Router /application/get_applications_by_service_id [POST]
func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) {
return c.service.GetByServiceId(ctx, req.Id)
}
func enrichWithTokens(apps ...entity.Application) ([]*AppWithToken, error) {
l := len(apps)
if len(apps) == 0 {
return []*AppWithToken{}, nil
// GetSystemTree godoc
// @Tags application
// @Summary Метод получения системного дерева
// @Description Возвращает описание взаимосвязей сервисов и приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.DomainWithService
// @Failure 500 {object} domain.GrpcError
// @Router /application/get_system_tree [POST]
func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithService, error) {
return c.service.SystemTree(ctx, domain.DefaultSystemId)
}
// CreateUpdate godoc
// @Tags application
// @Summary Создать/обновить приложение
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} domain.GrpcError
// @Failure 404 {object} domain.GrpcError
// @Failure 409 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application/create_update_application [POST]
func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.CreateUpdate(ctx, req)
switch {
case errors.Is(err, domain.ErrServiceNotFound):
return nil, status.Errorf(codes.InvalidArgument, "service with id %d not found", req.ServiceId)
case errors.Is(err, domain.ErrApplicationDuplicateName):
return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name)
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", req.Id)
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} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application/delete_applications [POST]
func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "At least one id are required")
}
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
}
+97 -68
View File
@@ -1,87 +1,116 @@
package controller
import (
"isp-system-service/entity"
"isp-system-service/model"
"context"
"github.com/integration-system/isp-lib/utils"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
/*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))
type DomainService interface {
GetById(ctx context.Context, id int) (*domain.Domain, error)
GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error)
CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error)
Delete(ctx context.Context, idList []int) (int, error)
}
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
}
type Domain struct {
service DomainService
}
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 NewDomain(service DomainService) Domain {
return Domain{
service: service,
}
}
func GetDomainById(identity Identity) (*entity.Domain, error) {
domain, err := model.DomainRep.GetDomainById(identity.Id)
// GetById godoc
// @Tags domain
// @Summary Получить домен по идентификатору
// @Description Возвращает описание домена по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {object} domain.Domain
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /domain/get_domain_by_id [POST]
func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domain, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
case err != nil:
return nil, err
default:
return result, nil
}
}
// GetBySystemId godoc
// @Tags domain
// @Summary Получить домены по идентификатору системы
// @Description Возвращает список доменов по системному идентификатору
// @Accept json
// @Produce json
// @Param body body integer false "Идентификатор системы"
// @Success 200 {array} domain.Domain
// @Failure 500 {object} domain.GrpcError
// @Router /domain/get_domains_by_system_id [POST]
func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) {
return c.service.GetBySystemId(ctx, domain.DefaultSystemId)
}
// CreateUpdate godoc
// @Tags domain
// @Summary Создать/обновить домен
// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.DomainCreateUpdateRequest true "Объект домена"
// @Success 200 {object} domain.Domain
// @Failure 500 {object} domain.GrpcError
// @Router /domain/create_update_domain [POST]
func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest) (*domain.Domain, error) {
result, err := c.service.CreateUpdate(ctx, req, domain.DefaultSystemId)
switch {
case errors.Is(err, domain.ErrSystemNotFound):
return nil, status.Errorf(codes.InvalidArgument, "system with id %d not found", domain.DefaultSystemId)
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
case errors.Is(err, domain.ErrDomainDuplicateName):
return nil, status.Errorf(codes.AlreadyExists, "domain with name %s already exists", req.Name)
case err != nil:
return nil, err
default:
return result, nil
}
}
// Delete godoc
// @Tags domain
// @Summary Удаление доменов
// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов доменов"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /domain/delete_domains [POST]
func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "at least one id are required")
}
result, err := c.service.Delete(ctx, req)
if err != nil {
return nil, err
}
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
return &domain.DeleteResponse{
Deleted: result,
}, nil
}
+82
View File
@@ -0,0 +1,82 @@
package controller
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
)
type SecureService interface {
Authenticate(ctx context.Context, token string) (*domain.AuthData, error)
Authorize(ctx context.Context, appId int, endpoint string) (bool, error)
}
type Secure struct {
service SecureService
}
func NewSecure(service SecureService) Secure {
return Secure{
service: service,
}
}
// Authenticate godoc
// @Tags secure
// @Summary Метод аутентификации токена
// @Description Проверяет наличие токена в системе,
// @Accept json
// @Produce json
// @Param body body domain.AuthenticateRequest true "Тело запроса"
// @Success 200 {array} domain.AuthenticateResponse
// @Failure 500 {object} domain.GrpcError
// @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} domain.GrpcError
// @Router /secure/authorize [POST]
func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) {
result, err := c.service.Authorize(ctx, req.ApplicationId, req.Endpoint)
switch {
case errors.Is(err, domain.ErrAccessListNotFound):
return &domain.AuthorizeResponse{
Authorized: false,
}, nil
case err != nil:
return nil, errors.WithMessage(err, "authorize")
default:
return &domain.AuthorizeResponse{
Authorized: result,
}, nil
}
}
+116 -56
View File
@@ -1,74 +1,134 @@
package controller
import (
"isp-system-service/entity"
"isp-system-service/model"
"context"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
func GetService(list []int32) ([]entity.Service, error) {
res, err := model.ServiceRep.GetServices(list)
if err != nil {
return res, err
type ServiceService interface {
GetById(ctx context.Context, id int) (*domain.Service, error)
GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error)
GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error)
CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error)
Delete(ctx context.Context, idList []int) (int, error)
}
type Service struct {
service ServiceService
}
func NewService(service ServiceService) Service {
return Service{
service: service,
}
return res, nil
}
func GetServicesByDomainId(identity Identity) ([]entity.Service, error) {
return model.ServiceRep.GetServicesByDomainId(identity.Id)
// GetById godoc
// @Tags service
// @Summary Получить сервис по идентификатору
// @Description Возвращает описание сервиса по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор сервиса"
// @Success 200 {object} domain.Service
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /service/get_service_by_id [POST]
func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrServiceNotFound):
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
case err != nil:
return nil, err
default:
return result, nil
}
}
func CreateUpdateService(service entity.Service) (*entity.Service, error) {
existed, err := model.ServiceRep.GetServiceByNameAndDomainId(service.Name, service.DomainId)
// Get godoc
// @Tags service
// @Summary Получить список сервисов
// @Description Возвращает список сервисов по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов сервисов"
// @Success 200 {array} domain.Service
// @Failure 500 {object} domain.GrpcError
// @Router /service/get_service [POST]
func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) {
return c.service.GetByIdList(ctx, req)
}
// GetByDomainId godoc
// @Tags service
// @Summary Получить список сервисов по идентификатору домена
// @Description Возвращает список сервисов по идентификатору домена
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {array} domain.Service
// @Failure 500 {object} domain.GrpcError
// @Router /service/get_services_by_domain_id [POST]
func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.Service, error) {
return c.service.GetByDomainId(ctx, req.Id)
}
// CreateUpdate godoc
// @Tags service
// @Summary Создать/обновить сервис
// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса"
// @Success 200 {object} domain.Service
// @Failure 400 {object} domain.GrpcError
// @Failure 404 {object} domain.GrpcError
// @Failure 409 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /service/create_update_service [POST]
func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
result, err := c.service.CreateUpdate(ctx, req)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.InvalidArgument, "domain with id %d not found", req.DomainId)
case errors.Is(err, domain.ErrServiceNotFound):
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
case errors.Is(err, domain.ErrServiceDuplicateName):
return nil, status.Errorf(codes.AlreadyExists, "service with name %s already exists", req.Name)
case err != nil:
return nil, err
default:
return result, nil
}
}
// Delete godoc
// @Tags service
// @Summary Удалить сервисы
// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов
// @Accept json
// @Produce json
// @Param body body []integer true "Массив идентификаторов сервисов"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /service/delete_service [POST]
func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, status.Error(codes.InvalidArgument, "at least one id are required")
}
result, err := c.service.Delete(ctx, req)
if err != nil {
return nil, err
}
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
return &domain.DeleteResponse{
Deleted: result,
}, nil
}
-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
}
+78 -189
View File
@@ -1,206 +1,95 @@
package controller
import (
"time"
"context"
"isp-system-service/conf"
"isp-system-service/entity"
"isp-system-service/model"
"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"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
const (
SystemIdentityFieldInDb = "1"
DomainIdentityFieldInDb = "2"
ServiceIdentityFieldInDb = "3"
ApplicationIdentityFieldInDb = "4"
)
var (
generator = tg.NewGenerator(tg.DefaultAlphabet)
)
type BoolResponse struct {
Ok bool
type ITokenService 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 ITokenService
}
func NewToken(service ITokenService) 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} domain.GrpcError
// @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} domain.GrpcError
// @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, status.Errorf(codes.NotFound, "application with id %d not found", req.AppId)
case errors.Is(err, domain.ErrServiceNotFound):
return nil, status.Errorf(codes.NotFound, "service for app_id id %d not found", req.AppId)
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.NotFound, "domain for app_id %d not found", req.AppId)
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} domain.GrpcError
// @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} domain.GrpcError
// @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)
}
+1563
View File
File diff suppressed because it is too large. Load diff
+1012
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
package domain
type AccessListSetOneRequest struct {
AppId int `valid:"required~Required"`
Method string `valid:"required~Required"`
Value bool
}
type AccessListSetOneResponse struct {
Count int
}
type AccessListSetListRequest struct {
AppId int `valid:"required~Required"`
RemoveOld bool
Methods []MethodInfo
}
type MethodInfo struct {
Method string
Value bool
}
+36
View File
@@ -0,0 +1,36 @@
package domain
import (
"time"
)
type Application struct {
Id int
Name string
Description string
ServiceId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
}
type ApplicationCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Description string
ServiceId int `valid:"required~Required"`
Type string `valid:"required~Required,in(SYSTEM|MOBILE)"`
}
type ApplicationWithTokens struct {
App Application
Tokens []Token
}
type ApplicationSimple struct {
Id int
Name string
Description string
Type string
Tokens []Token
}
+11
View File
@@ -0,0 +1,11 @@
package domain
type (
Identity struct {
Id int `valid:"required~Required"`
}
DeleteResponse struct {
Deleted int
}
)
+27
View File
@@ -0,0 +1,27 @@
package domain
import (
"time"
)
type DomainCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Description string
}
type Domain struct {
Id int
Name string
Description string
SystemId int
CreatedAt time.Time
UpdatedAt time.Time
}
type DomainWithService struct {
Id int
Name string
Description string
Services []*ServiceWithApps
}
+23
View File
@@ -0,0 +1,23 @@
package domain
import (
"github.com/pkg/errors"
)
var (
ErrDomainNotFound = errors.New("domain not found")
ErrDomainDuplicateName = errors.New("domain name already exist")
ErrServiceNotFound = errors.New("service not found")
ErrServiceDuplicateName = errors.New("service name already exist")
ErrSystemNotFound = errors.New("system not found")
ErrApplicationNotFound = errors.New("application not found")
ErrApplicationDuplicateName = errors.New("application name already exist")
ErrTokenNotFound = errors.New("token not found")
ErrTokenExpired = errors.New("token is expired")
ErrAccessListNotFound = errors.New("access_list not found")
)
+7
View File
@@ -0,0 +1,7 @@
package domain
type GrpcError struct {
ErrorMessage string `json:"errorMessage"`
ErrorCode string `json:"errorCode"`
Details []interface{} `json:"details"`
}
+27
View File
@@ -0,0 +1,27 @@
package domain
type AuthenticateRequest struct {
Token string `valid:"required~Required"`
}
type AuthenticateResponse struct {
Authenticated bool
ErrorReason string
AuthData *AuthData
}
type AuthData struct {
SystemId int
DomainId int
ServiceId int
ApplicationId int
}
type AuthorizeRequest struct {
ApplicationId int `valid:"required~Required"`
Endpoint string `valid:"required~Required"`
}
type AuthorizeResponse struct {
Authorized bool
}
+28
View File
@@ -0,0 +1,28 @@
package domain
import (
"time"
)
type Service struct {
Id int
Name string
Description string
DomainId int
CreatedAt time.Time
UpdatedAt time.Time
}
type ServiceCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Description string
DomainId int `valid:"required~Required"`
}
type ServiceWithApps struct {
Id int
Name string
Description string
Apps []*ApplicationSimple
}
+5
View File
@@ -0,0 +1,5 @@
package domain
const (
DefaultSystemId = 1
)
+22
View File
@@ -0,0 +1,22 @@
package domain
import (
"time"
)
type Token struct {
Token string
AppId int
ExpireTime int
CreatedAt time.Time
}
type TokenRevokeRequest struct {
AppId int `valid:"required~Required"`
Tokens []string
}
type TokenCreateRequest struct {
AppId int `valid:"required~Required"`
ExpireTimeMs int `valid:"required~Required"`
}
+7
View File
@@ -0,0 +1,7 @@
package entity
type AccessList struct {
AppId int
Method string
Value bool
}
+15
View File
@@ -0,0 +1,15 @@
package entity
import (
"time"
)
type Application struct {
Id int
Name string
Description *string
ServiceId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
}
+14
View File
@@ -0,0 +1,14 @@
package entity
import (
"time"
)
type Domain struct {
Id int
Name string
Description *string
SystemId int
CreatedAt time.Time
UpdatedAt time.Time
}
-60
View File
@@ -1,60 +0,0 @@
package entity
import "time"
const (
RootAdminApplicationId = 1
)
const (
AppTypeSystem = "SYSTEM"
AppTypeMobile = "MOBILE"
)
type System struct {
TableName string `sql:"system_service.system" json:"-"`
Id int32
Name string `valid:"required~Required"`
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
type Domain struct {
TableName string `sql:"system_service.domain" json:"-"`
Id int32
Name string `valid:"required~Required"`
Description string
SystemId int32
CreatedAt time.Time
UpdatedAt time.Time
}
type Service struct {
TableName string `sql:"system_service.service" json:"-"`
Id int32
Name string `valid:"required~Required"`
Description string
DomainId int32 `valid:"required~Required"`
CreatedAt time.Time
UpdatedAt time.Time
}
type Application struct {
TableName string `sql:"system_service.application" json:"-"`
Id int32
Name string `valid:"required~Required"`
Description string
Type string `valid:"required~Required,in(SYSTEM|MOBILE)"`
ServiceId int32 `valid:"required~Required"`
CreatedAt time.Time
UpdatedAt time.Time
}
type Token struct {
TableName string `sql:"system_service.token" json:"-"`
Token string `valid:"required~Required" sql:"pk:token"`
AppId int32 `valid:"required~Required"`
ExpireTime int64
CreatedAt time.Time
}
+14
View File
@@ -0,0 +1,14 @@
package entity
import (
"time"
)
type Service struct {
Id int
Name string
Description *string
DomainId int
CreatedAt time.Time
UpdatedAt time.Time
}
+21
View File
@@ -0,0 +1,21 @@
package entity
import (
"time"
)
type Token struct {
Token string
AppId int
ExpireTime int
CreatedAt time.Time
}
type AuthData struct {
SystemId int
DomainId int
ServiceId int
AppId int
ExpireTime int
CreatedAt time.Time
}
+86
View File
@@ -0,0 +1,86 @@
module isp-system-service
go 1.17
require (
github.com/Masterminds/squirrel v1.5.3
github.com/integration-system/isp-kit v1.10.4
github.com/integration-system/isp-lib/v2 v2.10.0
github.com/integration-system/jsonschema v1.0.1
github.com/pkg/errors v0.9.1
github.com/pressly/goose v2.7.0+incompatible
github.com/stretchr/testify v1.8.0
google.golang.org/grpc v1.48.0
)
require (
github.com/BurntSushi/toml v1.1.0 // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-openapi/spec v0.20.5 // indirect
github.com/go-openapi/swag v0.21.1 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect
github.com/integration-system/bellows v1.0.1 // indirect
github.com/integration-system/isp-etp-go/v2 v2.1.3 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.12.1 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.3.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.11.0 // indirect
github.com/jackc/pgx/v4 v4.16.1 // indirect
github.com/jmoiron/sqlx v1.3.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.15.8 // 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.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // 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/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.12.2 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.36.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.12.0 // indirect
github.com/subosito/gotenv v1.4.0 // indirect
github.com/swaggo/swag v1.7.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
go.uber.org/zap v1.21.0 // indirect
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/net v0.0.0-20220708220712-1185a9018129 // indirect
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.1.10 // indirect
google.golang.org/genproto v0.0.0-20220713161829-9c7dac0a6568 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.66.6 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
nhooyr.io/websocket v1.8.7 // indirect
)
+1306
View File
File diff suppressed because it is too large. Load diff
-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(),
}
}
+33 -91
View File
@@ -1,107 +1,49 @@
package main
import (
"os"
"github.com/integration-system/isp-kit/bootstrap"
"github.com/integration-system/isp-kit/shutdown"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/helper"
"isp-system-service/model"
_ "isp-system-service/migrations"
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/database"
"github.com/integration-system/isp-lib/metric"
"github.com/integration-system/isp-lib/socket"
"context"
"github.com/integration-system/isp-lib/bootstrap"
"github.com/integration-system/isp-lib/redis"
"isp-system-service/routes"
)
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 --parseDependency
//go:generate rm -f docs/swagger.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{}, routes.EndpointDescriptors())
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 {
app.Shutdown()
logger.Fatal(app.Context(), 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
+109 -75
View File
@@ -4,13 +4,12 @@ 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"
"path/filepath"
"github.com/pkg/errors"
"github.com/pressly/goose"
"isp-system-service/domain"
)
const (
@@ -25,102 +24,137 @@ const (
)
func init() {
goose.AddMigration(Up, Down)
goose.AddMigration(Initialize.Up, Initialize.Down)
}
func Up(tx *sql.Tx) error {
path := path2.Join(database.ResolveMigrationsDirectrory(), initFile)
var Initialize = &initializeMigration{}
type initializeMigration struct {
migrationDir string
schema string
}
type identity struct {
domainId int
appId int
serviceId int
}
func (i *initializeMigration) SetParams(migrationDir string, schema string) {
i.migrationDir = migrationDir
i.schema = schema
}
func (i *initializeMigration) Up(tx *sql.Tx) error {
path := filepath.Join(i.migrationDir, initFile)
bytes, err := ioutil.ReadFile(path)
if err != nil {
return err
return errors.WithMessage(err, "read file")
}
var list []controller.DomainWithServices
if err := json.Unmarshal(bytes, &list); err != nil {
return err
list := make([]domain.DomainWithService, 0)
err = json.Unmarshal(bytes, &list)
if err != nil {
return errors.WithMessage(err, "json unmarshal")
}
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
lastDomainId := 0
lastServiceId := 0
lastAppId := 0
for _, domainInfo := range list {
last, err := i.insert(tx, domainInfo)
if err != nil {
return errors.WithMessage(err, "")
}
if domainId > lastDomainId {
lastDomainId = domainId
if last.domainId > lastDomainId {
lastDomainId = last.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 last.serviceId > lastServiceId {
lastServiceId = last.serviceId
}
if last.appId > lastAppId {
lastAppId = last.appId
}
}
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
err = i.setSeq(tx, "domain", lastDomainId)
if err != nil {
return errors.WithMessage(err, "set domain")
}
err = i.setSeq(tx, "service", lastServiceId)
if err != nil {
return errors.WithMessage(err, "set service")
}
err = i.setSeq(tx, "application", lastAppId)
if err != nil {
return errors.WithMessage(err, "set application")
}
return nil
}
func Down(tx *sql.Tx) error {
func (i *initializeMigration) 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
func (i *initializeMigration) insert(tx *sql.Tx, domainInfo domain.DomainWithService) (*identity, error) {
domainId, err := i.insertNode(tx, insertDomain, true, i.schema, domainInfo.Id, domainInfo.Name, domainInfo.Description, 1)
if err != nil {
return nil, errors.WithMessage(err, "insert domain")
}
serviceId := 0
appId := 0
for _, service := range domainInfo.Services {
serviceId, err = i.insertNode(tx, insertService, true, i.schema, service.Id, service.Name, service.Description, domainId)
if err != nil {
return nil, errors.WithMessage(err, "insert service")
}
for _, app := range service.Apps {
appId, err = i.insertNode(tx, insertApp, true, i.schema, app.Id, app.Name, app.Description, serviceId, app.Type)
if err != nil {
return nil, errors.WithMessage(err, "insert application")
}
for _, t := range app.Tokens {
_, err = i.insertNode(tx, insertToken, false, i.schema, t.Token, appId, t.ExpireTime)
if err != nil {
return nil, errors.WithMessage(err, "insert token")
}
}
}
}
return &identity{
domainId: domainId,
appId: appId,
serviceId: serviceId,
}, nil
}
func (i *initializeMigration) insertNode(tx *sql.Tx, query string, scan bool, args ...interface{}) (int, error) {
var id int
query = fmt.Sprintf(query, args...)
row := tx.QueryRow(query)
if scan {
row.Scan(&id)
}
if err != nil {
return 0, err
err := row.Scan(&id)
if err != nil {
return 0, errors.WithMessage(err, "row scan")
}
}
return id, nil
}
func setSeq(tx *sql.Tx, schema, table string, value int64) error {
q := fmt.Sprintf(setSeqQuery, schema, table, value)
func (i *initializeMigration) setSeq(tx *sql.Tx, table string, value int) error {
q := fmt.Sprintf(setSeqQuery, i.schema, table, value)
_, err := tx.Exec(q)
return err
if err != nil {
return errors.WithMessage(err, "exec db")
}
return nil
}
@@ -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,7 @@
-- +goose Up
insert into access_list (app_id, method, value)
values (1, 'admin/auth/login', true)
on conflict (app_id, method) do update set value = true;
-- +goose Down
-62
View File
@@ -24,67 +24,5 @@
]
}
]
},
{
"id": 2,
"name": "citymodule",
"description": "",
"services": [
{
"id": 2,
"name": "citymodule_service",
"description": "",
"apps": [
{
"id": 2,
"name": "cityservice",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_token }}",
"expireTime": -1
}
]
},
{
"id": 3,
"name": "citymodule",
"description": "",
"type": "MOBILE",
"tokens": [
{
"token": "{{ isp_service_citymodule_token }}",
"expireTime": -1
}
]
},
{
"id": 4,
"name": "cityservice_operator_ui",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_operator_ui_token }}",
"expireTime": -1
}
]
},
{
"id": 5,
"name": "cityservice_web_portal",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_web_portal_token }}",
"expireTime": -1
}
]
}
]
}
]
}
]
-69
View File
@@ -1,69 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
var (
emptyApplication = &entity.Application{}
AppRep AppRepository
)
type AppRepository struct {
DB orm.DB
}
func (ar *AppRepository) GetApplications(list []int32) ([]entity.Application, error) {
var res []entity.Application
q := ar.DB.Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (ar *AppRepository) GetApplicationsByServiceId(serviceId ...int32) ([]entity.Application, error) {
var res []entity.Application
err := ar.DB.Model(&res).Where("service_id IN (?)", pg.In(serviceId)).Order("created_at DESC").Select()
return res, err
}
func (ar *AppRepository) CreateApplication(service entity.Application) (entity.Application, error) {
_, err := ar.DB.Model(&service).Insert()
return service, err
}
func (ar *AppRepository) GetApplicationByNameAndServiceId(name string, serviceId int32) (*entity.Application, error) {
app := new(entity.Application)
err := ar.DB.Model(app).Where("name = ? AND service_id = ?", name, serviceId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return app, err
}
func (ar *AppRepository) UpdateApplication(app entity.Application) (entity.Application, error) {
_, err := ar.DB.Model(&app).Column("name", "description").WherePK().Returning("*").Update()
return app, err
}
func (ar *AppRepository) GetApplicationById(id int32) (*entity.Application, error) {
app := &entity.Application{Id: id}
err := ar.DB.Select(app)
if err == pg.ErrNoRows {
return nil, nil
}
return app, err
}
func (ar *AppRepository) DeleteApplications(list []int32) (int, error) {
res, err := ar.DB.Model(emptyApplication).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
-69
View File
@@ -1,69 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
var (
emptyDomain = &entity.Domain{}
DomainRep DomainRepository
)
type DomainRepository struct {
DB orm.DB
}
func (dr *DomainRepository) GetDomains(list []int32) ([]entity.Domain, error) {
var res []entity.Domain
q := dr.DB.Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (dr *DomainRepository) GetDomainsBySystemId(systemId int32) ([]entity.Domain, error) {
var res []entity.Domain
err := dr.DB.Model(&res).Where("system_id = ?", systemId).Order("created_at DESC").Select()
return res, err
}
func (dr *DomainRepository) CreateDomain(domain entity.Domain) (entity.Domain, error) {
_, err := dr.DB.Model(&domain).Insert()
return domain, err
}
func (dr *DomainRepository) GetDomainByNameAndSystemId(name string, systemId int32) (*entity.Domain, error) {
domain := new(entity.Domain)
err := dr.DB.Model(domain).Where("name = ? AND system_id = ?", name, systemId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return domain, err
}
func (dr *DomainRepository) UpdateDomain(domain entity.Domain) (entity.Domain, error) {
_, err := dr.DB.Model(&domain).Column("name", "description").WherePK().Returning("*").Update()
return domain, err
}
func (dr *DomainRepository) GetDomainById(id int32) (*entity.Domain, error) {
domain := &entity.Domain{Id: id}
err := dr.DB.Select(domain)
if err == pg.ErrNoRows {
return nil, nil
}
return domain, err
}
func (dr *DomainRepository) DeleteDomains(list []int32) (int, error) {
res, err := dr.DB.Model(emptyDomain).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
-69
View File
@@ -1,69 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
var (
emptyService = &entity.Service{}
ServiceRep ServiceRepository
)
type ServiceRepository struct {
DB orm.DB
}
func (sr *ServiceRepository) GetServices(list []int32) ([]entity.Service, error) {
var res []entity.Service
q := sr.DB.Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (sr *ServiceRepository) GetServicesByDomainId(domainId ...int32) ([]entity.Service, error) {
var res []entity.Service
err := sr.DB.Model(&res).Where("domain_id IN (?)", pg.In(domainId)).Order("created_at DESC").Select()
return res, err
}
func (sr *ServiceRepository) CreateService(service entity.Service) (entity.Service, error) {
_, err := sr.DB.Model(&service).Insert()
return service, err
}
func (sr *ServiceRepository) GetServiceByNameAndDomainId(name string, domainId int32) (*entity.Service, error) {
service := new(entity.Service)
err := sr.DB.Model(service).Where("name = ? AND domain_id = ?", name, domainId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return service, err
}
func (sr *ServiceRepository) UpdateService(service entity.Service) (entity.Service, error) {
_, err := sr.DB.Model(&service).Column("name", "description").WherePK().Returning("*").Update()
return service, err
}
func (sr *ServiceRepository) GetServiceById(id int32) (*entity.Service, error) {
service := &entity.Service{Id: id}
err := sr.DB.Select(service)
if err == pg.ErrNoRows {
return nil, nil
}
return service, err
}
func (sr *ServiceRepository) DeleteServices(list []int32) (int, error) {
res, err := sr.DB.Model(emptyService).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
-73
View File
@@ -1,73 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
"github.com/integration-system/isp-lib/database"
)
var (
emptySystem = &entity.System{}
SystemRep SystemRepository
)
type SystemRepository struct {
DB orm.DB
}
func (sr *SystemRepository) GetSystems(list []int32) ([]entity.System, error) {
var res []entity.System
q := sr.DB.Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (sr *SystemRepository) CreateSystem(system entity.System) (entity.System, error) {
_, err := sr.DB.Model(&system).Insert()
return system, err
}
func (sr *SystemRepository) GetSystemByName(name string) (*entity.System, error) {
sys := new(entity.System)
err := sr.DB.Model(sys).Where("name = ?", name).First()
if err == pg.ErrNoRows {
return nil, nil
}
return sys, err
}
func (sr *SystemRepository) UpdateSystem(system entity.System) (entity.System, error) {
_, err := sr.DB.Model(&system).Column("name", "description").WherePK().Returning("*").Update()
return system, err
}
func (sr *SystemRepository) GetSystemById(id int32) (*entity.System, error) {
sys := &entity.System{Id: id}
err := sr.DB.Select(sys)
if err == pg.ErrNoRows {
return nil, nil
}
return sys, err
}
func (sr *SystemRepository) DeleteSystems(list []int32) (int, error) {
res, err := sr.DB.Model(emptySystem).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
func InitDbManager(pdb *database.DBManager) {
db := pdb.Db
SystemRep = SystemRepository{db}
DomainRep = DomainRepository{db}
ServiceRep = ServiceRepository{db}
AppRep = AppRepository{db}
TokenRep = TokenRepository{db}
}
-45
View File
@@ -1,45 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
type TokenRepository struct {
DB orm.DB
}
var (
emptyToken = &entity.Token{}
TokenRep TokenRepository
)
func (tr *TokenRepository) SaveToken(token entity.Token) (entity.Token, error) {
_, err := tr.DB.Model(&token).Insert()
return token, err
}
func (tr *TokenRepository) GetTokenById(id string) (*entity.Token, error) {
token := &entity.Token{Token: id}
err := tr.DB.Select(token)
if err == pg.ErrNoRows {
return nil, nil
}
return token, err
}
func (tr *TokenRepository) GetTokensByAppId(appId ...int32) ([]entity.Token, error) {
var res = make([]entity.Token, 0)
err := tr.DB.Model(&res).Where("app_id IN (?)", pg.In(appId)).Order("created_at DESC").Select()
return res, err
}
func (tr *TokenRepository) DeleteTokens(tokens []string) (int, error) {
res, err := tr.DB.Model(emptyToken).Where("token IN (?)", pg.In(tokens)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
+153
View File
@@ -0,0 +1,153 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type AccessList struct {
db db.DB
}
func NewAccessList(db db.DB) AccessList {
return AccessList{
db: db,
}
}
func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error) {
q := `
SELECT app_id, method, value
FROM access_list
WHERE app_id = $1 AND method = $2
`
result := entity.AccessList{}
err := r.db.SelectRow(ctx, &result, q, appId, method)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrAccessListNotFound
}
return nil, errors.WithMessagef(err, "select db")
}
return &result, nil
}
func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
q := `
SELECT app_id, method, value
FROM access_list
WHERE app_id = $1
`
result := make([]entity.AccessList, 0)
err := r.db.Select(ctx, &result, q, appId)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []int) ([]entity.AccessList, error) {
q, args, err := query.New().
Select("app_id", "method", "value").
From("access_list").
Where(squirrel.Eq{"app_id": appIdList}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.AccessList, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error {
qBuilder := query.New().
Insert("access_list").
Columns("app_id", "method", "value")
for _, e := range entity {
qBuilder = qBuilder.Values(e.AppId, e.Method, e.Value)
}
q, args, err := qBuilder.ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, q, args...)
if err != nil {
return errors.WithMessage(err, "exec db")
}
return nil
}
func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) {
q := `
INSERT INTO access_list
(app_id, method, value)
VALUES ($1, $2, $3)
ON CONFLICT (app_id, method)
DO UPDATE
SET (value) = (SELECT EXCLUDED.value)
`
result, err := r.db.Exec(ctx, q, e.AppId, e.Method, e.Value)
if err != nil {
return 0, errors.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 AccessList) DeleteAccessList(ctx context.Context, appId int, methods []string) error {
q, args, err := query.New().
Delete("access_list").
Where(squirrel.Eq{
"app_id": appId,
"method": methods,
}).
Suffix("RETURNING app_id, method, value").
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, q, args...)
if err != nil {
return errors.WithMessagef(err, "exec db")
}
return nil
}
func (r AccessList) DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
q := `
DELETE FROM access_list
WHERE app_id = $1
RETURNING app_id, method, value
`
result := make([]entity.AccessList, 0)
err := r.db.Select(ctx, &result, q, appId)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
+155
View File
@@ -0,0 +1,155 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Application struct {
db db.DB
}
func NewApplication(db db.DB) Application {
return Application{
db: db,
}
}
func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Application, error) {
q := `
SELECT id, name, description, service_id, type, created_at, updated_at
FROM application
WHERE id = $1
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrApplicationNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) {
q, args, err := query.New().
Select("id", "name", "description", "service_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, "select db")
}
return result, nil
}
func (r Application) GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error) {
q, args, err := query.New().
Select("id", "name", "description", "service_id", "type", "created_at", "updated_at").
From("application").
Where(squirrel.Eq{"service_id": serviceIdList}).
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, "select db")
}
return result, nil
}
func (r Application) GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error) {
q := `
SELECT id, name, description, service_id, type, created_at, updated_at
FROM application
WHERE name = $1 AND service_id = $2
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, name, serviceId)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (
*entity.Application, error) {
q := `
INSERT INTO application
(name, description, service_id, type)
VALUES ($1, $2, $3, $4)
RETURNING id, name, description, service_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, name, desc, serviceId, appType)
if err != nil {
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) {
q := `
UPDATE application
SET name = $2,
description = $3
WHERE id = $1
RETURNING id, name, description, service_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id, name, description)
if err != nil {
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) {
q, args, err := query.New().
Delete("application").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessage(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessage(err, "get rows affected")
}
return int(rowsAffected), nil
}
+153
View File
@@ -0,0 +1,153 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Domain struct {
db db.DB
}
func NewDomain(db db.DB) Domain {
return Domain{
db: db,
}
}
func (r Domain) GetDomainById(ctx context.Context, id int) (*entity.Domain, error) {
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE id = $1
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.Domain, error) {
q, args, err := query.New().
Select("id", "name", "description", "system_id", "created_at", "updated_at").
From("domain").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Domain, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessage(err, "select db")
}
return result, nil
}
func (r Domain) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) {
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE system_id = $1
ORDER BY created_at DESC
`
result := make([]entity.Domain, 0)
err := r.db.Select(ctx, &result, q, systemId)
if err != nil {
return nil, errors.WithMessage(err, "select db")
}
return result, nil
}
func (r Domain) GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) {
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE name = $1 AND system_id = $2
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, systemId)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) {
q := `
INSERT INTO domain
(name, description, system_id)
VALUES ($1, $2, $3)
RETURNING id, name, description, system_id, created_at, updated_at
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, desc, systemId)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) {
q := `
UPDATE domain
SET name = $1, description = $2
WHERE id = $3
RETURNING id, name, description, system_id, created_at, updated_at
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) {
q, args, err := query.New().
Delete("domain").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
+156
View File
@@ -0,0 +1,156 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Service struct {
db db.DB
}
func NewService(db db.DB) Service {
return Service{
db: db,
}
}
func (r Service) GetServiceById(ctx context.Context, id int) (*entity.Service, error) {
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM service
WHERE id = $1
`
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Service) GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("service").
Where(squirrel.Eq{"id": idList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Service, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Service) GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("service").
Where(squirrel.Eq{"domain_id": domainIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Service, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Service) GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error) {
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM service
WHERE name = $1 AND domain_id = $2
`
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, name, domainId)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select db")
}
return &result, nil
}
func (r Service) CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error) {
q := `
INSERT INTO service
(name, description, domain_id)
VALUES ($1, $2, $3)
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, name, desc, domainId)
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Service) UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error) {
q := `
UPDATE service
SET name = $1, description = $2
WHERE id = $3
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Service) DeleteService(ctx context.Context, idList []int) (int, error) {
q, args, err := query.New().
Delete("service").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
+120
View File
@@ -0,0 +1,120 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Token struct {
db db.DB
}
func NewToken(db db.DB) Token {
return Token{
db: db,
}
}
func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) {
q := `
INSERT INTO token
(token, app_id, expire_time)
VALUES ($1, $2, $3)
RETURNING token, app_id, expire_time, created_at
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token, appId, expireTime)
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, error) {
q := `
SELECT token, app_id, expire_time, created_at
FROM system
WHERE token = $1
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token)
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) {
q, args, err := query.New().
Select("token", "app_id", "expire_time", "created_at").
From("token").
Where(squirrel.Eq{"app_id": appIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Token, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
q, args, err := query.New().
Delete("token").
Where(squirrel.Eq{"token": tokens}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
func (r Token) AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error) {
q := `
SELECT system_id, domain_id, service_id, app_id, token.expire_time, token.created_at
FROM token
LEFT JOIN application
ON token.app_id = application.id
LEFT JOIN service
ON application.service_id = service.id
LEFT JOIN domain
ON service.domain_id = domain.id
WHERE token = $1
`
result := entity.AuthData{}
err := r.db.SelectRow(ctx, &result, q, token)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrTokenNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
+199
View File
@@ -0,0 +1,199 @@
package routes
import (
"github.com/integration-system/isp-kit/cluster"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/grpc/endpoint"
"github.com/integration-system/isp-kit/grpc/isp"
"isp-system-service/controller"
)
type Controllers struct {
AccessList controller.AccessList
Domain controller.Domain
Service controller.Service
Application controller.Application
Token controller.Token
Secure controller.Secure
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
return endpointDescriptors(Controllers{})
}
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
muxer := grpc.NewMux()
for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
return muxer
}
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return concatCluster([][]cluster.EndpointDescriptor{
secureCluster(c),
accessListCluster(c),
domainCluster(c),
serviceCluster(c),
applicationCluster(c),
tokenCluster(c),
})
}
func secureCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/secure/authenticate",
Inner: true,
Handler: c.Secure.Authenticate,
},
{
Path: "system/secure/authorize",
Inner: true,
Handler: c.Secure.Authorize,
},
}
}
func accessListCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/access_list/get_by_id",
Inner: true,
Handler: c.AccessList.GetById,
},
{
Path: "system/access_list/set_one",
Inner: true,
Handler: c.AccessList.SetOne,
},
{
Path: "system/access_list/set_list",
Inner: true,
Handler: c.AccessList.SetList,
},
}
}
func domainCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/domain/get_domains_by_system_id",
Inner: true,
Handler: c.Domain.GetBySystemId,
},
{
Path: "system/domain/create_update_domain",
Inner: true,
Handler: c.Domain.CreateUpdate,
},
{
Path: "system/domain/get_domain_by_id",
Inner: true,
Handler: c.Domain.GetById,
},
{
Path: "system/domain/delete_domains",
Inner: true,
Handler: c.Domain.Delete,
},
}
}
func serviceCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/service/get_service",
Inner: true,
Handler: c.Service.Get,
},
{
Path: "system/service/get_services_by_domain_id",
Inner: true,
Handler: c.Service.GetByDomainId,
},
{
Path: "system/service/create_update_service",
Inner: true,
Handler: c.Service.CreateUpdate,
},
{
Path: "system/service/get_service_by_id",
Inner: true,
Handler: c.Service.GetById,
},
{
Path: "system/service/delete_service",
Inner: true,
Handler: c.Service.Delete,
},
}
}
func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/application/get_applications",
Inner: true,
Handler: c.Application.GetByIdList,
},
{
Path: "system/application/get_applications_by_service_id",
Inner: true,
Handler: c.Application.GetByServiceId,
},
{
Path: "system/application/create_update_application",
Inner: true,
Handler: c.Application.CreateUpdate,
},
{
Path: "system/application/get_application_by_id",
Inner: true,
Handler: c.Application.GetById,
},
{
Path: "system/application/delete_applications",
Inner: true,
Handler: c.Application.Delete,
},
{
Path: "system/application/get_system_tree",
Inner: true,
Handler: c.Application.GetSystemTree,
},
}
}
func tokenCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/token/create_token",
Inner: true,
Handler: c.Token.Create,
},
{
Path: "system/token/revoke_tokens",
Inner: true,
Handler: c.Token.Revoke,
},
{
Path: "system/token/revoke_tokens_for_app",
Inner: true,
Handler: c.Token.RevokeForApp,
},
{
Path: "system/token/get_tokens_by_app_id",
Inner: true,
Handler: c.Token.GetByAppId,
},
}
}
func concatCluster(clusters [][]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
var result []cluster.EndpointDescriptor
for _, c := range clusters {
result = append(result, c...)
}
return result
}
+160
View File
@@ -0,0 +1,160 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IAccessListAccessListRep interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
}
type IAccessListApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
}
type IAccessListSetOneTx interface {
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
}
type IAccessListSetListTx interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error
DeleteAccessList(ctx context.Context, appId int, methods []string) error
DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
}
type IAccessListTxRunner interface {
AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetOneTx) error) error
AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetListTx) error) error
}
type AccessList struct {
tx IAccessListTxRunner
accessListRep IAccessListAccessListRep
applicationRep IAccessListApplicationRep
}
func NewAccessList(
tx IAccessListTxRunner,
accessListRep IAccessListAccessListRep,
applicationRep IAccessListApplicationRep,
) AccessList {
return AccessList{
tx: tx,
accessListRep: accessListRep,
applicationRep: applicationRep,
}
}
func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error) {
_, err := s.applicationRep.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
accessList, err := s.accessListRep.GetAccessListByAppId(ctx, appId)
if err != nil {
return nil, errors.WithMessagef(err, "get access list by app_id")
}
methodInfos := make([]domain.MethodInfo, len(accessList))
for i, access := range accessList {
methodInfos[i] = domain.MethodInfo{
Method: access.Method,
Value: access.Value,
}
}
return methodInfos, nil
}
func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
_, err := s.applicationRep.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 IAccessListSetOneTx) error {
resp, err = tx.UpsertAccessList(ctx, entity.AccessList{
AppId: request.AppId,
Method: request.Method,
Value: request.Value,
})
if err != nil {
return errors.WithMessagef(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.applicationRep.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 IAccessListSetListTx) error {
if req.RemoveOld {
_, err = tx.DeleteAccessListByAppId(ctx, req.AppId)
if err != nil {
return errors.WithMessage(err, "delete access list by app_id")
}
}
newAccessList := make([]entity.AccessList, len(req.Methods))
updateMethods := make([]string, len(req.Methods))
for i, m := range req.Methods {
updateMethods[i] = m.Method
newAccessList[i] = entity.AccessList{
AppId: req.AppId,
Method: m.Method,
Value: m.Value,
}
}
if len(newAccessList) > 0 {
err = tx.DeleteAccessList(ctx, req.AppId, updateMethods)
if err != nil {
return errors.WithMessage(err, "delete access_list")
}
err = tx.InsertArrayAccessList(ctx, newAccessList)
if err != nil {
return errors.WithMessage(err, "insert access_list")
}
}
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "transaction access list set list")
}
accessList, err := s.accessListRep.GetAccessListByAppId(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessagef(err, "get access list by app_id")
}
methodInfos := make([]domain.MethodInfo, len(accessList))
for i, access := range accessList {
methodInfos[i] = domain.MethodInfo{
Method: access.Method,
Value: access.Value,
}
}
return methodInfos, nil
}
+294
View File
@@ -0,0 +1,294 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IApplicationApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error)
GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error)
GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error)
CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (*entity.Application, error)
UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error)
}
type IApplicationTokenRep interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
}
type IApplicationServiceRep interface {
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error)
}
type IApplicationDomainRep interface {
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
}
type IApplicationDeleteTx interface {
DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error)
}
type IApplicationTxRunner interface {
ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx IApplicationDeleteTx) error) error
}
type Application struct {
tx IApplicationTxRunner
applicationRep IApplicationApplicationRep
domainRep IApplicationDomainRep
serviceRep IApplicationServiceRep
tokenRep IApplicationTokenRep
}
func NewApplication(
tx IApplicationTxRunner,
applicationRep IApplicationApplicationRep,
domainRep IApplicationDomainRep,
serviceRep IApplicationServiceRep,
tokenRep IApplicationTokenRep,
) Application {
return Application{
tx: tx,
applicationRep: applicationRep,
domainRep: domainRep,
serviceRep: serviceRep,
tokenRep: tokenRep,
}
}
func (s Application) GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error) {
application, err := s.applicationRep.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
arr, err := s.EnrichWithTokens(ctx, []entity.Application{*application})
if err != nil {
return nil, errors.WithMessage(err, "enrich application with tokens")
}
return arr[0], nil
}
func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error) {
res, err := s.applicationRep.GetApplicationByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get application by id list")
}
return s.EnrichWithTokens(ctx, res)
}
func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) {
arr, err := s.applicationRep.GetApplicationByServiceIdList(ctx, []int{id})
if err != nil {
return nil, errors.WithMessage(err, "get application by service_id")
}
return s.EnrichWithTokens(ctx, arr)
}
func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) {
domainEntityList, err := s.domainRep.GetDomainBySystemId(ctx, systemId)
if err != nil {
return nil, errors.WithMessage(err, "get domains by system_id")
}
if len(domainEntityList) == 0 {
return []*domain.DomainWithService{}, nil
}
result := make([]*domain.DomainWithService, len(domainEntityList))
resultByDomainId := make(map[int]*domain.DomainWithService, len(domainEntityList))
domainIdList := make([]int, len(domainEntityList))
for i, domainEntity := range domainEntityList {
domainIdList[i] = domainEntity.Id
description := ""
if domainEntity.Description != nil {
description = *domainEntity.Description
}
r := &domain.DomainWithService{
Id: domainEntity.Id,
Name: domainEntity.Name,
Description: description,
Services: make([]*domain.ServiceWithApps, 0),
}
resultByDomainId[domainEntity.Id] = r
result[i] = r
}
serviceEntityList, err := s.serviceRep.GetServiceByDomainId(ctx, domainIdList)
if err != nil {
return nil, errors.WithMessage(err, "get service by domain_id")
}
serviceIdList := make([]int, len(serviceEntityList))
resultServiceByServiceId := make(map[int]*domain.ServiceWithApps, len(serviceEntityList))
for i, serviceEntity := range serviceEntityList {
serviceIdList[i] = serviceEntity.Id
description := ""
if serviceEntity.Description != nil {
description = *serviceEntity.Description
}
resultService := &domain.ServiceWithApps{
Id: serviceEntity.Id,
Name: serviceEntity.Name,
Description: description,
Apps: make([]*domain.ApplicationSimple, 0),
}
r := resultByDomainId[serviceEntity.DomainId]
r.Services = append(r.Services, resultService)
resultServiceByServiceId[serviceEntity.Id] = resultService
}
applicationEntityList, err := s.applicationRep.GetApplicationByServiceIdList(ctx, serviceIdList)
if err != nil {
return nil, errors.WithMessagef(err, "get application by service_id")
}
for _, applicationEntity := range applicationEntityList {
resultService := resultServiceByServiceId[applicationEntity.ServiceId]
description := ""
if applicationEntity.Description != nil {
description = *applicationEntity.Description
}
resultService.Apps = append(resultService.Apps, &domain.ApplicationSimple{
Id: applicationEntity.Id,
Name: applicationEntity.Name,
Type: applicationEntity.Type,
Description: description,
Tokens: make([]domain.Token, 0),
})
}
return result, nil
}
func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
existed, err := s.applicationRep.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
case err != nil:
return nil, errors.WithMessage(err, "get application by name and service_id")
}
_, err = s.serviceRep.GetServiceById(ctx, req.ServiceId)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
}
if req.Id == 0 {
if existed != nil {
return nil, domain.ErrApplicationDuplicateName
}
_, err = s.applicationRep.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId)
if err != nil {
return nil, errors.WithMessage(err, "get application by name and service_id")
}
app, err := s.applicationRep.CreateApplication(ctx, req.Name, req.Description, req.ServiceId, req.Type)
if err != nil {
return nil, errors.WithMessage(err, "create application")
}
result, err := s.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessage(err, "enrich application with tokens")
}
return result[0], nil
}
if existed != nil && existed.Id != req.Id {
return nil, domain.ErrApplicationDuplicateName
}
_, err = s.applicationRep.GetApplicationById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
app, err := s.applicationRep.UpdateApplication(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update application")
}
result, err := s.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessage(err, "enrich application with tokens")
}
return result[0], nil
}
func (s Application) Delete(ctx context.Context, idList []int) (int, error) {
count := 0
err := s.tx.ApplicationDeleteTx(ctx, func(ctx context.Context, tx IApplicationDeleteTx) 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.tokenRep.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) convertApplication(req entity.Application) domain.Application {
desc := ""
if req.Description != nil {
desc = *req.Description
}
return domain.Application{
Id: req.Id,
Name: req.Name,
Description: desc,
ServiceId: req.ServiceId,
Type: req.Type,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
}
+119
View File
@@ -0,0 +1,119 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IDomainDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error)
CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error)
UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error)
DeleteDomain(ctx context.Context, idList []int) (int, error)
}
type Domain struct {
domainRep IDomainDomainRep
}
func NewDomain(
domainRep IDomainDomainRep,
) Domain {
return Domain{
domainRep: domainRep,
}
}
func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) {
domainEntity, err := s.domainRep.GetDomainById(ctx, id)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
result := s.convertDomain(*domainEntity)
return &result, nil
}
func (s Domain) GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error) {
domainEntity, err := s.domainRep.GetDomainBySystemId(ctx, systemId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by system_id")
}
result := make([]domain.Domain, len(domainEntity))
for i := range domainEntity {
result[i] = s.convertDomain(domainEntity[i])
}
return result, nil
}
func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error) {
existed, err := s.domainRep.GetDomainByNameAndSystemId(ctx, req.Name, systemId)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
case err != nil:
return nil, errors.WithMessage(err, "get domain by name and system_id")
}
if req.Id == 0 {
if existed != nil {
return nil, domain.ErrDomainDuplicateName
}
domainEntity, err := s.domainRep.CreateDomain(ctx, req.Name, req.Description, systemId)
if err != nil {
return nil, errors.WithMessagef(err, "create domain")
}
result := s.convertDomain(*domainEntity)
return &result, nil
}
if existed != nil && existed.Id != req.Id {
return nil, domain.ErrDomainDuplicateName
}
_, err = s.domainRep.GetDomainById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
domainEntity, err := s.domainRep.UpdateDomain(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update domain")
}
result := s.convertDomain(*domainEntity)
return &result, nil
}
func (s Domain) Delete(ctx context.Context, idList []int) (int, error) {
result, err := s.domainRep.DeleteDomain(ctx, idList)
if err != nil {
return 0, errors.WithMessage(err, "delete domain")
}
return result, nil
}
func (s Domain) convertDomain(req entity.Domain) domain.Domain {
desc := ""
if req.Description != nil {
desc = *req.Description
}
result := domain.Domain{
Id: req.Id,
Name: req.Name,
Description: desc,
SystemId: req.SystemId,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
return result
}
+61
View File
@@ -0,0 +1,61 @@
package secure
import (
"context"
"time"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type TokenRep interface {
AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error)
}
type AccessListRep interface {
GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error)
}
type Service struct {
tokenRep TokenRep
accessListRep AccessListRep
}
func NewService(
tokenRep TokenRep,
accessListRep AccessListRep,
) Service {
return Service{
tokenRep: tokenRep,
accessListRep: accessListRep,
}
}
func (s Service) Authenticate(ctx context.Context, token string) (*domain.AuthData, error) {
authData, err := s.tokenRep.AuthDataByToken(ctx, token)
if err != nil {
return nil, errors.WithMessage(err, "get auth data by token")
}
if authData.ExpireTime != -1 &&
authData.CreatedAt.Add(time.Millisecond*time.Duration(authData.ExpireTime)).Before(time.Now().UTC()) {
return nil, domain.ErrTokenExpired
}
return &domain.AuthData{
SystemId: authData.SystemId,
DomainId: authData.DomainId,
ServiceId: authData.ServiceId,
ApplicationId: authData.AppId,
}, nil
}
func (s Service) Authorize(ctx context.Context, appId int, endpoint string) (bool, error) {
accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod(ctx, appId, endpoint)
if err != nil {
return false, errors.WithMessage(err, "get access list by app_id and method")
}
return accessList.Value, nil
}
+145
View File
@@ -0,0 +1,145 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IServiceServiceRep interface {
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error)
GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error)
GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error)
CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error)
UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error)
DeleteService(ctx context.Context, idList []int) (int, error)
}
type IServiceDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
}
type Service struct {
domainRep IServiceDomainRep
serviceRep IServiceServiceRep
}
func NewService(
domainRep IServiceDomainRep,
serviceRep IServiceServiceRep,
) Service {
return Service{
domainRep: domainRep,
serviceRep: serviceRep,
}
}
func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) {
serviceEntity, err := s.serviceRep.GetServiceById(ctx, id)
if err != nil {
return nil, errors.WithMessagef(err, "get service by id")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error) {
serviceEntity, err := s.serviceRep.GetServiceByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get system by id list")
}
result := make([]domain.Service, len(serviceEntity))
for i := range serviceEntity {
result[i] = s.convertService(serviceEntity[i])
}
return result, nil
}
func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error) {
serviceEntity, err := s.serviceRep.GetServiceByDomainId(ctx, []int{domainId})
if err != nil {
return nil, errors.WithMessage(err, "get system by id list")
}
result := make([]domain.Service, len(serviceEntity))
for i := range serviceEntity {
result[i] = s.convertService(serviceEntity[i])
}
return result, nil
}
func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
existed, err := s.serviceRep.GetServiceByNameAndDomainId(ctx, req.Name, req.DomainId)
switch {
case errors.Is(err, domain.ErrServiceNotFound):
case err != nil:
return nil, errors.WithMessage(err, "get service by name and domain_id")
}
_, err = s.domainRep.GetDomainById(ctx, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
if req.Id == 0 {
if existed != nil {
return nil, domain.ErrDomainDuplicateName
}
serviceEntity, err := s.serviceRep.CreateService(ctx, req.Name, req.Description, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "create service")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
if existed != nil && existed.Id != req.Id {
return nil, domain.ErrDomainDuplicateName
}
_, err = s.serviceRep.GetServiceById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
}
serviceEntity, err := s.serviceRep.UpdateService(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update service")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
func (s Service) Delete(ctx context.Context, idList []int) (int, error) {
result, err := s.serviceRep.DeleteService(ctx, idList)
if err != nil {
return 0, errors.WithMessage(err, "delete service")
}
return result, nil
}
func (s Service) convertService(req entity.Service) domain.Service {
desc := ""
if req.Description != nil {
desc = *req.Description
}
result := domain.Service{
Id: req.Id,
Name: req.Name,
Description: desc,
DomainId: req.DomainId,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
return result
}
+188
View File
@@ -0,0 +1,188 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type ITokenSource interface {
CreateApplicationToken() (string, error)
}
type ITokenAppEnrich interface {
EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error)
}
type ITokenApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
}
type ITokenServiceRep interface {
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
}
type ITokenDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
}
type ITokenTokenRep interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
}
type ITokenCreateTx interface {
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
}
type ITokenRevokeTx interface {
DeleteToken(ctx context.Context, tokens []string) (int, error)
}
type ITokenTxRunner interface {
TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx ITokenCreateTx) error) error
TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx ITokenRevokeTx) error) error
}
type Token struct {
jwt ITokenSource
appEnrich ITokenAppEnrich
tx ITokenTxRunner
appRep ITokenApplicationRep
domainRep ITokenDomainRep
serviceRep ITokenServiceRep
tokenRep ITokenTokenRep
}
func NewToken(
jwtGenerate ITokenSource,
appEnrich ITokenAppEnrich,
tx ITokenTxRunner,
appRep ITokenApplicationRep,
domainRep ITokenDomainRep,
serviceRep ITokenServiceRep,
tokenRep ITokenTokenRep,
) Token {
return Token{
appEnrich: appEnrich,
jwt: jwtGenerate,
tx: tx,
appRep: appRep,
domainRep: domainRep,
serviceRep: serviceRep,
tokenRep: tokenRep,
}
}
func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error) {
tokenEntity, err := s.tokenRep.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.appRep.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessagef(err, "get application by id")
}
serviceEntity, err := s.serviceRep.GetServiceById(ctx, applicationEntity.ServiceId)
if err != nil {
return nil, errors.WithMessagef(err, "get service by id")
}
_, err = s.domainRep.GetDomainById(ctx, serviceEntity.DomainId)
if err != nil {
return nil, errors.WithMessagef(err, "get domain by id")
}
token, err := s.jwt.CreateApplicationToken()
if err != nil {
return nil, errors.WithMessagef(err, "create application token")
}
err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx ITokenCreateTx) error {
_, err = tx.SaveToken(ctx, token, req.AppId, req.ExpireTimeMs)
if err != nil {
return errors.WithMessagef(err, "tx save token")
}
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "token create transaction")
}
arr, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*applicationEntity})
if err != nil {
return nil, errors.WithMessagef(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.appRep.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessagef(err, "get application by id")
}
_, err = s.revokeTokens(ctx, req.Tokens)
if err != nil {
return nil, errors.WithMessagef(err, "reboke tokens")
}
res, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessagef(err, "application enrich")
}
return res[0], nil
}
func (s Token) RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error) {
tokens, err := s.tokenRep.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 ITokenRevokeTx) error {
deleted, err := tx.DeleteToken(ctx, tokens)
if err != nil {
return errors.WithMessagef(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
}
+26
View File
@@ -0,0 +1,26 @@
package service
import (
"crypto/rand"
"encoding/hex"
"github.com/pkg/errors"
)
type TokenSource struct {
}
func NewTokenSource() TokenSource {
return TokenSource{}
}
func (s TokenSource) CreateApplicationToken() (string, error) {
cryptoRand := make([]byte, 128) //nolint:gomnd
_, err := rand.Read(cryptoRand)
if err != nil {
return "", errors.WithMessage(err, "crypto/rand read")
}
random := hex.EncodeToString(cryptoRand)
return random, nil
}
+56
View File
@@ -0,0 +1,56 @@
package tests
import (
"github.com/integration-system/isp-kit/test/dbt"
"isp-system-service/entity"
)
func InsertDomain(db *dbt.TestDb, value entity.Domain) {
q := `
INSERT INTO domain
(id, name, description, system_id, created_at, updated_at)
VALUES
(:id, :name, :description, 1, :created_at, :updated_at)
`
db.Must().ExecNamed(q, value)
}
func InsertService(db *dbt.TestDb, value entity.Service) {
q := `
INSERT INTO service
(id, name, description, domain_id, created_at, updated_at)
VALUES
(:id, :name, :description, :domain_id, :created_at, :updated_at)
`
db.Must().ExecNamed(q, value)
}
func InsertApplication(db *dbt.TestDb, value entity.Application) {
q := `
INSERT INTO application
(id, name, description, service_id, created_at, updated_at)
VALUES
(:id, :name, :description, :service_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)
}
+203
View File
@@ -0,0 +1,203 @@
package tests
import (
"context"
"testing"
"time"
"github.com/integration-system/isp-kit/dbx/migration"
"github.com/integration-system/isp-kit/grpc/client"
"github.com/integration-system/isp-kit/test"
"github.com/integration-system/isp-kit/test/dbt"
"github.com/integration-system/isp-kit/test/grpct"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/migrations"
)
func TestSecureSuite(t *testing.T) {
suite.Run(t, &SecureSuite{})
}
type SecureSuite struct {
suite.Suite
test *test.Test
require *require.Assertions
testDb *dbt.TestDb
api *client.Client
}
func (s *SecureSuite) SetupSuite() {
s.test, s.require = test.New(s.T())
s.testDb = dbt.New(s.test)
migrations.Initialize.SetParams("../migrations", s.testDb.Schema())
db, err := s.testDb.DB()
s.require.NoError(err)
err = migration.NewRunner(db.DB.DB, "../migrations").Run()
s.require.NoError(err)
locator := assembly.NewLocator(s.testDb, s.test.Logger())
handler := locator.Handler(conf.Remote{})
_, s.api = grpct.TestServer(s.test, handler)
createdTime := time.Now().UTC()
InsertDomain(s.testDb, entity.Domain{
Id: 3, Name: "test_domain", SystemId: 1, CreatedAt: createdTime, UpdatedAt: createdTime,
})
InsertService(s.testDb, entity.Service{
Id: 5, Name: "test_service", DomainId: 3, CreatedAt: createdTime, UpdatedAt: createdTime,
})
InsertApplication(s.testDb, entity.Application{
Id: 7, Name: "test_application", ServiceId: 5, CreatedAt: createdTime, UpdatedAt: createdTime,
})
}
func (s *SecureSuite) TestAuthenticate_Success() {
InsertToken(s.testDb, entity.Token{
Token: "test_token_success", AppId: 7, ExpireTime: -1, CreatedAt: time.Now().UTC(),
})
result := domain.AuthenticateResponse{}
err := s.api.Invoke("system/secure/authenticate").
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_success",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
SystemId: 1,
DomainId: 3,
ServiceId: 5,
ApplicationId: 7,
},
}, result)
}
func (s *SecureSuite) TestAuthenticate_NotFound() {
result := domain.AuthenticateResponse{}
err := s.api.Invoke("system/secure/authenticate").
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_not_found",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenNotFound.Error(),
AuthData: nil,
}, result)
}
func (s *SecureSuite) TestAuthenticate_NotExpired() {
InsertToken(s.testDb, entity.Token{
Token: "test_token_not_expired", AppId: 7, ExpireTime: int((time.Hour).Milliseconds()), CreatedAt: time.Now().UTC(),
})
result := domain.AuthenticateResponse{}
err := s.api.Invoke("system/secure/authenticate").
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_not_expired",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
SystemId: 1,
DomainId: 3,
ServiceId: 5,
ApplicationId: 7,
},
}, result)
}
func (s *SecureSuite) TestAuthenticate_Expired() {
InsertToken(s.testDb, entity.Token{
Token: "test_token_expired", AppId: 7, ExpireTime: 0, CreatedAt: time.Now().UTC(),
})
result := domain.AuthenticateResponse{}
err := s.api.Invoke("system/secure/authenticate").
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_expired",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenExpired.Error(),
AuthData: nil,
}, result)
}
func (s *SecureSuite) TestAuthorize_Success_True() {
InsertAccessList(s.testDb, entity.AccessList{
AppId: 7,
Method: "endpoint/available",
Value: true,
})
result := domain.AuthorizeResponse{}
err := s.api.Invoke("system/secure/authorize").
JsonRequestBody(domain.AuthorizeRequest{
ApplicationId: 7,
Endpoint: "endpoint/available",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: true,
}, result)
}
func (s *SecureSuite) TestAuthorize_Success_False() {
InsertAccessList(s.testDb, entity.AccessList{
AppId: 7,
Method: "endpoint/not_available",
Value: false,
})
result := domain.AuthorizeResponse{}
err := s.api.Invoke("system/secure/authorize").
JsonRequestBody(domain.AuthorizeRequest{
ApplicationId: 7,
Endpoint: "endpoint/not_available",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: false,
}, result)
}
func (s *SecureSuite) TestAuthorize_NotFound() {
result := domain.AuthorizeResponse{}
err := s.api.Invoke("system/secure/authorize").
JsonRequestBody(domain.AuthorizeRequest{
ApplicationId: 7,
Endpoint: "endpoint/not_found",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: false,
}, result)
}
+84
View File
@@ -0,0 +1,84 @@
package transaction
import (
"context"
"github.com/integration-system/isp-kit/db"
"isp-system-service/repository"
"isp-system-service/service"
)
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.IAccessListSetOneTx) 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.IAccessListSetListTx) 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.IApplicationDeleteTx) 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.ITokenCreateTx) 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.ITokenRevokeTx) 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,
})
})
}