Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63a47ee7b5 | ||
|
|
cecbda3e43 | ||
|
|
2cea7a516c | ||
|
|
e544074dbf | ||
|
|
e2af9c4978 | ||
|
|
24a8ea2578 | ||
|
|
ebc99c6ae4 | ||
|
|
7bac2e403f | ||
|
|
1ea3ef186c | ||
|
|
1d1c5dbde6 | ||
|
|
11ef48bbeb | ||
|
|
5263e1504d | ||
|
|
06acaba5b3 | ||
|
|
2f29af5e76 | ||
|
|
3e707244dd | ||
|
|
fa8bc6c1b7 | ||
|
|
71498785ea | ||
|
|
aa68f6028a | ||
|
|
11d705124d | ||
|
|
b8ef777339 | ||
|
|
7589203719 | ||
|
|
67e9b563b4 | ||
|
|
bca4b4adaf | ||
|
|
14224c2de5 | ||
|
|
4e01670ceb | ||
|
|
e0a35868af | ||
|
|
888a71df57 | ||
|
|
4fecfaa701 | ||
|
|
884aa6a439 | ||
|
|
c14f8441fb | ||
|
|
5bd389757c | ||
|
|
c32459f73d | ||
|
|
911a5bdf46 | ||
|
|
3ee480f5e3 | ||
|
|
5daaea50a1 | ||
|
|
3a66223a89 | ||
|
|
674dd99f92 | ||
|
|
eb066cb055 | ||
|
|
5175d87e08 | ||
|
|
1db559469f | ||
|
|
84c3529a66 | ||
|
|
896f08a8cb | ||
|
|
86e96b79b1 | ||
|
|
f23359dfcb | ||
|
|
ea81d2716f | ||
|
|
e43a27e5d3 | ||
|
|
f122ad081b | ||
|
|
81c8e86eb4 | ||
|
|
d81961e9d6 | ||
|
|
45bc24711e | ||
|
|
c9ce1158ea | ||
|
|
b1c4322c98 | ||
|
|
5625f00174 | ||
|
|
f2c3f9dea5 | ||
|
|
2d7adad800 | ||
|
|
939a94b704 | ||
|
|
bbeb6eb735 | ||
|
|
5ee5854831 | ||
|
|
5ee9d85682 | ||
|
|
0442513f43 | ||
|
|
69664d764a | ||
|
|
67ff6571be | ||
|
|
a2c5dab4a7 | ||
|
|
d2da566f25 | ||
|
|
d19bb44bb6 | ||
|
|
c036063534 | ||
|
|
ec327424c9 | ||
|
|
71e0768231 | ||
|
|
4da0d51b5b | ||
|
|
1976e3aa29 | ||
|
|
07540b762e | ||
|
|
641aef0150 | ||
|
|
c17970678b | ||
|
|
b1d5aae316 | ||
|
|
2637770d82 | ||
|
|
051c2f08c4 | ||
|
|
7de82862bd | ||
|
|
187e1f07a0 | ||
|
|
f693afee79 | ||
|
|
d489c4281e | ||
|
|
e11f65ac05 | ||
|
|
41ce47f7e0 | ||
|
|
09dbce4125 | ||
|
|
20f3fb7b5e | ||
|
|
a18deb8762 | ||
|
|
72b37d77e2 | ||
|
|
494ffac97c | ||
|
|
841c75b457 | ||
|
|
fbd64f9d47 | ||
|
|
9b09326317 | ||
|
|
601a690901 | ||
|
|
4947ac5d4e | ||
|
|
df693c0294 | ||
|
|
3f65b11a65 | ||
|
|
38f22dfdf8 | ||
|
|
302e9b7a54 | ||
|
|
996abfda16 | ||
|
|
fb882e5c5c | ||
|
|
3a2ad9219c | ||
|
|
7514be3309 | ||
|
|
4f67872d3f | ||
|
|
558682da1e | ||
|
|
40b37f8900 | ||
|
|
4791c6dbaf | ||
|
|
05ac07c3bb | ||
|
|
4cc5edeed0 | ||
|
|
830ef54663 | ||
|
|
0cb61c184a | ||
|
|
e9030f6282 | ||
|
|
51081ca964 | ||
|
|
cb59605eba | ||
|
|
d7779efdbd | ||
|
|
b89e10a0bd | ||
|
|
9bf05f1e9d | ||
|
|
8f80bf5742 | ||
|
|
1746acd559 | ||
|
|
b16ac80053 | ||
|
|
635046d221 | ||
|
|
46fc51275e | ||
|
|
055921d711 | ||
|
|
bf8cfff7fa | ||
|
|
3be63ce95a | ||
|
|
f5a38117b1 | ||
|
|
21714e0603 | ||
|
|
c966a2cca5 | ||
|
|
c2f154da02 | ||
|
|
2343940930 | ||
|
|
2d6398224f | ||
|
|
ac1457e534 | ||
|
|
b59a5ce858 | ||
|
|
4352c400b4 | ||
|
|
1653289e01 | ||
|
|
cf20571a7d | ||
|
|
e4755abdc8 | ||
|
|
e7935499b6 | ||
|
|
6f48eea3c9 | ||
|
|
4251ca3da9 | ||
|
|
3a564dfae8 | ||
|
|
c4871f210d | ||
|
|
fcebffe4b6 | ||
|
|
a741135dc3 | ||
|
|
7d60f6d51d | ||
|
|
fb0a08ea13 | ||
|
|
10e316049d | ||
|
|
753af57524 | ||
|
|
1f232c4271 | ||
|
|
a7ec10fa39 | ||
|
|
d799b5be60 | ||
|
|
03bbdd1761 | ||
|
|
72a62d1996 | ||
|
|
3552e08f29 | ||
|
|
c2e7c5ab2b | ||
|
|
3b3fc9dcfb | ||
|
|
db7a668875 | ||
|
|
a4b3bfa390 | ||
|
|
c77ab9d5f8 | ||
|
|
e65f5ac03c | ||
|
|
c08782855b | ||
|
|
a5a4dab813 | ||
|
|
03a7b16026 | ||
|
|
9a12e08181 | ||
|
|
cd04e996e1 | ||
|
|
051dea1674 | ||
|
|
c1263fce77 | ||
|
|
f3bc3ce657 | ||
|
|
3beb23d4de | ||
|
|
3f177eb436 | ||
|
|
df15ae228a | ||
|
|
61bdaeaa3d | ||
|
|
03580260e7 | ||
|
|
cf42bed9bf | ||
|
|
c4c0f2ea10 | ||
|
|
c1d4680a02 | ||
|
|
1517f744d3 | ||
|
|
6af7ed9cb8 | ||
|
|
5cff5df97b | ||
|
|
d208ad633e | ||
|
|
a664d5db4a | ||
|
|
7b5e1362be | ||
|
|
b2305c0f12 | ||
|
|
73ab09dc7d | ||
|
|
150d61fb18 | ||
|
|
158962dcfe | ||
|
|
41479adbb0 | ||
|
|
2c1c655fed | ||
|
|
669542b546 | ||
|
|
92021b8a0e | ||
|
|
1bbe8c71ce | ||
|
|
98b79732fa | ||
|
|
d2f56ca43e | ||
|
|
6fcc9e45e3 | ||
|
|
7f7a827a69 | ||
|
|
a915bdf633 | ||
|
|
ef0028c091 | ||
|
|
4cad9cbbb4 | ||
|
|
7f7216b91a | ||
|
|
7e899197ec | ||
|
|
c25d6e3d3b | ||
|
|
da3ae21766 | ||
|
|
84888e8202 | ||
|
|
cccb1fc80b | ||
|
|
d3747e6ff3 | ||
|
|
036200a765 | ||
|
|
fa89426bcc | ||
|
|
8a2752fdaa | ||
|
|
efc521f8fe | ||
|
|
dbf35fc383 | ||
|
|
6e9918dc7b | ||
|
|
b21154afd7 | ||
|
|
234ea0ca38 | ||
|
|
e81028722f | ||
|
|
557491ed05 | ||
|
|
1e6c72ead2 | ||
|
|
bcf3fd576a | ||
|
|
fa3d8f5f14 | ||
|
|
74625d0525 | ||
|
|
a355338d40 | ||
|
|
60fc5d9170 | ||
|
|
0877e05811 | ||
|
|
abcf2162a7 | ||
|
|
0cea0d4f0a | ||
|
|
205c4724d4 | ||
|
|
917982cff1 | ||
|
|
4d1c17f9ae | ||
|
|
45810b4ec8 | ||
|
|
fdd46409cd | ||
|
|
72e89b1c9f | ||
|
|
060c5a09de | ||
|
|
0d5b55f3a1 | ||
|
|
3d29805df6 | ||
|
|
2561479816 | ||
|
|
447d33747a | ||
|
|
56e38174bf | ||
|
|
f90f21ebef | ||
|
|
c6f5f4096b | ||
|
|
d2a1b2394b | ||
|
|
0a2eab739e | ||
|
|
f26b953a3f | ||
|
|
882f6a47bf | ||
|
|
2d3179180e | ||
|
|
5d6616652d | ||
|
|
b349af7351 | ||
|
|
c843bce25d | ||
|
|
607539d47b | ||
|
|
b2ec20421f | ||
|
|
14d526e033 | ||
|
|
e2df3f377d | ||
|
|
670957db36 | ||
|
|
c1e4aded9d | ||
|
|
ca4554f514 | ||
|
|
39911e3a09 | ||
|
|
17559ce3ba | ||
|
|
b79ed21c10 | ||
|
|
850abfd93c | ||
|
|
5af15ed13a | ||
|
|
d3ffa31e00 | ||
|
|
ece61a0e87 | ||
|
|
bb4c8cd8ad | ||
|
|
f54132443c | ||
|
|
82009842a6 | ||
|
|
312f4fbd24 | ||
|
|
8fa3be2d17 | ||
|
|
a7147a0c06 | ||
|
|
b40c180471 | ||
|
|
1ab60e0a29 | ||
|
|
68e15a3c78 | ||
|
|
c90721bb13 | ||
|
|
0f368d304a | ||
|
|
a98d4db606 | ||
|
|
848df1830f | ||
|
|
a9485516b6 | ||
|
|
4c3559bffd | ||
|
|
5f1d8c8fd4 | ||
|
|
4e6b21a7d9 | ||
|
|
7be37bc52d | ||
|
|
208dbe7b58 | ||
|
|
193adeed9c | ||
|
|
198f5633d4 | ||
|
|
e2e8bf5f45 | ||
|
|
932d5cb725 | ||
|
|
5bb4da2650 | ||
|
|
2cf17a20d0 | ||
|
|
f3accb56b5 | ||
|
|
9ecc52a8eb | ||
|
|
27bc07fcd9 | ||
|
|
fcade81bf5 | ||
|
|
a720cef797 | ||
|
|
abd9a937a1 | ||
|
|
7feb2d6507 | ||
|
|
06818e5616 | ||
|
|
ca8d278566 | ||
|
|
d3068c1947 | ||
|
|
4d6094b384 | ||
|
|
0ee80926ef | ||
|
|
a72862f94e | ||
|
|
0e8afa6cd6 | ||
|
|
5456e59f0b | ||
|
|
e2549ebffe | ||
|
|
23c6b16a7c | ||
|
|
5b61803868 | ||
|
|
07acc3b087 | ||
|
|
d8f9a6940d | ||
|
|
7bde532b31 | ||
|
|
12811d119a | ||
|
|
21ab57ddc2 | ||
|
|
80880c2f69 | ||
|
|
38d065ab86 | ||
|
|
685520ef8d | ||
|
|
974eac515e | ||
|
|
1db5a1a82e | ||
|
|
dfc78ddc71 | ||
|
|
6bac52cdea | ||
|
|
48e310d4b0 | ||
|
|
bf6a8de246 | ||
|
|
416013ed1d | ||
|
|
f5ab9c768f | ||
|
|
bbb9d200ce | ||
|
|
2a53d5b19d | ||
|
|
2135dfca96 | ||
|
|
32ef7a7097 | ||
|
|
faaa642b0b | ||
|
|
a5b8620e39 | ||
|
|
724c25ecd6 | ||
|
|
4091b62817 | ||
|
|
5cc4936962 | ||
|
|
677c49216f | ||
|
|
251505f9f7 | ||
|
|
cccb276493 | ||
|
|
495ff06bbe | ||
|
|
72b163e22d | ||
|
|
3e77f00d16 | ||
|
|
00c43353f2 | ||
|
|
82a3f877a7 | ||
|
|
edf17d6434 | ||
|
|
7c1fd79af1 | ||
|
|
c281fb1e01 | ||
|
|
ddaf57df6c | ||
|
|
011aaa50e8 | ||
|
|
0d956b6bf6 | ||
|
|
8f2a6a58f2 | ||
|
|
24dc1fe615 | ||
|
|
dc5ca4b1c6 | ||
|
|
9884712392 | ||
|
|
0c5b23b790 | ||
|
|
edd51c67c4 | ||
|
|
05341ad604 | ||
|
|
493f105055 | ||
|
|
f5d46fcaba | ||
|
|
8533f1aaad | ||
|
|
419c3799f6 | ||
|
|
00c0e4949b | ||
|
|
88fc42f8ec | ||
|
|
d28b0c09de | ||
|
|
412a150d1e | ||
|
|
405f6f8cee | ||
|
|
d8ca8e4116 | ||
|
|
dcb2d5943d | ||
|
|
8da7fab51f | ||
|
|
8408f574a1 | ||
|
|
973812230a | ||
|
|
2c45cb2887 | ||
|
|
1cd2b08524 | ||
|
|
61afe79506 | ||
|
|
b97e82c2dd | ||
|
|
d40d78d098 | ||
|
|
6e59ef4e8d | ||
|
|
d0f0642c45 | ||
|
|
577c1fd1a6 | ||
|
|
1b7eef2443 | ||
|
|
6fc835dacb | ||
|
|
1cad4a158e | ||
|
|
b0c9033c06 | ||
|
|
b224f0d4a1 | ||
|
|
b4d913d517 | ||
|
|
c28e08d7a2 | ||
|
|
7b7bccbca2 | ||
|
|
8c0513d394 | ||
|
|
7ab0e77a97 | ||
|
|
cbca0e9fa9 | ||
|
|
1b92bd9d7d | ||
|
|
be84492c3d | ||
|
|
00f555442d | ||
|
|
dc572d0f65 | ||
|
|
256dc78e5b | ||
|
|
b6e13fb4af | ||
|
|
1109b9f12e | ||
|
|
0bdedc65ad | ||
|
|
7ffe48855f | ||
|
|
266a5cb5d8 | ||
|
|
678147c9ed | ||
|
|
4e608d872a |
No files matched your search
@@ -1,60 +0,0 @@
|
||||
name: Create and publish a Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
APP_NAME: ${{ github.event.repository.name }}
|
||||
|
||||
jobs:
|
||||
build-and-push-image:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
attestations: write
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Get version from tag
|
||||
id: version_reader
|
||||
run: |
|
||||
VERSION=${GITHUB_REF_NAME#v}
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
driver: docker-container
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build and push Docker image
|
||||
id: push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version_reader.outputs.version }}
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
|
||||
labels: |
|
||||
org.opencontainers.image.title=${{ env.IMAGE_NAME }}
|
||||
org.opencontainers.image.version=${{ steps.version_reader.outputs.version }}
|
||||
build-args: |
|
||||
app_name=${{ env.APP_NAME }}
|
||||
version=${{ steps.version_reader.outputs.version }}
|
||||
- name: Generate artifact attestation
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
|
||||
subject-digest: ${{ steps.push.outputs.digest }}
|
||||
push-to-registry: true
|
||||
@@ -69,8 +69,6 @@ fabric.properties
|
||||
*.out
|
||||
|
||||
/node_modules/
|
||||
/vendor/
|
||||
google/
|
||||
package.json
|
||||
yarn.lock
|
||||
/bin/golangci-lint
|
||||
@@ -20,7 +20,12 @@ linters:
|
||||
- wsl_v5 # расставление пробелов очень индивидуально
|
||||
- godoclint # ругается на // nolint, не удобно
|
||||
- prealloc # слишком аггресивный, в большинстве случаев не требуется
|
||||
- gomodguard # deprecated
|
||||
- goconst # слишком агрессивный
|
||||
settings:
|
||||
exhaustruct_v5:
|
||||
allow-empty: true
|
||||
explicit-mode: true
|
||||
cyclop:
|
||||
max-complexity: 15 # по умолчанию 10 мало
|
||||
funlen:
|
||||
@@ -60,6 +65,9 @@ linters:
|
||||
- unqueryvet
|
||||
- prealloc
|
||||
path: ".*_test\\.go$"
|
||||
- linters:
|
||||
- goconst
|
||||
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
@@ -73,3 +81,4 @@ formatters:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
|
||||
@@ -1,3 +1,25 @@
|
||||
### v7.2.0
|
||||
* Добавлено поле `application_group` в таблицу `roles`
|
||||
* Добавлен для запросов `admin/role/create` и `admin/role/update`, необязателен
|
||||
* Изменен эндпоинт `admin/role/all`, теперь результаты фильтруются по группе из тела запроса, при пустом теле без фильтрации
|
||||
* Добавлена возможность скачивания и формирования CSV
|
||||
### v7.1.0
|
||||
* переименование авторизации через SUDIR в OAuth:
|
||||
* Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth`
|
||||
* Колонка `users.sudir_user_id` → `users.oauth_user_id`
|
||||
* Переименованы ошибки: `ErrOauthAuthorization`, `ErrOauthIsMissed`
|
||||
* Метод `LoginWithSudir` → `LoginWithOauth`, поле `OauthUser.SudirUserId` → `OauthUser.OauthUserId`
|
||||
* Обновлены сообщения ошибок, логи, аудит и swagger-документация
|
||||
* в конфиге ключ OAuth-раздела `sudirAuth` → `oauth`
|
||||
### v7.0.0
|
||||
* Изменена логика авторизации через СУДИР:
|
||||
* Изменена схема конфигурации для авторизации через СУДИР
|
||||
* Изменён контракт взаимодействия по `admin/auth/login_with_sudir`
|
||||
* Добавлен endpoint для получения ссылок для login и logout через sudir - `admin/ui_settings/sudir`
|
||||
### v6.8.2
|
||||
* обновлены зависимости
|
||||
### v6.8.1
|
||||
* Обновлен isp-kit
|
||||
### v6.8.0
|
||||
* Изменен контракт методов. В запросах теперь массив идентификаторов пользователей и массив статусов сессий
|
||||
* Обновлена версия go
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.26-alpine as builder
|
||||
FROM golang:1.27-alpine as builder
|
||||
WORKDIR /build
|
||||
ARG version
|
||||
ENV version_env=$version
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
FROM dockerhub.mos.ru/mosos/arbat:15.5 as builder
|
||||
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.24 git
|
||||
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.27 git
|
||||
WORKDIR /build
|
||||
ARG version
|
||||
ENV version_env=$version
|
||||
|
||||
+30
-18
@@ -4,45 +4,48 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/service/delete_old_audit_worker"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
"msp-admin-service/service/session_worker"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/service/delete_old_audit_worker"
|
||||
"isp-admin-service/service/inactive_worker"
|
||||
"isp-admin-service/service/session_worker"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/dbrx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/observability/sentry"
|
||||
)
|
||||
|
||||
type Assembly struct {
|
||||
boot *bootstrap.Bootstrap
|
||||
db *dbrx.Client
|
||||
server *grpc.Server
|
||||
httpCli *httpcli.Client
|
||||
server *http.Server
|
||||
oauthCli *httpcli.Client
|
||||
logger *log.Adapter
|
||||
bgjobCli *bgjobx.Client
|
||||
}
|
||||
|
||||
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
logger := boot.App.Logger()
|
||||
server := grpc.NewServer()
|
||||
httpCli := httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(logger)))
|
||||
db := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, logger))
|
||||
bgjobCli := bgjobx.NewClient(db, logger)
|
||||
wrappedLogger := sentry.WrapErrorLogger(logger, boot.SentryHub)
|
||||
|
||||
db := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, wrappedLogger))
|
||||
boot.HealthcheckRegistry.Register("db", db)
|
||||
|
||||
bgjobCli := bgjobx.NewClient(db, wrappedLogger)
|
||||
return &Assembly{
|
||||
boot: boot,
|
||||
db: db,
|
||||
server: server,
|
||||
server: http.NewServer(logger),
|
||||
logger: logger,
|
||||
httpCli: httpCli,
|
||||
oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
|
||||
bgjobCli: bgjobCli,
|
||||
}, nil
|
||||
}
|
||||
@@ -64,8 +67,17 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"))
|
||||
}
|
||||
|
||||
locator := NewLocator(a.logger, a.httpCli, a.db)
|
||||
config := locator.Config(ctx, newCfg, time.Minute)
|
||||
oauthBaseUrl := ""
|
||||
if newCfg.Oauth != nil {
|
||||
oauthBaseUrl = newCfg.Oauth.Host
|
||||
}
|
||||
a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl
|
||||
|
||||
locator := NewLocator(a.logger, a.oauthCli, a.db)
|
||||
config, err := locator.Config(ctx, newCfg, time.Minute)
|
||||
if err != nil {
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "locator config"))
|
||||
}
|
||||
|
||||
a.server.Upgrade(config.Handler)
|
||||
|
||||
@@ -97,7 +109,7 @@ func (a *Assembly) Runners() []app.Runner {
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
err := a.server.ListenAndServe(a.boot.BindingAddress)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "listen ans serve grpc server")
|
||||
return errors.WithMessage(err, "listen and serve http server")
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
@@ -115,7 +127,7 @@ func (a *Assembly) Closers() []app.Closer {
|
||||
return []app.Closer{
|
||||
a.boot.ClusterCli,
|
||||
app.CloserFunc(func() error {
|
||||
a.server.Shutdown()
|
||||
_ = a.server.Shutdown(context.Background())
|
||||
return nil
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
|
||||
+56
-25
@@ -4,22 +4,24 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/controller"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/routes"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/service/delete_old_audit_worker"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
"msp-admin-service/service/secure"
|
||||
"msp-admin-service/service/session_worker"
|
||||
"msp-admin-service/transaction"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/controller"
|
||||
"isp-admin-service/repository"
|
||||
"isp-admin-service/routes"
|
||||
"isp-admin-service/service"
|
||||
"isp-admin-service/service/delete_old_audit_worker"
|
||||
"isp-admin-service/service/inactive_worker"
|
||||
"isp-admin-service/service/secure"
|
||||
"isp-admin-service/service/session_worker"
|
||||
"isp-admin-service/transaction"
|
||||
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
@@ -29,21 +31,21 @@ type DB interface {
|
||||
}
|
||||
|
||||
type Locator struct {
|
||||
logger log.Logger
|
||||
httpCli *httpcli.Client
|
||||
db DB
|
||||
logger log.Logger
|
||||
oauthCli *httpcli.Client
|
||||
db DB
|
||||
}
|
||||
|
||||
func NewLocator(logger log.Logger, httpCli *httpcli.Client, db DB) Locator {
|
||||
func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator {
|
||||
return Locator{
|
||||
logger: logger,
|
||||
httpCli: httpCli,
|
||||
db: db,
|
||||
logger: logger,
|
||||
oauthCli: oauthCli,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Handler isp.BackendServiceServer
|
||||
Handler *router.Router
|
||||
BgJobCfg []bgjobx.WorkerConfig
|
||||
}
|
||||
|
||||
@@ -52,8 +54,8 @@ func (l Locator) Config(
|
||||
ctx context.Context,
|
||||
cfg conf.Remote,
|
||||
jobPollInterval time.Duration,
|
||||
) Config {
|
||||
sudirRepo := repository.NewSudir(l.httpCli, cfg.SudirAuth)
|
||||
) (Config, error) {
|
||||
oauthRepo := repository.NewOauth(l.oauthCli)
|
||||
roleRepo := repository.NewRole(l.db)
|
||||
userRepo := repository.NewUser(l.db)
|
||||
tokenRepo := repository.NewToken(l.db)
|
||||
@@ -63,7 +65,13 @@ func (l Locator) Config(
|
||||
|
||||
auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings)
|
||||
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
|
||||
sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo)
|
||||
|
||||
oauthBaseUrl, oauthSettings := l.getOauthSettings(cfg.Oauth)
|
||||
oauthService, err := service.NewOauth(oauthSettings, oauthRepo)
|
||||
if err != nil {
|
||||
return Config{}, errors.WithMessage(err, "new oauth")
|
||||
}
|
||||
|
||||
secureService := secure.NewService(tokenRepo, userRoleRepo)
|
||||
|
||||
txManager := transaction.NewManager(l.db)
|
||||
@@ -80,7 +88,7 @@ func (l Locator) Config(
|
||||
l.logger,
|
||||
)
|
||||
authService := service.NewAuth(
|
||||
userRepo, txManager, tokenService, sudirService, auditService, l.logger,
|
||||
userRepo, txManager, tokenService, oauthService, auditService, l.logger,
|
||||
cfg.AntiBruteforce.DelayLoginRequestInSec,
|
||||
cfg.AntiBruteforce.MaxInFlightLoginRequests,
|
||||
)
|
||||
@@ -88,6 +96,16 @@ func (l Locator) Config(
|
||||
|
||||
permissionsService := service.NewPermission(cfg.Permissions)
|
||||
|
||||
uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings)
|
||||
|
||||
downloadService := service.NewDownload(
|
||||
auditService,
|
||||
userService,
|
||||
tokenService,
|
||||
roleService,
|
||||
permissionsService,
|
||||
)
|
||||
|
||||
userController := controller.NewUser(userService)
|
||||
customizationController := controller.NewCustomization(cfg.UiDesign)
|
||||
authController := controller.NewAuth(authService, l.logger)
|
||||
@@ -96,9 +114,12 @@ func (l Locator) Config(
|
||||
auditController := controller.NewAudit(auditService)
|
||||
roleController := controller.NewRole(roleService)
|
||||
permissionController := controller.NewPermissions(permissionsService)
|
||||
uiSettingsController := controller.NewUiSettings(uiSettingsService)
|
||||
downloadController := controller.NewDownload(downloadService)
|
||||
|
||||
wrapper := endpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true))
|
||||
handler := routes.Handler(
|
||||
endpoint.DefaultWrapper(l.logger),
|
||||
wrapper,
|
||||
routes.Controllers{
|
||||
User: userController,
|
||||
Customization: customizationController,
|
||||
@@ -108,6 +129,8 @@ func (l Locator) Config(
|
||||
Audit: auditController,
|
||||
Role: roleController,
|
||||
Permissions: permissionController,
|
||||
UiSettings: uiSettingsController,
|
||||
Download: downloadController,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -139,5 +162,13 @@ func (l Locator) Config(
|
||||
PollInterval: jobPollInterval,
|
||||
Handle: expireSessionWorker,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l Locator) getOauthSettings(oauthAuth *conf.Oauth) (string, []conf.OauthClientConfig) {
|
||||
if oauthAuth == nil {
|
||||
return "", []conf.OauthClientConfig{}
|
||||
}
|
||||
|
||||
return oauthAuth.Host, oauthAuth.Clients
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
// StringFromHeader extracts a string value from header by key.
|
||||
// Returns an error if header is nil or the key is not found.
|
||||
func StringFromHeader(key string, h http.Header) (string, error) {
|
||||
if h == nil {
|
||||
return "", errors.New("header is nil")
|
||||
}
|
||||
values := h.Values(key)
|
||||
if len(values) == 0 {
|
||||
return "", errors.Errorf("'%s' is expected in header", key)
|
||||
}
|
||||
return values[0], nil
|
||||
}
|
||||
|
||||
// IntFromHeader extracts an integer value from header by key.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func IntFromHeader(key string, h http.Header) (int, error) {
|
||||
value, err := StringFromHeader(key, h)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "parse '%s' to int", key)
|
||||
}
|
||||
return intValue, nil
|
||||
}
|
||||
+2
-2
@@ -7,11 +7,11 @@ grpcOuterAddress:
|
||||
grpcInnerAddress:
|
||||
ip: 0.0.0.0
|
||||
port: 9007
|
||||
moduleName: msp-admin-service
|
||||
moduleName: isp-admin-service
|
||||
infraServerPort: 9557
|
||||
|
||||
logfile:
|
||||
path: /var/log/msp-admin-service/runtime.log
|
||||
path: /var/log/isp-admin-service/runtime.log
|
||||
maxSizeMb: 512
|
||||
maxBackups: 4
|
||||
compress: true
|
||||
+32
-21
@@ -1,3 +1,4 @@
|
||||
//nolint:lll
|
||||
package conf
|
||||
|
||||
import (
|
||||
@@ -10,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
// nolint: gochecknoinits
|
||||
func init() { //
|
||||
func init() {
|
||||
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
|
||||
t.Type = "string"
|
||||
t.Enum = []any{"debug", "info", "error", "fatal"}
|
||||
@@ -18,13 +19,12 @@ func init() { //
|
||||
}
|
||||
|
||||
type Remote struct {
|
||||
Audit Audit
|
||||
Database dbx.Config
|
||||
ExpireSec int `validate:"required" schema:"Время жизни токена в секундах,in seconds"`
|
||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||
//nolint:lll
|
||||
Audit Audit `schema:"Настройки audit"`
|
||||
Database dbx.Config `schema:"Настройка подключения к БД"`
|
||||
ExpireSec int `validate:"required" schema:"Время жизни токена в секундах,in seconds"`
|
||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||
IdleTimeoutMs int `schema:"Время бездействия пользователя,в милисекундах, после указанного времени пользователь будет разлогирован из интерфейса в браузере, по умолчанию отключено"`
|
||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||
Oauth *Oauth `schema:"OAuth авторизация"`
|
||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
||||
BlockInactiveWorker BlockInactiveWorker `validate:"required" schema:"Блокировка неактивных УЗ"`
|
||||
@@ -32,30 +32,41 @@ type Remote struct {
|
||||
}
|
||||
|
||||
type Audit struct {
|
||||
EventSettings []AuditEventSetting
|
||||
AuditTTl AuditTTlSetting
|
||||
EventSettings []AuditEventSetting `schema:"Маппинг событий"`
|
||||
AuditTTl AuditTTlSetting `schema:"Настройки TTL для audit"`
|
||||
}
|
||||
|
||||
type AuditTTlSetting struct {
|
||||
TimeToLiveInMin int `validate:"required"`
|
||||
ExpireSyncPeriodInMin int `validate:"required"`
|
||||
TimeToLiveInMin int `validate:"required" schema:"TTL события в минутах"`
|
||||
ExpireSyncPeriodInMin int `validate:"required" schema:"Интервал запуска воркера"`
|
||||
}
|
||||
|
||||
type AuditEventSetting struct {
|
||||
Event string
|
||||
Name string
|
||||
Event string `schema:"Ключ события"`
|
||||
Name string `schema:"Пользовательское название события"`
|
||||
}
|
||||
|
||||
type UIDesign struct {
|
||||
Name string `schema:"Название стенда"`
|
||||
PrimaryColor string `schema:"Цвет в HEX, примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
||||
PrimaryColor string `schema:"Цвет в HEX,примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
||||
}
|
||||
|
||||
type SudirAuth struct {
|
||||
ClientId string `validate:"required"`
|
||||
ClientSecret string `validate:"required"`
|
||||
Host string `validate:"required" schema:"Хост, пример https://sudir.mos.ru"`
|
||||
RedirectURI string `validate:"required"`
|
||||
type Oauth struct {
|
||||
Host string `validate:"required" schema:"Базовый путь до методов, пример https://oauth.example.com"`
|
||||
Clients []OauthClientConfig `validate:"omitempty,min=1" schema:"Настройка взаимодействия для логина по authCode"`
|
||||
}
|
||||
|
||||
type OauthClientConfig struct {
|
||||
ClientName string `validate:"required" schema:"Уникальное имя конфигурации клиента"`
|
||||
ClientId string `validate:"required" schema:"Идентификатор клиента,выданный для basicAuth"`
|
||||
ClientSecret string `validate:"required" schema:"Пароль клиента,выданный для basicAuth"`
|
||||
RedirectURI string `validate:"required" schema:"URI для редиректа,передаётся в запросе токена в query"`
|
||||
UiSetting *UiOauthSetting `schema:"Настройки OAuth для админки"`
|
||||
}
|
||||
|
||||
type UiOauthSetting struct {
|
||||
LoginEndpoint string `validate:"required" schema:"Эндпоинт для входа через OAuth в адмиинке,может содержать query параметры,client_id и redirect_uri добавляются автоматически"`
|
||||
LogoutEndpoint string `validate:"required" schema:"Эндпоинт для выхода через OAuth в адмиинке"`
|
||||
}
|
||||
|
||||
type AntiBruteforce struct {
|
||||
@@ -69,6 +80,6 @@ type BlockInactiveWorker struct {
|
||||
}
|
||||
|
||||
type Permission struct {
|
||||
Key string
|
||||
Name string
|
||||
Key string `schema:"Ключ прав"`
|
||||
Name string `schema:"Пользовательское название"`
|
||||
}
|
||||
+2
-1
@@ -3,8 +3,9 @@ package conf_test
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"isp-admin-service/conf"
|
||||
|
||||
"github.com/txix-open/isp-kit/test/rct"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
func TestDefaultRemoteConfig(t *testing.T) {
|
||||
|
||||
+38
-37
@@ -2,12 +2,12 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type AuditService interface {
|
||||
@@ -27,16 +27,17 @@ func NewAudit(service AuditService) Audit {
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.AuditResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/all [POST]
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)"
|
||||
// @Success 200 {object} domain.AuditResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/all [POST]
|
||||
func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -49,38 +50,38 @@ func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.Au
|
||||
}
|
||||
|
||||
// Events
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Description Возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditResponse true "Тело запроса"
|
||||
// @Success 200 {array} domain.AuditEvent
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/events [POST]
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Получение списка событий аудита
|
||||
// @Description Возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.AuditEvent
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/events [POST]
|
||||
func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) {
|
||||
return c.service.Events(ctx)
|
||||
}
|
||||
|
||||
// SetEvents
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Description Всегда возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SetAuditEvent true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/set_events [POST]
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Установить события аудита
|
||||
// @Description Устанавливает (обновляет) набор активных событий аудита.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body []domain.SetAuditEvent true "Список событий аудита для установки"
|
||||
// @Success 200 {object} map[string]interface{} "События успешно установлены"
|
||||
// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/set_events [POST]
|
||||
func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error {
|
||||
err := c.service.SetEvents(ctx, req)
|
||||
switch {
|
||||
case errors.As(err, &domain.UnknownAuditEventError{}):
|
||||
return status.Error(codes.InvalidArgument, err.Error())
|
||||
return apierrors.New(http.StatusBadRequest, domain.UnknownAuditEventErrorCode, err.Error(), err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
+73
-69
@@ -2,21 +2,20 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/auth"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type authService interface {
|
||||
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
|
||||
LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error)
|
||||
LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error)
|
||||
Logout(ctx context.Context, adminId int64, request *domain.LogoutRequest) error
|
||||
}
|
||||
|
||||
@@ -33,18 +32,19 @@ func NewAuth(authService authService, logger log.Logger) Auth {
|
||||
}
|
||||
|
||||
// Logout
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout [POST]
|
||||
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} map[string]interface{} "Успешный выход"
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/logout [POST]
|
||||
func (a Auth) Logout(ctx context.Context, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -58,19 +58,20 @@ func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
||||
}
|
||||
|
||||
// LogoutWithReason
|
||||
// @Tags auth
|
||||
// @Summary Выход по бездействию из авторизованной сессии
|
||||
// @Description Выход по бездействию из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LogoutRequest true "Тело запроса"
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout_with_reason [POST]
|
||||
func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Выход по бездействию из авторизованной сессии
|
||||
// @Description Выход по бездействию из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.LogoutRequest true "Тело запроса"
|
||||
// @Success 200 {object} map[string]interface{} "Успешный выход"
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/logout_with_reason [POST]
|
||||
func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -84,28 +85,30 @@ func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logo
|
||||
}
|
||||
|
||||
// Login
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login [POST]
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны"
|
||||
// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/login [POST]
|
||||
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.Login(ctx, authRequest)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSudirAuthorization):
|
||||
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
||||
case errors.Is(err, domain.ErrOauthAuthorization):
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthAuthorizationCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
a.logger.Error(ctx, err.Error())
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid credential")
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrTooManyLoginRequests):
|
||||
return nil, status.Error(codes.ResourceExhausted, "too many requests")
|
||||
return nil, apierrors.New(http.StatusTooManyRequests, domain.ErrTooManyLoginRequestsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login")
|
||||
default:
|
||||
@@ -113,42 +116,43 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
||||
}
|
||||
}
|
||||
|
||||
// LoginWithSudir
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от СУДИР
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginSudirRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации"
|
||||
// @Failure 412 {object} domain.GrpcError "Авторизация СУДИР не настроена на сервере"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login_with_sudir [POST]
|
||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.LoginWithSudir(ctx, request)
|
||||
// LoginWithOauth
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от OAuth
|
||||
// @Description Авторизация с получением токена администратора.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginOauthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере"
|
||||
// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/login_with_oauth [POST]
|
||||
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.LoginWithOauth(ctx, request)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSudirAuthIsMissed):
|
||||
return nil, status.Error(codes.FailedPrecondition, "sudir auth is not configured")
|
||||
case errors.Is(err, domain.ErrOauthIsMissed):
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthIsMissedCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login with sudir")
|
||||
return nil, errors.WithMessage(err, "login with oauth")
|
||||
default:
|
||||
return auth, nil
|
||||
}
|
||||
}
|
||||
|
||||
func getAdminId(authData grpc.AuthData) (int64, error) {
|
||||
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData))
|
||||
func getAdminId(r *http.Request) (int64, error) {
|
||||
token, err := auth.StringFromHeader(domain.AdminAuthIdHeader, r.Header)
|
||||
if err != nil {
|
||||
return 0, status.Error(codes.InvalidArgument, err.Error())
|
||||
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||
}
|
||||
|
||||
adminId, err := strconv.Atoi(token)
|
||||
if err != nil {
|
||||
return 0, status.Error(codes.InvalidArgument, "admin id is not a number")
|
||||
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||
}
|
||||
|
||||
return int64(adminId), nil
|
||||
|
||||
+19
-14
@@ -1,30 +1,35 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"msp-admin-service/conf"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
)
|
||||
|
||||
type Customization struct {
|
||||
uiCfg conf.UIDesign
|
||||
uiCfg domain.UIDesign
|
||||
}
|
||||
|
||||
func NewCustomization(uiCfg conf.UIDesign) Customization {
|
||||
return Customization{
|
||||
uiCfg: uiCfg,
|
||||
uiCfg: domain.UIDesign{
|
||||
Name: uiCfg.Name,
|
||||
PrimaryColor: uiCfg.PrimaryColor,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// GetUIDesign
|
||||
// @Tags user
|
||||
// @Summary Получение внешнего вида
|
||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} conf.UIDesign
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_design [POST]
|
||||
func (c Customization) GetUIDesign() (conf.UIDesign, error) {
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получение внешнего вида
|
||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UIDesign
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_design [POST]
|
||||
func (c Customization) GetUIDesign() (domain.UIDesign, error) {
|
||||
return c.uiCfg, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type DownloadService interface {
|
||||
DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error
|
||||
DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error
|
||||
DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error
|
||||
DownloadRoles(ctx context.Context, req domain.RoleAllRequest, w http.ResponseWriter) error
|
||||
}
|
||||
|
||||
type Download struct {
|
||||
service DownloadService
|
||||
}
|
||||
|
||||
func NewDownload(service DownloadService) Download {
|
||||
return Download{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Users
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать список пользователей в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /user/download [POST]
|
||||
func (c Download) Users(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadUsers(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download users")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sessions
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать список сессий в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /session/download [POST]
|
||||
func (c Download) Sessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadSessions(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download sessions")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Audit
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать журнал аудита в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /log/download [POST]
|
||||
func (c Download) Audit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadAudit(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download audit")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Roles
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать матрицу ролей в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /role/download [POST]
|
||||
func (c Download) Roles(ctx context.Context, req domain.RoleAllRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadRoles(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download roles")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
)
|
||||
|
||||
type permissionsService interface {
|
||||
@@ -21,13 +21,15 @@ func NewPermissions(permissionsService permissionsService) Permissions {
|
||||
}
|
||||
|
||||
// GetPermissions
|
||||
// @Tags user
|
||||
// @Summary Получить все разрашения
|
||||
// @Description Получить все разрашения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.Permission
|
||||
// @Router /user/get_permissions [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получить все разрешения
|
||||
// @Description Получить все разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.Permission
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_permissions [POST]
|
||||
func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission {
|
||||
return u.permissionsService.All(ctx)
|
||||
}
|
||||
+66
-62
@@ -2,16 +2,16 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type roleService interface {
|
||||
All(ctx context.Context) ([]domain.Role, error)
|
||||
All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error)
|
||||
Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error)
|
||||
Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error)
|
||||
Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error
|
||||
@@ -28,18 +28,19 @@ func NewRole(roleService roleService) Role {
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags role
|
||||
// @Summary Список ролей
|
||||
// @Description Получить список ролей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.Role
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/all [POST]
|
||||
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
users, err := u.roleService.All(ctx)
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Список ролей
|
||||
// @Description Получить список ролей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.Role
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/all [POST]
|
||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
||||
users, err := u.roleService.All(ctx, req)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get roles")
|
||||
}
|
||||
@@ -48,20 +49,21 @@ func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
}
|
||||
|
||||
// CreateRole
|
||||
// @Tags user
|
||||
// @Summary Создать роль
|
||||
// @Description Создать роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/create [POST]
|
||||
func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Создать роль
|
||||
// @Description Создать роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/create [POST]
|
||||
func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -69,7 +71,7 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
|
||||
role, err := u.roleService.Create(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create role")
|
||||
default:
|
||||
@@ -78,20 +80,21 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
|
||||
}
|
||||
|
||||
// UpdateRole
|
||||
// @Tags role
|
||||
// @Summary Обновить роль
|
||||
// @Description Обновить данные существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует"
|
||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/update [POST]
|
||||
func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Обновить роль
|
||||
// @Description Обновить данные существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 404 {object} apierrors.Error "Роль с указанным id не существует"
|
||||
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/update [POST]
|
||||
func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -99,9 +102,9 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
|
||||
result, err := u.roleService.Update(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "role not found")
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update role")
|
||||
default:
|
||||
@@ -110,19 +113,20 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
|
||||
}
|
||||
|
||||
// DeleteRole
|
||||
// @Tags role
|
||||
// @Summary Удалить роль
|
||||
// @Description Удалить существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/delete [POST]
|
||||
func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Удалить роль
|
||||
// @Description Удалить существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/delete [POST]
|
||||
func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+24
-21
@@ -3,9 +3,10 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type SecureService interface {
|
||||
@@ -24,15 +25,16 @@ func NewSecure(service SecureService) Secure {
|
||||
}
|
||||
|
||||
// Authenticate
|
||||
// @Tags secure
|
||||
// @Summary Метод аутентификации токена
|
||||
// @Description Проверяет токен и возвращает идентификатор администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authenticate [POST]
|
||||
//
|
||||
// @Tags secure
|
||||
// @Summary Метод аутентификации токена
|
||||
// @Description Проверяет токен и возвращает идентификатор администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthResponse
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /secure/authenticate [POST]
|
||||
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
|
||||
adminId, err := s.service.Authenticate(ctx, req.Token)
|
||||
switch {
|
||||
@@ -60,15 +62,16 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
|
||||
}
|
||||
|
||||
// Authorize
|
||||
// @Tags secure
|
||||
// @Summary Метод авторизации для администратора
|
||||
// @Description Проверяет наличие у администратора необходимого разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthzResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authorize [POST]
|
||||
//
|
||||
// @Tags secure
|
||||
// @Summary Метод авторизации для администратора
|
||||
// @Description Проверяет наличие у администратора необходимого разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthzResponse
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /secure/authorize [POST]
|
||||
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
|
||||
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
|
||||
if err != nil {
|
||||
|
||||
+23
-21
@@ -3,7 +3,7 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
)
|
||||
|
||||
type SessionService interface {
|
||||
@@ -22,16 +22,17 @@ func NewSession(service SessionService) Session {
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags session
|
||||
// @Summary Получение списка сессий
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SessionResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/all [POST]
|
||||
//
|
||||
// @Tags session
|
||||
// @Summary Получение списка сессий
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SessionResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /session/all [POST]
|
||||
func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -44,16 +45,17 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai
|
||||
}
|
||||
|
||||
// Revoke
|
||||
// @Tags session
|
||||
// @Summary Отзыв сессии
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/revoke [POST]
|
||||
//
|
||||
// @Tags session
|
||||
// @Summary Отзыв сессии
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /session/revoke [POST]
|
||||
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
|
||||
return c.service.Revoke(ctx, req.Id)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"isp-admin-service/domain"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type UiSettingsService interface {
|
||||
OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error)
|
||||
}
|
||||
|
||||
type UiSettings struct {
|
||||
service UiSettingsService
|
||||
}
|
||||
|
||||
func NewUiSettings(service UiSettingsService) UiSettings {
|
||||
return UiSettings{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// UiOauthSettings
|
||||
//
|
||||
// @Tags ui_settings
|
||||
// @Summary Получение настроек для ui для авторизации через OAuth
|
||||
// @Description Получение настроек для ui для авторизации через OAuth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UiOauthSetting
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 401 {object} apierrors.Error "Неизвестное название клиента"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /ui_settings/oauth [POST]
|
||||
func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
||||
resp, err := c.service.OauthSettings(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnknownClient):
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnknownClientCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
+129
-122
@@ -2,15 +2,13 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type userService interface {
|
||||
@@ -36,19 +34,20 @@ func NewUser(userService userService) User {
|
||||
}
|
||||
|
||||
// GetProfile
|
||||
// @Tags user
|
||||
// @Summary Получить профиль
|
||||
// @Description Получить данные профиля
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.AdminUserShort
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 404 {object} domain.GrpcError "Пользователя не существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_profile [POST]
|
||||
func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получить профиль
|
||||
// @Description Получить данные профиля
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.AdminUserShort
|
||||
// @Failure 401 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 404 {object} apierrors.Error "Пользователя не существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_profile [POST]
|
||||
func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -56,9 +55,9 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
|
||||
profile, err := u.userService.GetProfileById(ctx, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "user is blocked")
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "user not found")
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get profile")
|
||||
default:
|
||||
@@ -67,17 +66,18 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
|
||||
}
|
||||
|
||||
// GetUsers
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_users [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_users [POST]
|
||||
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -95,16 +95,17 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
|
||||
}
|
||||
|
||||
// GetAllUsers
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_all_users [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_all_users [POST]
|
||||
func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
||||
users, err := u.userService.GetAllUsers(ctx)
|
||||
if err != nil {
|
||||
@@ -115,20 +116,21 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
||||
}
|
||||
|
||||
// CreateUser
|
||||
// @Tags user
|
||||
// @Summary Создать пользователя
|
||||
// @Description Создать пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/create_user [POST]
|
||||
func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Создать пользователя
|
||||
// @Description Создать пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/create_user [POST]
|
||||
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -136,7 +138,7 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
|
||||
user, err := u.userService.CreateUser(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create user")
|
||||
default:
|
||||
@@ -145,21 +147,22 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
|
||||
}
|
||||
|
||||
// UpdateUser
|
||||
// @Tags user
|
||||
// @Summary Обновить пользователя
|
||||
// @Description Обновить данные существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/update_user [POST]
|
||||
func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Обновить пользователя
|
||||
// @Description Обновить данные существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует"
|
||||
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/update_user [POST]
|
||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -167,11 +170,11 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
|
||||
result, err := u.userService.UpdateUser(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "user not found")
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
return nil, status.Error(codes.InvalidArgument, "user modification is not available")
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrInvalidCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update user")
|
||||
default:
|
||||
@@ -180,19 +183,20 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
|
||||
}
|
||||
|
||||
// DeleteUser
|
||||
// @Tags user
|
||||
// @Summary Удалить пользователя
|
||||
// @Description Удалить существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/delete_user [POST]
|
||||
func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Удалить пользователя
|
||||
// @Description Удалить существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/delete_user [POST]
|
||||
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -206,18 +210,19 @@ func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities
|
||||
}
|
||||
|
||||
// Block
|
||||
// @Tags user
|
||||
// @Summary Метод блокировки/разблокировки пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/block_user [POST]
|
||||
func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод блокировки/разблокировки пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/block_user [POST]
|
||||
func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -230,32 +235,34 @@ func (u User) Block(ctx context.Context, authData grpc.AuthData, identities doma
|
||||
}
|
||||
|
||||
// GetById
|
||||
// @Tags user
|
||||
// @Summary Метод получения данных по пользователю
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_by_id [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод получения данных по пользователю
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_by_id [POST]
|
||||
func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) {
|
||||
return u.userService.GetById(ctx, identities.UserId)
|
||||
}
|
||||
|
||||
// ChangePassword
|
||||
// @Tags user
|
||||
// @Summary Метод изменения пароля пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error "внутренняя ошибка"
|
||||
// @Router /user/change_password [POST]
|
||||
func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод изменения пароля пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль"
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка"
|
||||
// @Router /user/change_password [POST]
|
||||
func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -263,7 +270,7 @@ func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req do
|
||||
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrInvalidPassword):
|
||||
return apierrors.NewBusinessError(domain.ErrCodeInvalidPassword, "invalid password", err)
|
||||
return apierrors.New(http.StatusBadRequest, domain.ErrCodeInvalidPassword, err.Error(), err)
|
||||
case err != nil:
|
||||
return apierrors.NewInternalServiceError(err)
|
||||
default:
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package docs
|
||||
|
||||
import _ "embed"
|
||||
|
||||
// Embedded swagger files.
|
||||
var (
|
||||
//go:embed swagger.json
|
||||
SwaggerJson []byte
|
||||
)
|
||||
+2401
File diff suppressed because it is too large.
Load diff
-1314
File diff suppressed because it is too large.
Load diff
+17
-17
@@ -5,38 +5,38 @@ import (
|
||||
)
|
||||
|
||||
type Audit struct {
|
||||
Id int
|
||||
UserId int
|
||||
Message string
|
||||
CreatedAt time.Time
|
||||
Id int // Идентификатор audit'а
|
||||
UserId int // Идентификатор пользователя
|
||||
Message string // Сообщение
|
||||
CreatedAt time.Time // Дата события
|
||||
}
|
||||
|
||||
type AuditResponse struct {
|
||||
TotalCount int
|
||||
Items []Audit
|
||||
TotalCount int // Количество audit'ов
|
||||
Items []Audit // Список audit'ов
|
||||
}
|
||||
|
||||
type AuditPageRequest struct {
|
||||
LimitOffestParams
|
||||
LimitOffsetParams
|
||||
|
||||
Order *OrderParams
|
||||
Query *AuditQuery
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *AuditQuery // Параметры выборки
|
||||
}
|
||||
|
||||
type AuditQuery struct {
|
||||
Id *int
|
||||
UserId []int
|
||||
Message *string
|
||||
CreatedAt *DateFromToParams
|
||||
Id *int // Фильтр по идентификатору audit
|
||||
UserId []int // Фильтр по идентификатору пользователей
|
||||
Message *string // Фильтр по сообщению
|
||||
CreatedAt *DateFromToParams // Фильтр по дате
|
||||
}
|
||||
|
||||
type SetAuditEvent struct {
|
||||
Event string
|
||||
Enabled bool
|
||||
Event string // Название события
|
||||
Enabled bool // Включено/выключено
|
||||
}
|
||||
|
||||
type AuditEvent struct {
|
||||
Event string
|
||||
Name string
|
||||
Event string // Название события
|
||||
Name string //
|
||||
Enabled bool
|
||||
}
|
||||
+17
-3
@@ -3,7 +3,7 @@ package domain
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -13,8 +13,8 @@ const (
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUnauthenticated = errors.New("authentication failure")
|
||||
ErrSudirAuthorization = errors.New("User is authorized only with SUDIR")
|
||||
ErrSudirAuthIsMissed = errors.New("SUDIR authorization is not configured on the server")
|
||||
ErrOauthAuthorization = errors.New("user is authorized only with oauth")
|
||||
ErrOauthIsMissed = errors.New("oauth is not configured on the server")
|
||||
ErrInvalid = errors.New("entity is invalid")
|
||||
ErrAlreadyExists = errors.New("already exists")
|
||||
ErrTokenExpired = errors.New("token expired")
|
||||
@@ -23,6 +23,20 @@ var (
|
||||
ErrUserIsBlocked = errors.New("user is blocked")
|
||||
ErrNoActionRequired = errors.New("no action required")
|
||||
ErrInvalidPassword = errors.New("invalid password")
|
||||
ErrUnknownClient = errors.New("unknown client")
|
||||
)
|
||||
|
||||
const (
|
||||
UnknownAuditEventErrorCode = 601
|
||||
ErrOauthAuthorizationCode = 602
|
||||
ErrUnauthenticatedCode = 603
|
||||
ErrTooManyLoginRequestsCode = 604
|
||||
ErrOauthIsMissedCode = 605
|
||||
ErrAlreadyExistsCode = 606
|
||||
ErrNotFoundCode = 607
|
||||
ErrUnknownClientCode = 608
|
||||
ErrInvalidCode = 609
|
||||
ErrInvalidPasswordCode = 610
|
||||
)
|
||||
|
||||
type UnknownAuditEventError struct {
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
package domain
|
||||
|
||||
type GrpcError struct {
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
ErrorCode string `json:"errorCode"`
|
||||
Details []any `json:"details"`
|
||||
}
|
||||
+9
-8
@@ -6,21 +6,22 @@ const (
|
||||
)
|
||||
|
||||
type LogoutRequest struct {
|
||||
Reason string
|
||||
Reason string // Причина выхода
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `validate:"required"`
|
||||
Password string ` validate:"required"`
|
||||
Email string `validate:"required"` // Электронная почта
|
||||
Password string ` validate:"required"` // Пароль
|
||||
}
|
||||
|
||||
type LoginSudirRequest struct {
|
||||
AuthCode string `validate:"required"`
|
||||
type LoginOauthRequest struct {
|
||||
AuthCode string `validate:"required"` // Код для авторизации у OAuth-провайдера
|
||||
ClientName string `validate:"required"` // Уникальное имя конфигурации клиента
|
||||
}
|
||||
|
||||
// nolint:tagliatelle,godoclint
|
||||
type LoginResponse struct {
|
||||
Token string
|
||||
Expired string `json:",omitempty"`
|
||||
HeaderName string
|
||||
Token string // Токен
|
||||
Expired string `json:",omitempty"` // Дата истечения токена
|
||||
HeaderName string // Названия заголовка для передачи токена
|
||||
}
|
||||
+7
-7
@@ -7,17 +7,17 @@ const (
|
||||
DefaultOrderType = "desc"
|
||||
)
|
||||
|
||||
type LimitOffestParams struct {
|
||||
Limit uint64 `validate:"required"`
|
||||
Offset uint64
|
||||
type LimitOffsetParams struct {
|
||||
Limit uint64 `validate:"required"` // Максимальное количество записей
|
||||
Offset uint64 // Отступ для выборки
|
||||
}
|
||||
|
||||
type OrderParams struct {
|
||||
Field string
|
||||
Type string `validate:"oneof=asc desc ASC DESC"`
|
||||
Field string // Поле сортировки
|
||||
Type string `validate:"oneof=asc desc ASC DESC"` // Порядок сортировки
|
||||
}
|
||||
|
||||
type DateFromToParams struct {
|
||||
From time.Time `validate:"required"`
|
||||
To time.Time `validate:"required"`
|
||||
From time.Time `validate:"required"` // Дата с
|
||||
To time.Time `validate:"required"` // Дата до
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package domain
|
||||
|
||||
type Permission struct {
|
||||
Key string
|
||||
Name string
|
||||
Key string // Ключ прав
|
||||
Name string // Пользовательское название
|
||||
}
|
||||
+26
-19
@@ -5,32 +5,39 @@ import (
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
Id int
|
||||
Name string
|
||||
ExternalGroup string
|
||||
ChangeMessage string
|
||||
Permissions []string
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time // Дата создания
|
||||
UpdatedAt time.Time // Дата обновления
|
||||
}
|
||||
|
||||
type CreateRoleRequest struct {
|
||||
Name string
|
||||
ExternalGroup string
|
||||
ChangeMessage string
|
||||
Permissions []string
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
}
|
||||
|
||||
type UpdateRoleRequest struct {
|
||||
Id int
|
||||
Name string
|
||||
ExternalGroup string
|
||||
ChangeMessage string
|
||||
Permissions []string
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
}
|
||||
|
||||
type DeleteRoleRequest struct {
|
||||
Id int
|
||||
Id int // Идентификатор роли
|
||||
}
|
||||
|
||||
type RoleAllRequest struct {
|
||||
ApplicationGroup *string `validate:"omitnil,min=1"` // Фильтр по группе приложений
|
||||
}
|
||||
+7
-7
@@ -1,20 +1,20 @@
|
||||
package domain
|
||||
|
||||
type SecureAuthRequest struct {
|
||||
Token string
|
||||
Token string // Токен
|
||||
}
|
||||
|
||||
type SecureAuthResponse struct {
|
||||
Authenticated bool
|
||||
ErrorReason string
|
||||
AdminId int64
|
||||
Authenticated bool // Флаг успешной аутентикации
|
||||
ErrorReason string // Причина ошибки
|
||||
AdminId int64 // Идентификатор администратора
|
||||
}
|
||||
|
||||
type SecureAuthzRequest struct {
|
||||
AdminId int
|
||||
Permission string
|
||||
AdminId int // Идентификатор администратора
|
||||
Permission string // Роль
|
||||
}
|
||||
|
||||
type SecureAuthzResponse struct {
|
||||
Authorized bool
|
||||
Authorized bool // Флаг успешноЙ авторизации
|
||||
}
|
||||
+39
-16
@@ -4,34 +4,57 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
SessionStatusAllowed = "ALLOWED"
|
||||
SessionStatusAllowedRus = "Активная"
|
||||
|
||||
SessionStatusExpired = "EXPIRED"
|
||||
SessionStatusExpiredRus = "Истекшая"
|
||||
|
||||
SessionStatusRevoked = "REVOKED"
|
||||
SessionStatusRevokedRus = "Отмененная"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
Id int
|
||||
UserId int
|
||||
Status string
|
||||
ExpiredAt time.Time
|
||||
CreatedAt time.Time
|
||||
Id int // Идентификатор сессии
|
||||
UserId int // Идентификатор пользоватеккля
|
||||
Status string // Статус сессии
|
||||
ExpiredAt time.Time // Дата протухания сессии
|
||||
CreatedAt time.Time // Дата создания сессии
|
||||
}
|
||||
|
||||
type SessionPageRequest struct {
|
||||
LimitOffestParams
|
||||
LimitOffsetParams
|
||||
|
||||
Order *OrderParams
|
||||
Query *SessionQuery
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *SessionQuery // Параметры выборки
|
||||
}
|
||||
|
||||
type SessionQuery struct {
|
||||
Id *int
|
||||
UserId []int
|
||||
Status []string
|
||||
CreatedAt *DateFromToParams
|
||||
ExpiredAt *DateFromToParams
|
||||
Id *int // Фильтр по идентификатору сессии
|
||||
UserId []int // Фильтр по идентификаторам пользователей
|
||||
Status []string // Фильтр по статусам
|
||||
CreatedAt *DateFromToParams // Фильтр по дате создания
|
||||
ExpiredAt *DateFromToParams // Фильтр по дате протухания
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
TotalCount int
|
||||
Items []Session
|
||||
TotalCount int // Количество сессий
|
||||
Items []Session // Список сессий
|
||||
}
|
||||
|
||||
type RevokeRequest struct {
|
||||
Id int `validate:"required"`
|
||||
Id int `validate:"required"` // Идентификатор сессии
|
||||
}
|
||||
|
||||
func (s Session) StatusRus() string {
|
||||
switch s.Status {
|
||||
case SessionStatusAllowed:
|
||||
return SessionStatusAllowedRus
|
||||
case SessionStatusExpired:
|
||||
return SessionStatusExpiredRus
|
||||
case SessionStatusRevoked:
|
||||
return SessionStatusRevokedRus
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package domain
|
||||
|
||||
type UIDesign struct {
|
||||
Name string // Название ui
|
||||
PrimaryColor string `example:"#ff4d4f"` // Цвет в HEX
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
type ClientNameRequest struct {
|
||||
ClientName string `validate:"required"`
|
||||
}
|
||||
|
||||
type UiOauthSetting struct {
|
||||
LoginUrl string // URL для получения authCode для авторизации через OAuth
|
||||
LogoutUrl string // URL для завершения сессии
|
||||
}
|
||||
+49
-48
@@ -5,83 +5,84 @@ import (
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Id int64
|
||||
Roles []int
|
||||
FirstName string
|
||||
LastName string
|
||||
FullName string
|
||||
Email string
|
||||
Description string
|
||||
Blocked bool
|
||||
LastSessionCreatedAt *time.Time
|
||||
UpdatedAt time.Time
|
||||
CreatedAt time.Time
|
||||
Id int64 // Идентификатор пользователя
|
||||
Roles []int // Список идентификаторов ролей
|
||||
FirstName string // Имя
|
||||
LastName string // Фамилия
|
||||
FullName string // ФИО
|
||||
Email string // Электронная почта
|
||||
Description string // Описание
|
||||
Blocked bool // Флаг блокировки
|
||||
LastSessionCreatedAt *time.Time // Дата создания последней сессии
|
||||
UpdatedAt time.Time // Дата обновлёния
|
||||
CreatedAt time.Time // Дата создания
|
||||
}
|
||||
|
||||
type UsersResponse struct {
|
||||
Items []User
|
||||
Items []User // Список пользователей
|
||||
}
|
||||
|
||||
type UserQuery struct {
|
||||
Id *int
|
||||
UserId []int
|
||||
Description *string
|
||||
Email *string
|
||||
Roles []int
|
||||
LastSessionCreatedAt *DateFromToParams
|
||||
Id *int // Фильтр по идентификатору пользователя
|
||||
UserId []int // Фильтр по идентификаторам пользователя
|
||||
Description *string // Фильтр по описанию
|
||||
Email *string // Фильтр по электроннйо почты
|
||||
Roles []int // Фильтр по ролям
|
||||
LastSessionCreatedAt *DateFromToParams // Фильтр по дате создания последней сессии
|
||||
}
|
||||
|
||||
type UsersPageRequest struct {
|
||||
LimitOffestParams
|
||||
LimitOffsetParams
|
||||
RoleAllRequest
|
||||
|
||||
Order *OrderParams
|
||||
Query *UserQuery
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *UserQuery // Параметры выборки
|
||||
}
|
||||
|
||||
type AdminUserShort struct {
|
||||
FirstName string
|
||||
LastName string
|
||||
FullName string
|
||||
Email string `validate:"required"`
|
||||
Role string
|
||||
Roles []int
|
||||
RoleNames []string
|
||||
Permissions []string
|
||||
IdleTimeoutMs int
|
||||
FirstName string // Имя
|
||||
LastName string // Фамилия
|
||||
FullName string // ФИО
|
||||
Email string `validate:"required"` // Электронный адрес
|
||||
Role string // Название роли
|
||||
Roles []int // Список идентификаторов ролей
|
||||
RoleNames []string // Список названия ролей
|
||||
Permissions []string // Список прав
|
||||
IdleTimeoutMs int // Время бездействия пользователя в мс
|
||||
}
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Roles []int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string `validate:"required"`
|
||||
Password string `validate:"required"`
|
||||
Description string
|
||||
Roles []int // Список идентификаторов ролей
|
||||
FirstName string // Имя
|
||||
LastName string // Фамилия
|
||||
Email string `validate:"required"` // Электронный адрес
|
||||
Password string `validate:"required"` // Пароль
|
||||
Description string // Описание
|
||||
}
|
||||
|
||||
type UpdateUserRequest struct {
|
||||
Id int64 `validate:"required"`
|
||||
Roles []int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
Description string
|
||||
Blocked bool
|
||||
Id int64 `validate:"required"` // Идентификатор пользователя
|
||||
Roles []int // Список идентификаторов ролей
|
||||
FirstName string // Имя
|
||||
LastName string // Фамилия
|
||||
Email string // Электронный адрес
|
||||
Description string // Описание
|
||||
Blocked bool // Флаг блокировки
|
||||
}
|
||||
|
||||
type DeleteResponse struct {
|
||||
Deleted int
|
||||
Deleted int // Количество удалённых УЗ
|
||||
}
|
||||
|
||||
type IdentitiesRequest struct {
|
||||
Ids []int64 `validate:"required"`
|
||||
Ids []int64 `validate:"required"` // Список идентификаторов
|
||||
}
|
||||
|
||||
type IdRequest struct {
|
||||
UserId int `validate:"required"`
|
||||
UserId int `validate:"required"` // Идентификато пользователя
|
||||
}
|
||||
|
||||
type ChangePasswordRequest struct {
|
||||
OldPassword string `validate:"required"`
|
||||
NewPassword string `validate:"required"`
|
||||
OldPassword string `validate:"required"` // Старый пароль
|
||||
NewPassword string `validate:"required"` // Новый пароль
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package entity
|
||||
|
||||
const (
|
||||
SessionStatusAllowed = "ALLOWED"
|
||||
SessionStatusAllowedRus = "Активная"
|
||||
|
||||
SessionStatusExpired = "EXPIRED"
|
||||
SessionStatusExpiredRus = "Истекшая"
|
||||
|
||||
SessionStatusRevoked = "REVOKED"
|
||||
SessionStatusRevokedRus = "Отмененная"
|
||||
)
|
||||
|
||||
func AuditColumnNames() []string {
|
||||
return []string{"Пользователь", "Время события", "Действие"}
|
||||
}
|
||||
|
||||
func SessionColumnNames() []string {
|
||||
return []string{"Пользователь", "Идентификатор", "Дата начала сессии", "Дата окончания сессии", "Статус"}
|
||||
}
|
||||
|
||||
func UserColumnNames() []string {
|
||||
return []string{"id", "Пользователь", "Описание", "Email", "Роль", "Последняя сессия"}
|
||||
}
|
||||
|
||||
func RoleColumnNames() []string {
|
||||
return []string{"Действие", "Ключ в системе"}
|
||||
}
|
||||
@@ -4,19 +4,26 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type ClientSetting struct {
|
||||
AuthCode string
|
||||
ClientId string
|
||||
ClientSecret string
|
||||
RedirectURI string
|
||||
}
|
||||
|
||||
// nolint:tagliatelle,godoclint
|
||||
type SudirAuthError struct {
|
||||
type OauthAuthError struct {
|
||||
ErrorName string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
func (s *SudirAuthError) Error() string {
|
||||
func (s *OauthAuthError) Error() string {
|
||||
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
||||
}
|
||||
|
||||
// nolint:tagliatelle,errname,godoclint
|
||||
type SudirUserResponse struct {
|
||||
*SudirAuthError
|
||||
type OauthUserResponse struct {
|
||||
*OauthAuthError
|
||||
|
||||
Email string `json:"email"`
|
||||
Groups []string `json:"groups"`
|
||||
@@ -27,8 +34,8 @@ type SudirUserResponse struct {
|
||||
}
|
||||
|
||||
// nolint:tagliatelle,errname,godoclint
|
||||
type SudirTokenResponse struct {
|
||||
*SudirAuthError
|
||||
type OauthTokenResponse struct {
|
||||
*OauthAuthError
|
||||
|
||||
IdToken string `json:"id_token"`
|
||||
AccessToken string `json:"access_token"`
|
||||
+9
-8
@@ -13,14 +13,15 @@ const (
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
Id int
|
||||
Name string
|
||||
ExternalGroup string
|
||||
Permissions PermList
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Id int
|
||||
Name string
|
||||
ExternalGroup string
|
||||
ApplicationGroup string
|
||||
Permissions PermList
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type PermList []string
|
||||
|
||||
+4
-3
@@ -3,8 +3,9 @@ package entity
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
SudirUserId *string
|
||||
OauthUserId *string
|
||||
Id int64
|
||||
Roles []int
|
||||
FirstName string
|
||||
LastName string
|
||||
FullName string
|
||||
@@ -18,9 +19,9 @@ type User struct {
|
||||
LastSessionCreatedAt *time.Time
|
||||
}
|
||||
|
||||
type SudirUser struct {
|
||||
type OauthUser struct {
|
||||
RoleIds []int
|
||||
SudirUserId string
|
||||
OauthUserId string
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
|
||||
@@ -1,84 +1,86 @@
|
||||
module msp-admin-service
|
||||
module isp-admin-service
|
||||
|
||||
go 1.26
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/iancoleman/strcase v0.3.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/txix-open/bgjob v1.6.0
|
||||
github.com/txix-open/isp-kit v1.65.2
|
||||
github.com/txix-open/isp-kit v1.76.0
|
||||
github.com/txix-open/jsonschema v1.3.0
|
||||
golang.org/x/crypto v0.49.0
|
||||
golang.org/x/sync v0.20.0
|
||||
google.golang.org/grpc v1.79.2
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/sync v0.25.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/buger/jsonparser v1.1.1 // indirect
|
||||
github.com/buger/jsonparser v1.6.1 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/coder/websocket v1.8.14 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/getsentry/sentry-go v0.43.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
|
||||
github.com/getsentry/sentry-go v0.50.0 // indirect
|
||||
github.com/go-faker/faker/v4 v4.12.0 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/go-playground/locales v0.14.2 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.2 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.8.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jackc/pgx/v5 v5.13.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.4 // indirect
|
||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/julienschmidt/httprouter v1.3.0 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/mailru/easyjson v0.9.2 // indirect
|
||||
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||
github.com/mfridman/interpolate v0.2.0 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/pressly/goose/v3 v3.27.0 // indirect
|
||||
github.com/prometheus/client_golang v1.23.2 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.67.5 // indirect
|
||||
github.com/prometheus/procfs v0.20.1 // indirect
|
||||
github.com/pandatix/go-abnf v0.5.5 // indirect
|
||||
github.com/pressly/goose/v3 v3.30.1 // indirect
|
||||
github.com/prometheus/client_golang v1.25.0 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.74.0 // indirect
|
||||
github.com/prometheus/procfs v0.23.0 // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
github.com/sethvargo/go-retry v0.3.0 // indirect
|
||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
||||
github.com/txix-open/bellows v1.2.0 // indirect
|
||||
github.com/txix-open/etp/v4 v4.0.1 // indirect
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
|
||||
github.com/txix-open/etp/v4 v4.1.3 // indirect
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.67.0 // indirect
|
||||
go.opentelemetry.io/otel v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.42.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
|
||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.1 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.4 // indirect
|
||||
golang.org/x/net v0.52.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.6 // indirect
|
||||
golang.org/x/net v0.63.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
|
||||
google.golang.org/grpc v1.85.0 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -9,43 +9,42 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
||||
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
|
||||
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
|
||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/getsentry/sentry-go v0.43.0 h1:XbXLpFicpo8HmBDaInk7dum18G9KSLcjZiyUKS+hLW4=
|
||||
github.com/getsentry/sentry-go v0.43.0/go.mod h1:XDotiNZbgf5U8bPDUAfvcFmOnMQQceESxyKaObSssW0=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
|
||||
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
|
||||
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
|
||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
|
||||
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
|
||||
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
|
||||
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
|
||||
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
|
||||
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
|
||||
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
|
||||
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -53,26 +52,26 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
|
||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
|
||||
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
|
||||
github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
|
||||
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
|
||||
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -83,18 +82,18 @@ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
|
||||
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
|
||||
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
|
||||
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -104,34 +103,35 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
|
||||
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
|
||||
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
|
||||
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
|
||||
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
||||
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose/v3 v3.27.0 h1:/D30gVTuQhu0WsNZYbJi4DMOsx1lNq+6SkLe+Wp59BM=
|
||||
github.com/pressly/goose/v3 v3.27.0/go.mod h1:3ZBeCXqzkgIRvrEMDkYh1guvtoJTU5oMMuDdkutoM78=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
|
||||
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
|
||||
github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=
|
||||
github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
|
||||
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
|
||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
||||
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
|
||||
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
|
||||
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
|
||||
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
|
||||
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
|
||||
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
|
||||
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
|
||||
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
|
||||
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -143,22 +143,22 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
|
||||
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
|
||||
github.com/txix-open/bgjob v1.6.0 h1:Vwj9cAsIhMrHPKRZVxfg6mHqE9LI/atDCq1aeihH3+I=
|
||||
github.com/txix-open/bgjob v1.6.0/go.mod h1:aKbwpVclWmq82s7fchazp099yWjEpVKFkxT85i4hARM=
|
||||
github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA=
|
||||
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
||||
github.com/txix-open/grmq v1.10.0 h1:1bXuF+7TxtUvoh+Wn6SOCYpVACFbWDuDmz/+tKwW9Ms=
|
||||
github.com/txix-open/grmq v1.10.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po=
|
||||
github.com/txix-open/isp-kit v1.65.2 h1:AH4PTpgEJFqaggfQw3k6c05xWTRx+Xqxkx5iZ3vEPNs=
|
||||
github.com/txix-open/isp-kit v1.65.2/go.mod h1:F4B/+ErbNVaWzIIGasXM5DtcDKtjl6u2OESO02RyzCI=
|
||||
github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo=
|
||||
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
|
||||
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
|
||||
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
|
||||
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
|
||||
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
|
||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
||||
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
||||
@@ -170,56 +170,58 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
|
||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.67.0 h1:c9r/G1CSw4dPI1jaNNG9RnQP+q4SvZnHciDQJVIvchU=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.67.0/go.mod h1:gO9smoZe9KnZcJCqcB0lMmQ4Z5VEifYmjMTpnwtTSuQ=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=
|
||||
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
|
||||
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=
|
||||
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
|
||||
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
|
||||
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
|
||||
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
|
||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
|
||||
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
|
||||
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5 h1:CogIeEXn4qWYzzQU0QqvYBM8yDF9cFYzDq9ojSpv0Js=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:EIQZ5bFCfRQDV4MhRle7+OgjNtZ6P1PiZBgAKuxXu/Y=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 h1:aJmi6DVGGIStN9Mobk/tZOOQUBbj0BPjZjjnOdoZKts=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.79.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU=
|
||||
google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
|
||||
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
|
||||
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
@@ -228,11 +230,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/libc v1.68.0 h1:PJ5ikFOV5pwpW+VqCK1hKJuEWsonkIJhhIXyuF/91pQ=
|
||||
modernc.org/libc v1.68.0/go.mod h1:NnKCYeoYgsEqnY3PgvNgAeaJnso968ygU8Z0DxjoEc0=
|
||||
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
|
||||
modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/sqlite v1.46.1 h1:eFJ2ShBLIEnUWlLy12raN0Z1plqmFX9Qe3rjQTKt6sU=
|
||||
modernc.org/sqlite v1.46.1/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
|
||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
|
||||
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
|
||||
@@ -1,9 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/routes"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/routes"
|
||||
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
@@ -12,19 +12,18 @@ import (
|
||||
|
||||
var version = "1.0.0"
|
||||
|
||||
// @title msp-admin-service
|
||||
// @version 1.0.0
|
||||
// @description сервис управления администраторами
|
||||
// @title isp-admin-service
|
||||
// @version 1.0.0
|
||||
// @description сервис управления администраторами
|
||||
|
||||
// @license.name GNU GPL v3.0
|
||||
// @license.name GNU GPL v3.0
|
||||
|
||||
// @host localhost:9000
|
||||
// @BasePath /api/admin
|
||||
// @host localhost:9000
|
||||
// @BasePath /api/admin
|
||||
|
||||
//go:generate swag init --parseDependency
|
||||
//go:generate rm -f docs/swagger.json docs/docs.go
|
||||
//go:generate swag init -pd -ot json -eot json
|
||||
func main() {
|
||||
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors(), cluster.GrpcTransport)
|
||||
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.HttpTransport)
|
||||
app := boot.App
|
||||
logger := app.Logger()
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE users RENAME COLUMN sudir_user_id TO oauth_user_id;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE users RENAME COLUMN oauth_user_id TO sudir_user_id;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE roles ADD COLUMN application_group TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE roles DROP COLUMN application_group;
|
||||
+3
-3
@@ -4,14 +4,14 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/iancoleman/strcase"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
)
|
||||
|
||||
//nolint:gosec
|
||||
const (
|
||||
getTokenEndpoint = "/oauth/te"
|
||||
getUserEndpoint = "/oauth/me"
|
||||
)
|
||||
|
||||
type Oauth struct {
|
||||
cli *httpcli.Client
|
||||
}
|
||||
|
||||
func NewOauth(cli *httpcli.Client) Oauth {
|
||||
return Oauth{
|
||||
cli: cli,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Oauth) GetToken(ctx context.Context, clientSetting entity.ClientSetting) (*entity.OauthTokenResponse, error) {
|
||||
ctx = http_metrics.ClientEndpointToContext(ctx, getTokenEndpoint)
|
||||
|
||||
response := entity.OauthTokenResponse{}
|
||||
err := s.cli.Post(getTokenEndpoint).
|
||||
BasicAuth(httpcli.BasicAuth{
|
||||
Username: clientSetting.ClientId,
|
||||
Password: clientSetting.ClientSecret,
|
||||
}).
|
||||
Header("Content-Type", "application/x-www-form-urlencoded").
|
||||
QueryParams(map[string]any{
|
||||
"grant_type": "authorization_code",
|
||||
"code": clientSetting.AuthCode,
|
||||
"redirect_uri": clientSetting.RedirectURI,
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "call POST: '%s'", getTokenEndpoint)
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
func (s Oauth) GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error) {
|
||||
ctx = http_metrics.ClientEndpointToContext(ctx, getUserEndpoint)
|
||||
|
||||
response := entity.OauthUserResponse{}
|
||||
err := s.cli.Get(getUserEndpoint).
|
||||
Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)).
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "call GET: '%s'", getUserEndpoint)
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
}
|
||||
+24
-7
@@ -4,13 +4,14 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
@@ -24,6 +25,7 @@ const (
|
||||
updatedAtRolesColumn = "updated_at"
|
||||
permissionsRolesColumn = "permissions"
|
||||
externalGroupRolesColumn = "external_group"
|
||||
applicationGroupColumn = "application_group"
|
||||
immutableRolesColumn = "immutable"
|
||||
exclusiveRolesColumn = "exclusive"
|
||||
)
|
||||
@@ -36,7 +38,7 @@ func (r Role) GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error)
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds")
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("id, name, external_group, permissions, created_at, updated_at").
|
||||
Select("id, name, external_group, application_group, permissions, created_at, updated_at").
|
||||
From("roles").
|
||||
Where(squirrel.Eq{"id": id}).
|
||||
ToSql()
|
||||
@@ -66,6 +68,7 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err
|
||||
updatedAtRolesColumn,
|
||||
permissionsRolesColumn,
|
||||
externalGroupRolesColumn,
|
||||
applicationGroupColumn,
|
||||
immutableRolesColumn,
|
||||
exclusiveRolesColumn,
|
||||
).
|
||||
@@ -100,6 +103,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
|
||||
updatedAtRolesColumn,
|
||||
permissionsRolesColumn,
|
||||
externalGroupRolesColumn,
|
||||
applicationGroupColumn,
|
||||
immutableRolesColumn,
|
||||
exclusiveRolesColumn,
|
||||
).
|
||||
@@ -121,7 +125,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
|
||||
|
||||
func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All")
|
||||
q := "select id, name, external_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
|
||||
q := "select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
|
||||
roles := make([]entity.Role, 0)
|
||||
err := r.db.Select(ctx, &roles, q)
|
||||
if err != nil {
|
||||
@@ -130,12 +134,24 @@ func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (r Role) AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.AllWithFilter")
|
||||
roles := make([]entity.Role, 0)
|
||||
err := r.db.Select(ctx, &roles, `
|
||||
select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at
|
||||
from roles where application_group=$1 order by created_at`, applicationGroup)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "select all roles")
|
||||
}
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole")
|
||||
|
||||
q, args, err := query.New().Insert("roles").
|
||||
Columns("name", "permissions", "external_group").
|
||||
Values(role.Name, role.Permissions, role.ExternalGroup).
|
||||
Columns("name", "permissions", "external_group", "application_group").
|
||||
Values(role.Name, role.Permissions, role.ExternalGroup, role.ApplicationGroup).
|
||||
Suffix("RETURNING *").ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
@@ -157,6 +173,7 @@ func (r Role) Update(ctx context.Context, role entity.Role) (*entity.Role, error
|
||||
Set("name", role.Name).
|
||||
Set("permissions", role.Permissions).
|
||||
Set("external_group", role.ExternalGroup).
|
||||
Set("application_group", role.ApplicationGroup).
|
||||
Where(squirrel.Eq{"id": role.Id}).
|
||||
Suffix("RETURNING *").ToSql()
|
||||
if err != nil {
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type Sudir struct {
|
||||
httpCli *httpcli.Client
|
||||
cfg *conf.SudirAuth
|
||||
}
|
||||
|
||||
func NewSudir(httpCli *httpcli.Client, cfg *conf.SudirAuth) Sudir {
|
||||
return Sudir{
|
||||
httpCli: httpCli,
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Sudir) GetToken(ctx context.Context, authCode string) (*entity.SudirTokenResponse, error) {
|
||||
urlString, err := url.JoinPath(s.cfg.Host, "/oauth/te")
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build url")
|
||||
}
|
||||
|
||||
ctx = http_metrics.ClientEndpointToContext(ctx, urlString)
|
||||
|
||||
response := entity.SudirTokenResponse{}
|
||||
err = s.httpCli.Post(urlString).
|
||||
BasicAuth(httpcli.BasicAuth{
|
||||
Username: s.cfg.ClientId,
|
||||
Password: s.cfg.ClientSecret,
|
||||
}).
|
||||
Header("Content-Type", "application/x-www-form-urlencoded").
|
||||
QueryParams(map[string]any{
|
||||
"grant_type": "authorization_code",
|
||||
"code": authCode,
|
||||
"redirect_uri": s.cfg.RedirectURI,
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "http request")
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
func (s Sudir) GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error) {
|
||||
urlString, err := url.JoinPath(s.cfg.Host, "/oauth/me")
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build url")
|
||||
}
|
||||
|
||||
ctx = http_metrics.ClientEndpointToContext(ctx, urlString)
|
||||
|
||||
response := entity.SudirUserResponse{}
|
||||
err = s.httpCli.
|
||||
Get(urlString).
|
||||
Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)).
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "http request")
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
}
|
||||
+3
-3
@@ -9,12 +9,12 @@ import (
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/iancoleman/strcase"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
|
||||
+21
-21
@@ -6,14 +6,14 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/iancoleman/strcase"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
@@ -25,7 +25,7 @@ const (
|
||||
passwordUsersColumn = "password"
|
||||
createdAtUsersColumn = "created_at"
|
||||
updatedAtUsersColumn = "updated_at"
|
||||
sudirUserIdUsersColumn = "sudir_user_id"
|
||||
oauthUserIdUsersColumn = "oauth_user_id"
|
||||
blockedUsersColumn = "blocked"
|
||||
descriptionUsersColumn = "description"
|
||||
lastActiveAtUsersColumn = "last_active_at"
|
||||
@@ -45,7 +45,7 @@ func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, e
|
||||
|
||||
q, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn).
|
||||
From("users").
|
||||
Where(squirrel.Eq{"email": email}).
|
||||
@@ -72,7 +72,7 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
||||
|
||||
q, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn).
|
||||
From("users").
|
||||
Where(squirrel.Eq{"id": identity}).
|
||||
@@ -94,17 +94,17 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) GetUserByEmailAndSudirId(ctx context.Context, email string, sudirUserId string) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
||||
func (u User) GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmailAndOauthId")
|
||||
|
||||
equalClause := squirrel.Eq{"email": email, "sudir_user_id": nil}
|
||||
if sudirUserId != "" {
|
||||
equalClause["sudir_user_id"] = sudirUserId
|
||||
equalClause := squirrel.Eq{"email": email, "oauth_user_id": nil}
|
||||
if oauthUserId != "" {
|
||||
equalClause["oauth_user_id"] = oauthUserId
|
||||
}
|
||||
|
||||
q, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn).
|
||||
From("users").
|
||||
Where(equalClause).
|
||||
@@ -126,13 +126,13 @@ func (u User) GetUserByEmailAndSudirId(ctx context.Context, email string, sudirU
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertBySudirUserId")
|
||||
func (u User) UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertByOauthUserId")
|
||||
|
||||
selectQ := `
|
||||
insert into users as u (first_name, last_name, full_name, email, created_at, updated_at, sudir_user_id)
|
||||
insert into users as u (first_name, last_name, full_name, email, created_at, updated_at, oauth_user_id)
|
||||
values ($1, $2, $3, $4, $5, $6, $7)
|
||||
on conflict (sudir_user_id) do update
|
||||
on conflict (oauth_user_id) do update
|
||||
set first_name = excluded.first_name,
|
||||
last_name = excluded.last_name,
|
||||
full_name = excluded.full_name,
|
||||
@@ -145,7 +145,7 @@ func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entit
|
||||
err := u.db.SelectRow(ctx,
|
||||
&result,
|
||||
selectQ,
|
||||
user.FirstName, user.LastName, user.FullName, user.Email, user.CreatedAt, user.UpdatedAt, user.SudirUserId,
|
||||
user.FirstName, user.LastName, user.FullName, user.Email, user.CreatedAt, user.UpdatedAt, user.OauthUserId,
|
||||
)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, domain.ErrUserIsBlocked
|
||||
@@ -162,7 +162,7 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]enti
|
||||
|
||||
q := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
||||
From("users").
|
||||
Offset(req.Offset).
|
||||
@@ -193,7 +193,7 @@ func (u User) GetAllUsers(ctx context.Context) ([]entity.User, error) {
|
||||
|
||||
query, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
||||
From("users").ToSql()
|
||||
if err != nil {
|
||||
@@ -214,7 +214,7 @@ func (u User) GetUsersByEmail(ctx context.Context, email string) ([]entity.User,
|
||||
|
||||
q, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn).
|
||||
From("users").
|
||||
Where(squirrel.Eq{"email": email}).
|
||||
@@ -274,7 +274,7 @@ func (u User) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser)
|
||||
descriptionUsersColumn: user.Description,
|
||||
}).
|
||||
Where(squirrel.Eq{"id": id}).
|
||||
Suffix("RETURNING id, first_name, last_name, full_name, email, sudir_user_id, description, created_at, updated_at").
|
||||
Suffix("RETURNING id, first_name, last_name, full_name, email, oauth_user_id, description, created_at, updated_at").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
|
||||
@@ -3,12 +3,13 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type UserRole struct {
|
||||
|
||||
+186
-100
@@ -1,12 +1,14 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"msp-admin-service/controller"
|
||||
"isp-admin-service/controller"
|
||||
"isp-admin-service/docs"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/common_endpoints"
|
||||
httpEndpoint "github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
)
|
||||
|
||||
type Controllers struct {
|
||||
@@ -18,16 +20,24 @@ type Controllers struct {
|
||||
Audit controller.Audit
|
||||
Role controller.Role
|
||||
Permissions controller.Permissions
|
||||
UiSettings controller.UiSettings
|
||||
Download controller.Download
|
||||
}
|
||||
|
||||
func EndpointDescriptors() []cluster.EndpointDescriptor {
|
||||
return endpointDescriptors(Controllers{})
|
||||
return concatEndpoints(
|
||||
endpointDescriptors(Controllers{}),
|
||||
commonEndpoints(),
|
||||
)
|
||||
}
|
||||
|
||||
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { // nolint:ireturn
|
||||
muxer := grpc.NewMux()
|
||||
func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn
|
||||
muxer := router.New()
|
||||
for _, descriptor := range endpointDescriptors(c) {
|
||||
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
}
|
||||
for _, descriptor := range commonEndpoints() {
|
||||
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
}
|
||||
return muxer
|
||||
}
|
||||
@@ -36,148 +46,224 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
|
||||
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
return []cluster.EndpointDescriptor{
|
||||
{
|
||||
Path: "admin/auth/login",
|
||||
Inner: false,
|
||||
Handler: c.Auth.Login,
|
||||
Path: "admin/auth/login",
|
||||
Inner: false,
|
||||
Handler: c.Auth.Login,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/login_with_sudir",
|
||||
Inner: false,
|
||||
Handler: c.Auth.LoginWithSudir,
|
||||
Path: "admin/auth/login_with_oauth",
|
||||
Inner: false,
|
||||
Handler: c.Auth.LoginWithOauth,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout",
|
||||
Inner: true,
|
||||
Handler: c.Auth.Logout,
|
||||
Path: "admin/auth/logout",
|
||||
Inner: true,
|
||||
Handler: c.Auth.Logout,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout_with_reason",
|
||||
Inner: true,
|
||||
Handler: c.Auth.LogoutWithReason,
|
||||
Path: "admin/auth/logout_with_reason",
|
||||
Inner: true,
|
||||
Handler: c.Auth.LogoutWithReason,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_profile",
|
||||
Inner: true,
|
||||
Handler: c.User.GetProfile,
|
||||
Path: "admin/user/get_profile",
|
||||
Inner: true,
|
||||
Handler: c.User.GetProfile,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_design",
|
||||
Inner: true,
|
||||
Handler: c.Customization.GetUIDesign,
|
||||
Path: "admin/user/get_design",
|
||||
Inner: true,
|
||||
Handler: c.Customization.GetUIDesign,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetUsers,
|
||||
Path: "admin/user/get_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetUsers,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_all_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetAllUsers,
|
||||
Path: "admin/user/get_all_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetAllUsers,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/create_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_create"),
|
||||
Handler: c.User.CreateUser,
|
||||
Path: "admin/user/create_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_create"),
|
||||
Handler: c.User.CreateUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/update_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_update"),
|
||||
Handler: c.User.UpdateUser,
|
||||
Path: "admin/user/update_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_update"),
|
||||
Handler: c.User.UpdateUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/delete_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_delete"),
|
||||
Handler: c.User.DeleteUser,
|
||||
Path: "admin/user/delete_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_delete"),
|
||||
Handler: c.User.DeleteUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/block_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_block"),
|
||||
Handler: c.User.Block,
|
||||
Path: "admin/user/block_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_block"),
|
||||
Handler: c.User.Block,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_by_id",
|
||||
Inner: true,
|
||||
Handler: c.User.GetById,
|
||||
Path: "admin/user/get_by_id",
|
||||
Inner: true,
|
||||
Handler: c.User.GetById,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/change_password",
|
||||
Inner: true,
|
||||
Handler: c.User.ChangePassword,
|
||||
Path: "admin/user/change_password",
|
||||
Inner: true,
|
||||
Handler: c.User.ChangePassword,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Role.All,
|
||||
Path: "admin/role/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Role.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_permissions",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Permissions.GetPermissions,
|
||||
Path: "admin/user/get_permissions",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Permissions.GetPermissions,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/create",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_add"),
|
||||
Handler: c.Role.CreateRole,
|
||||
Path: "admin/role/create",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_add"),
|
||||
Handler: c.Role.CreateRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/update",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_update"),
|
||||
Handler: c.Role.UpdateRole,
|
||||
Path: "admin/role/update",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_update"),
|
||||
Handler: c.Role.UpdateRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/delete",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_delete"),
|
||||
Handler: c.Role.DeleteRole,
|
||||
Path: "admin/role/delete",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_delete"),
|
||||
Handler: c.Role.DeleteRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/session/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_view"),
|
||||
Handler: c.Session.All,
|
||||
Path: "admin/session/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_view"),
|
||||
Handler: c.Session.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/session/revoke",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_revoke"),
|
||||
Handler: c.Session.Revoke,
|
||||
Path: "admin/session/revoke",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_revoke"),
|
||||
Handler: c.Session.Revoke,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("security_log_view"),
|
||||
Handler: c.Audit.All,
|
||||
Path: "admin/log/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("security_log_view"),
|
||||
Handler: c.Audit.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.Events,
|
||||
Path: "admin/log/events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.Events,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/set_events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.SetEvents,
|
||||
Path: "admin/log/set_events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.SetEvents,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/secure/authenticate",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authenticate,
|
||||
Path: "admin/secure/authenticate",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authenticate,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/secure/authorize",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authorize,
|
||||
Path: "admin/secure/authorize",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authorize,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/ui_settings/oauth",
|
||||
Inner: false,
|
||||
Handler: c.UiSettings.OauthSettings,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
// download
|
||||
{
|
||||
Path: "user/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Users,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "session/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Sessions,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "log/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Audit,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "role/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Roles,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func commonEndpoints() []cluster.EndpointDescriptor {
|
||||
return common_endpoints.CommonEndpoints(
|
||||
"isp-admin-service",
|
||||
common_endpoints.WithSwaggerEndpoint(docs.SwaggerJson),
|
||||
)
|
||||
}
|
||||
|
||||
func concatEndpoints(endpoints ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
|
||||
var result []cluster.EndpointDescriptor
|
||||
for _, desc := range endpoints {
|
||||
result = append(result, desc...)
|
||||
}
|
||||
return result
|
||||
}
|
||||
+4
-4
@@ -4,11 +4,11 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
+30
-30
@@ -5,10 +5,10 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -30,7 +30,7 @@ type auditService interface {
|
||||
|
||||
type userRepository interface {
|
||||
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||
UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
||||
UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||
UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
|
||||
}
|
||||
@@ -40,15 +40,15 @@ type tokenService interface {
|
||||
RevokeAllByUserId(ctx context.Context, userId int64) error
|
||||
}
|
||||
|
||||
type sudirService interface {
|
||||
Authenticate(ctx context.Context, authCode string, repo roleRepo) (*entity.SudirUser, error)
|
||||
type oauthService interface {
|
||||
Authenticate(ctx context.Context, request domain.LoginOauthRequest, repo roleRepo) (*entity.OauthUser, error)
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
userRepository userRepository
|
||||
txRunner AuthTransactionRunner
|
||||
tokenService tokenService
|
||||
sudirService sudirService
|
||||
oauthService oauthService
|
||||
auditService auditService
|
||||
logger log.Logger
|
||||
maxInFlightLoginRequests int64
|
||||
@@ -60,7 +60,7 @@ func NewAuth(
|
||||
userRepository userRepository,
|
||||
txRunner AuthTransactionRunner,
|
||||
tokenService tokenService,
|
||||
sudirService sudirService,
|
||||
oauthService oauthService,
|
||||
auditService auditService,
|
||||
logger log.Logger,
|
||||
delayLoginRequestInSec int,
|
||||
@@ -70,7 +70,7 @@ func NewAuth(
|
||||
userRepository: userRepository,
|
||||
txRunner: txRunner,
|
||||
tokenService: tokenService,
|
||||
sudirService: sudirService,
|
||||
oauthService: oauthService,
|
||||
auditService: auditService,
|
||||
logger: logger,
|
||||
delayLoginRequest: time.Duration(delayLoginRequestInSec) * time.Second,
|
||||
@@ -100,8 +100,8 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
||||
return errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "get user by email")
|
||||
case user.SudirUserId != nil:
|
||||
return domain.ErrSudirAuthorization
|
||||
case user.OauthUserId != nil:
|
||||
return domain.ErrOauthAuthorization
|
||||
}
|
||||
|
||||
if user.Blocked {
|
||||
@@ -141,7 +141,7 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
||||
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
||||
var (
|
||||
user *entity.User
|
||||
|
||||
@@ -150,41 +150,41 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
||||
)
|
||||
|
||||
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
||||
sudirUser, err := a.sudirService.Authenticate(ctx, request.AuthCode, tx)
|
||||
oauthUser, err := a.oauthService.Authenticate(ctx, request, tx)
|
||||
|
||||
var authErr *entity.SudirAuthError
|
||||
var authErr *entity.OauthAuthError
|
||||
switch {
|
||||
case errors.As(err, &authErr):
|
||||
a.logger.Error(ctx, "sudir authenticate: error occurred", log.String("error", err.Error()))
|
||||
a.logger.Error(ctx, "oauth authenticate: error occurred", log.String("error", err.Error()))
|
||||
return domain.ErrUnauthenticated
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "sudir authenticate")
|
||||
case sudirUser.SudirUserId == "" || sudirUser.Email == "":
|
||||
a.logger.Error(ctx, "sudir authenticate: missing sudirUserId or email",
|
||||
log.String("userId", sudirUser.SudirUserId),
|
||||
log.String("email", sudirUser.Email))
|
||||
return errors.WithMessage(err, "oauth authenticate")
|
||||
case oauthUser.OauthUserId == "" || oauthUser.Email == "":
|
||||
a.logger.Error(ctx, "oauth authenticate: missing oauthUserId or email",
|
||||
log.String("userId", oauthUser.OauthUserId),
|
||||
log.String("email", oauthUser.Email))
|
||||
return domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
user, err = tx.UpsertBySudirUserId(ctx, entity.User{
|
||||
SudirUserId: &sudirUser.SudirUserId,
|
||||
FirstName: sudirUser.FirstName,
|
||||
LastName: sudirUser.LastName,
|
||||
FullName: sudirUser.FullName,
|
||||
Email: sudirUser.Email,
|
||||
user, err = tx.UpsertByOauthUserId(ctx, entity.User{
|
||||
OauthUserId: &oauthUser.OauthUserId,
|
||||
FirstName: oauthUser.FirstName,
|
||||
LastName: oauthUser.LastName,
|
||||
FullName: oauthUser.FullName,
|
||||
Email: oauthUser.Email,
|
||||
Password: "",
|
||||
Blocked: false,
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
})
|
||||
if errors.Is(err, domain.ErrUserIsBlocked) {
|
||||
return errors.Errorf("user with sudir user id = %s is blocked", sudirUser.SudirUserId)
|
||||
return errors.Errorf("user with oauth user id = %s is blocked", oauthUser.OauthUserId)
|
||||
}
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert by sudir user id")
|
||||
return errors.WithMessage(err, "upsert by oauth user id")
|
||||
}
|
||||
|
||||
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), sudirUser.RoleIds)
|
||||
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), oauthUser.RoleIds)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert user role links")
|
||||
}
|
||||
@@ -206,7 +206,7 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
||||
return nil, errors.WithMessage(err, "auth transaction")
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через СУДИР", entity.EventSuccessLogin)
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через OAuth", entity.EventSuccessLogin)
|
||||
|
||||
return &domain.LoginResponse{
|
||||
Token: tokenString,
|
||||
|
||||
@@ -3,9 +3,9 @@ package delete_old_audit_worker
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -4,11 +4,11 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"isp-admin-service/conf"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
requestLimit = 1000
|
||||
foundSymbol = "+"
|
||||
notFoundSymbol = "-"
|
||||
)
|
||||
|
||||
type Download struct {
|
||||
auditService Audit
|
||||
userService User
|
||||
tokenService Token
|
||||
roleService Role
|
||||
permissionService Permission
|
||||
loc *time.Location
|
||||
}
|
||||
|
||||
func NewDownload(
|
||||
auditService Audit,
|
||||
userService User,
|
||||
tokenService Token,
|
||||
roleService Role,
|
||||
permissionService Permission,
|
||||
) Download {
|
||||
loc, _ := time.LoadLocation("Europe/Moscow")
|
||||
return Download{
|
||||
auditService: auditService,
|
||||
userService: userService,
|
||||
tokenService: tokenService,
|
||||
roleService: roleService,
|
||||
permissionService: permissionService,
|
||||
loc: loc,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Download) DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
response, err := s.auditService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get audit")
|
||||
}
|
||||
|
||||
if response.TotalCount == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Audit")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.AuditColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write auditColumns to csv")
|
||||
}
|
||||
|
||||
userById, err := s.getUsersList(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users list")
|
||||
}
|
||||
|
||||
itemsCount := len(response.Items)
|
||||
for {
|
||||
for _, audit := range response.Items {
|
||||
username := getUsername(userById, audit.UserId)
|
||||
|
||||
row := []string{username, s.formatTime(&audit.CreatedAt, false), audit.Message}
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write audit row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
if itemsCount >= response.TotalCount {
|
||||
break
|
||||
}
|
||||
|
||||
req.Offset += requestLimit
|
||||
response, err = s.auditService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get audit")
|
||||
}
|
||||
|
||||
itemsCount += len(response.Items)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
response, err := s.tokenService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get sessions")
|
||||
}
|
||||
|
||||
if response.TotalCount == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Sessions")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.SessionColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write sessionColumns to csv")
|
||||
}
|
||||
|
||||
userById, err := s.getUsersList(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users list")
|
||||
}
|
||||
|
||||
itemsCount := len(response.Items)
|
||||
for {
|
||||
for _, session := range response.Items {
|
||||
row := []string{
|
||||
getUsername(userById, session.UserId),
|
||||
strconv.Itoa(session.Id),
|
||||
s.formatTime(&session.CreatedAt, false),
|
||||
s.formatTime(&session.ExpiredAt, false),
|
||||
session.StatusRus()}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write session row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
if itemsCount >= response.TotalCount {
|
||||
break
|
||||
}
|
||||
|
||||
req.Offset += requestLimit
|
||||
response, err = s.tokenService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get sessions")
|
||||
}
|
||||
|
||||
itemsCount += len(response.Items)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
users, err := s.userService.GetUsers(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users")
|
||||
}
|
||||
|
||||
roles, err := s.roleService.All(ctx, req.RoleAllRequest)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
if len(users.Items) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Users")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.UserColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write userColumns to csv")
|
||||
}
|
||||
|
||||
for _, user := range users.Items {
|
||||
row := []string{strconv.Itoa(int(user.Id)),
|
||||
user.FullName,
|
||||
user.Description,
|
||||
user.Email,
|
||||
getRoleNamesByIds(roles, user.Roles),
|
||||
s.formatTime(user.LastSessionCreatedAt, true)}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write user row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadRoles(ctx context.Context, req domain.RoleAllRequest, w http.ResponseWriter) error {
|
||||
roles, err := s.roleService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
perms := s.permissionService.All(ctx)
|
||||
|
||||
if len(perms) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
columns := entity.RoleColumnNames()
|
||||
for _, role := range roles {
|
||||
columns = append(columns, role.Name)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Roles")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, columns)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write role columns to csv")
|
||||
}
|
||||
|
||||
for _, perm := range perms {
|
||||
row := []string{perm.Name, perm.Key}
|
||||
|
||||
for _, role := range roles {
|
||||
if slices.Contains(role.Permissions, perm.Key) {
|
||||
row = append(row, foundSymbol)
|
||||
} else {
|
||||
row = append(row, notFoundSymbol)
|
||||
}
|
||||
}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write role row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) getUsersList(ctx context.Context) (map[int]domain.User, error) {
|
||||
users, err := s.userService.GetAllUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get users")
|
||||
}
|
||||
|
||||
userById := make(map[int]domain.User)
|
||||
for _, user := range users.Items {
|
||||
userById[int(user.Id)] = user
|
||||
}
|
||||
|
||||
return userById, nil
|
||||
}
|
||||
|
||||
func getUsername(userById map[int]domain.User, userId int) string {
|
||||
user, ok := userById[userId]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
return user.FullName
|
||||
}
|
||||
|
||||
func getRoleNamesByIds(roles []domain.Role, roleIds []int) string {
|
||||
names := make([]string, 0)
|
||||
for _, role := range roles {
|
||||
if slices.Contains(roleIds, role.Id) {
|
||||
names = append(names, role.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
func writeCsvLine(csvWriter *csv.Writer, line []string) error {
|
||||
err := csvWriter.Write(line)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write line to csv")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getCsvFileName(pageName string) string {
|
||||
return fmt.Sprintf("%s_%s.%s", pageName, time.Now().Format("02-01-2006_15:04:05"), "csv")
|
||||
}
|
||||
|
||||
func (s Download) formatTime(t *time.Time, onlyDate bool) string {
|
||||
if t == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if onlyDate {
|
||||
return t.In(s.loc).Format("02-01-2006")
|
||||
}
|
||||
|
||||
return t.In(s.loc).Format("02-01-2006 15:04:05")
|
||||
}
|
||||
@@ -3,9 +3,9 @@ package inactive_worker
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type oauthRepo interface {
|
||||
GetToken(ctx context.Context, creds entity.ClientSetting) (*entity.OauthTokenResponse, error)
|
||||
GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error)
|
||||
}
|
||||
|
||||
type roleRepo interface {
|
||||
GetRolesByExternalGroup(ctx context.Context, groups []string) ([]entity.Role, error)
|
||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
}
|
||||
|
||||
type Oauth struct {
|
||||
oauthRepo oauthRepo
|
||||
clientSettings map[string]conf.OauthClientConfig
|
||||
}
|
||||
|
||||
func NewOauth(settings []conf.OauthClientConfig, oauthRepo oauthRepo) (Oauth, error) {
|
||||
clientSettings := make(map[string]conf.OauthClientConfig, len(settings))
|
||||
for i, setting := range settings {
|
||||
_, ok := clientSettings[setting.ClientName]
|
||||
if ok {
|
||||
return Oauth{}, errors.Errorf("client setting [%d] has non-unique client name", i)
|
||||
}
|
||||
clientSettings[setting.ClientName] = setting
|
||||
}
|
||||
|
||||
return Oauth{
|
||||
oauthRepo: oauthRepo,
|
||||
clientSettings: clientSettings,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s Oauth) Authenticate(ctx context.Context, req domain.LoginOauthRequest, roleRepo roleRepo) (*entity.OauthUser, error) {
|
||||
if len(s.clientSettings) == 0 {
|
||||
return nil, domain.ErrOauthIsMissed
|
||||
}
|
||||
|
||||
setting, ok := s.clientSettings[req.ClientName]
|
||||
if !ok {
|
||||
return nil, domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
creds := entity.ClientSetting{
|
||||
AuthCode: req.AuthCode,
|
||||
ClientId: setting.ClientId,
|
||||
ClientSecret: setting.ClientSecret,
|
||||
RedirectURI: setting.RedirectURI,
|
||||
}
|
||||
tokenResponse, err := s.oauthRepo.GetToken(ctx, creds)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get token")
|
||||
case tokenResponse.OauthAuthError != nil:
|
||||
return nil, errors.WithMessage(tokenResponse.OauthAuthError, "get token")
|
||||
}
|
||||
|
||||
user, err := s.oauthRepo.GetUser(ctx, tokenResponse.AccessToken)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user")
|
||||
case user.OauthAuthError != nil:
|
||||
return nil, errors.WithMessage(user.OauthAuthError, "get user")
|
||||
}
|
||||
email := user.Email
|
||||
if email == "" {
|
||||
email = user.Sub
|
||||
}
|
||||
|
||||
rolesIds := make([]int, 0)
|
||||
if len(user.Groups) > 0 {
|
||||
roles, err := roleRepo.GetRolesByExternalGroup(ctx, user.Groups)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get roles by external groups")
|
||||
}
|
||||
for _, role := range roles {
|
||||
rolesIds = append(rolesIds, role.Id)
|
||||
}
|
||||
}
|
||||
|
||||
return &entity.OauthUser{
|
||||
RoleIds: rolesIds,
|
||||
OauthUserId: user.Sub,
|
||||
FirstName: user.GivenName,
|
||||
LastName: user.FamilyName,
|
||||
FullName: user.Name,
|
||||
Email: email,
|
||||
}, nil
|
||||
}
|
||||
@@ -3,20 +3,20 @@ package service
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
)
|
||||
|
||||
type Permission struct {
|
||||
permissions []domain.Permission
|
||||
}
|
||||
|
||||
func NewPermission(permissions []conf.Permission) *Permission {
|
||||
return &Permission{
|
||||
func NewPermission(permissions []conf.Permission) Permission {
|
||||
return Permission{
|
||||
permissions: toDomain(permissions),
|
||||
}
|
||||
}
|
||||
func (s *Permission) All(_ context.Context) []domain.Permission {
|
||||
func (s Permission) All(_ context.Context) []domain.Permission {
|
||||
return s.permissions
|
||||
}
|
||||
|
||||
|
||||
+50
-32
@@ -5,13 +5,15 @@ import (
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type roleRoleRepo interface {
|
||||
All(ctx context.Context) ([]entity.Role, error)
|
||||
AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error)
|
||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
Update(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
Delete(ctx context.Context, id int) error
|
||||
@@ -31,8 +33,17 @@ func NewRole(roleRepo roleRoleRepo, audit auditService) Role {
|
||||
}
|
||||
}
|
||||
|
||||
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
roles, err := u.roleRepo.All(ctx)
|
||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
||||
var (
|
||||
roles []entity.Role
|
||||
err error
|
||||
)
|
||||
switch {
|
||||
case req.ApplicationGroup != nil:
|
||||
roles, err = u.roleRepo.AllWithFilter(ctx, *req.ApplicationGroup)
|
||||
default:
|
||||
roles, err = u.roleRepo.All(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get all roles")
|
||||
}
|
||||
@@ -57,9 +68,10 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
|
||||
}
|
||||
|
||||
role, err = u.roleRepo.InsertRole(ctx, entity.Role{
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
Permissions: req.Permissions,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
ApplicationGroup: req.ApplicationGroup,
|
||||
Permissions: req.Permissions,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -68,13 +80,15 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
|
||||
|
||||
slices.Sort(role.Permissions)
|
||||
diff := diffToString(map[string]any{
|
||||
"Название": "",
|
||||
"Группа ЕСК": "",
|
||||
"Разрешения": []int{},
|
||||
"Название": "",
|
||||
"Группа ЕСК": "",
|
||||
"Группа приложений": "",
|
||||
"Разрешения": []int{},
|
||||
}, map[string]any{
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Группа приложений": role.ApplicationGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
})
|
||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||
fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
|
||||
@@ -105,10 +119,11 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
|
||||
oldRole := roles[0]
|
||||
|
||||
role, err := u.roleRepo.Update(ctx, entity.Role{
|
||||
Id: req.Id,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
Permissions: req.Permissions,
|
||||
Id: req.Id,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
ApplicationGroup: req.ApplicationGroup,
|
||||
Permissions: req.Permissions,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -118,13 +133,15 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
|
||||
slices.Sort(oldRole.Permissions)
|
||||
slices.Sort(role.Permissions)
|
||||
diff := diffToString(map[string]any{
|
||||
"Название": oldRole.Name,
|
||||
"Группа ЕСК": oldRole.ExternalGroup,
|
||||
"Разрешения": oldRole.Permissions,
|
||||
"Название": oldRole.Name,
|
||||
"Группа ЕСК": oldRole.ExternalGroup,
|
||||
"Группа приложений": oldRole.ApplicationGroup,
|
||||
"Разрешения": oldRole.Permissions,
|
||||
}, map[string]any{
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Группа приложений": role.ApplicationGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
})
|
||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||
fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
|
||||
@@ -147,13 +164,14 @@ func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId
|
||||
|
||||
func (u Role) toDomain(role entity.Role) domain.Role {
|
||||
return domain.Role{
|
||||
Id: role.Id,
|
||||
Name: role.Name,
|
||||
ExternalGroup: role.ExternalGroup,
|
||||
Permissions: role.Permissions,
|
||||
Immutable: role.Immutable,
|
||||
Exclusive: role.Exclusive,
|
||||
CreatedAt: role.CreatedAt,
|
||||
UpdatedAt: role.UpdatedAt,
|
||||
Id: role.Id,
|
||||
Name: role.Name,
|
||||
ExternalGroup: role.ExternalGroup,
|
||||
ApplicationGroup: role.ApplicationGroup,
|
||||
Permissions: role.Permissions,
|
||||
Immutable: role.Immutable,
|
||||
Exclusive: role.Exclusive,
|
||||
CreatedAt: role.CreatedAt,
|
||||
UpdatedAt: role.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type TokenRep interface {
|
||||
|
||||
@@ -3,9 +3,9 @@ package session_worker
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -4,11 +4,11 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type sudirRepo interface {
|
||||
GetToken(ctx context.Context, authCode string) (*entity.SudirTokenResponse, error)
|
||||
GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error)
|
||||
}
|
||||
|
||||
type roleRepo interface {
|
||||
GetRolesByExternalGroup(ctx context.Context, groups []string) ([]entity.Role, error)
|
||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
}
|
||||
|
||||
type Sudir struct {
|
||||
cfg *conf.SudirAuth
|
||||
sudirRepo sudirRepo
|
||||
}
|
||||
|
||||
func NewSudir(cfg *conf.SudirAuth, sudirRepo sudirRepo) Sudir {
|
||||
return Sudir{
|
||||
cfg: cfg,
|
||||
sudirRepo: sudirRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Sudir) Authenticate(ctx context.Context, authCode string, roleRepo roleRepo) (*entity.SudirUser, error) {
|
||||
if s.cfg == nil {
|
||||
return nil, domain.ErrSudirAuthIsMissed
|
||||
}
|
||||
|
||||
tokenResponse, err := s.sudirRepo.GetToken(ctx, authCode)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get token")
|
||||
case tokenResponse.SudirAuthError != nil:
|
||||
return nil, errors.WithMessage(tokenResponse.SudirAuthError, "get token")
|
||||
}
|
||||
|
||||
user, err := s.sudirRepo.GetUser(ctx, tokenResponse.AccessToken)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user")
|
||||
case user.SudirAuthError != nil:
|
||||
return nil, errors.WithMessage(user.SudirAuthError, "get user")
|
||||
}
|
||||
email := user.Email
|
||||
if email == "" {
|
||||
email = user.Sub
|
||||
}
|
||||
|
||||
rolesIds := make([]int, 0)
|
||||
if len(user.Groups) > 0 {
|
||||
roles, err := roleRepo.GetRolesByExternalGroup(ctx, user.Groups)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get roles by external groups")
|
||||
}
|
||||
for _, role := range roles {
|
||||
rolesIds = append(rolesIds, role.Id)
|
||||
}
|
||||
}
|
||||
|
||||
return &entity.SudirUser{
|
||||
RoleIds: rolesIds,
|
||||
SudirUserId: user.Sub,
|
||||
FirstName: user.GivenName,
|
||||
LastName: user.FamilyName,
|
||||
FullName: user.Name,
|
||||
Email: email,
|
||||
}, nil
|
||||
}
|
||||
+3
-3
@@ -6,10 +6,10 @@ import (
|
||||
"encoding/hex"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"net/url"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type UiSettings struct {
|
||||
oauthBaseUrl string
|
||||
settings map[string]conf.OauthClientConfig
|
||||
}
|
||||
|
||||
func NewUiSettings(oauthBaseUrl string, settings []conf.OauthClientConfig) UiSettings {
|
||||
settingsMap := make(map[string]conf.OauthClientConfig, len(settings))
|
||||
for _, setting := range settings {
|
||||
if setting.UiSetting == nil {
|
||||
continue
|
||||
}
|
||||
settingsMap[setting.ClientName] = setting
|
||||
}
|
||||
return UiSettings{
|
||||
oauthBaseUrl: oauthBaseUrl,
|
||||
settings: settingsMap,
|
||||
}
|
||||
}
|
||||
|
||||
func (s UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
||||
setting, ok := s.settings[req.ClientName]
|
||||
if !ok {
|
||||
return nil, domain.ErrUnknownClient
|
||||
}
|
||||
|
||||
loginUrl, err := s.buildUrl(
|
||||
setting.UiSetting.LoginEndpoint,
|
||||
map[string]string{
|
||||
"client_id": setting.ClientId,
|
||||
"redirect_uri": setting.RedirectURI,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("build url for login: %w", err)
|
||||
}
|
||||
|
||||
logoutUrl, err := s.buildUrl(setting.UiSetting.LogoutEndpoint, nil)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("build url for logout: %w", err)
|
||||
}
|
||||
return &domain.UiOauthSetting{
|
||||
LoginUrl: loginUrl,
|
||||
LogoutUrl: logoutUrl,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s UiSettings) buildUrl(methodPath string, additionalQuery map[string]string) (string, error) {
|
||||
method, err := url.Parse(methodPath)
|
||||
if err != nil {
|
||||
return "", errors.Errorf("parse method path")
|
||||
}
|
||||
|
||||
joined, err := url.JoinPath(s.oauthBaseUrl, method.Path)
|
||||
if err != nil {
|
||||
return "", errors.Errorf("join method path and baseUrl")
|
||||
}
|
||||
|
||||
u, err := url.Parse(joined)
|
||||
if err != nil {
|
||||
return "", errors.Errorf("parse joined")
|
||||
}
|
||||
|
||||
q := method.Query()
|
||||
for k, v := range additionalQuery {
|
||||
q.Set(k, v)
|
||||
}
|
||||
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String(), nil
|
||||
}
|
||||
+9
-9
@@ -8,10 +8,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -31,7 +31,7 @@ type UserRepo interface {
|
||||
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
||||
GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]entity.User, error)
|
||||
GetAllUsers(ctx context.Context) ([]entity.User, error)
|
||||
GetUserByEmailAndSudirId(ctx context.Context, email string, sudirUserId string) (*entity.User, error)
|
||||
GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error)
|
||||
GetUsersByEmail(ctx context.Context, email string) ([]entity.User, error)
|
||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||
DeleteUser(ctx context.Context, ids []int64) (int, error)
|
||||
@@ -207,7 +207,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
||||
var usr entity.User
|
||||
|
||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||
user, err := tx.GetUserByEmailAndSudirId(ctx, req.Email, "")
|
||||
user, err := tx.GetUserByEmailAndOauthId(ctx, req.Email, "")
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
break
|
||||
@@ -223,7 +223,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
||||
}
|
||||
|
||||
usr = entity.User{
|
||||
SudirUserId: nil,
|
||||
OauthUserId: nil,
|
||||
Id: 0,
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
@@ -301,12 +301,12 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
|
||||
|
||||
for _, usr := range users {
|
||||
// check in internal user space
|
||||
if (user.SudirUserId == nil && usr.SudirUserId == nil) && (usr.Id != req.Id) {
|
||||
if (user.OauthUserId == nil && usr.OauthUserId == nil) && (usr.Id != req.Id) {
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
|
||||
// check in sudir user space
|
||||
if usr.SudirUserId != nil && user.SudirUserId != nil && (*user.SudirUserId != *usr.SudirUserId) {
|
||||
// check in oauth user space
|
||||
if usr.OauthUserId != nil && user.OauthUserId != nil && (*user.OauthUserId != *usr.OauthUserId) {
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
}
|
||||
|
||||
+82
-86
@@ -1,25 +1,22 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestAuditSuite(t *testing.T) {
|
||||
@@ -32,13 +29,13 @@ type AuditSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (t *AuditSuite) SetupTest() {
|
||||
testInstance, _ := test.New(t.T())
|
||||
t.test = testInstance
|
||||
t.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
func (s *AuditSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
|
||||
remote := conf.Remote{
|
||||
Audit: conf.Audit{
|
||||
@@ -71,26 +68,26 @@ func (t *AuditSuite) SetupTest() {
|
||||
AuditTTl: conf.AuditTTlSetting{},
|
||||
},
|
||||
}
|
||||
cfg := assembly.NewLocator(testInstance.Logger(), httpcli.New(), t.db).
|
||||
Config(context.Background(), remote, time.Minute)
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.insertAuditLogs()
|
||||
|
||||
t.insertAuditLogs()
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
t.grpcCli = apiCli
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func (t *AuditSuite) Test_Events_DefaultEvents() {
|
||||
func (s *AuditSuite) Test_Events_DefaultEvents() {
|
||||
response := make([]domain.AuditEvent, 0)
|
||||
err := t.grpcCli.
|
||||
Invoke("admin/log/events").
|
||||
err := s.httpCli.
|
||||
Post("admin/log/events").
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedEventList := map[string]string{
|
||||
entity.EventSuccessLogin: "успешный вход",
|
||||
@@ -102,16 +99,16 @@ func (t *AuditSuite) Test_Events_DefaultEvents() {
|
||||
}
|
||||
for _, event := range response {
|
||||
name, found := expectedEventList[event.Event]
|
||||
t.Require().Equal(found, event.Enabled)
|
||||
t.Require().Equal(name, event.Name)
|
||||
s.Require().Equal(found, event.Enabled)
|
||||
s.Require().Equal(name, event.Name)
|
||||
delete(expectedEventList, event.Event)
|
||||
}
|
||||
t.Require().Empty(expectedEventList)
|
||||
s.Require().Empty(expectedEventList)
|
||||
}
|
||||
|
||||
func (t *AuditSuite) Test_Events_SortEvents() {
|
||||
eventRep := repository.NewAuditEvent(t.db)
|
||||
err := eventRep.Upsert(context.Background(), []entity.AuditEvent{
|
||||
func (s *AuditSuite) Test_Events_SortEvents() {
|
||||
eventRep := repository.NewAuditEvent(s.db)
|
||||
err := eventRep.Upsert(s.T().Context(), []entity.AuditEvent{
|
||||
{Event: "новый#1", Enable: false},
|
||||
{Event: entity.EventSuccessLogin, Enable: false},
|
||||
{Event: entity.EventErrorLogin, Enable: true},
|
||||
@@ -121,33 +118,33 @@ func (t *AuditSuite) Test_Events_SortEvents() {
|
||||
{Event: entity.EventUserBlocked, Enable: true},
|
||||
{Event: "новый#2", Enable: false},
|
||||
})
|
||||
t.Require().NoError(err)
|
||||
s.Require().NoError(err)
|
||||
|
||||
response := make([]domain.AuditEvent, 0)
|
||||
err = t.grpcCli.
|
||||
Invoke("admin/log/events").
|
||||
err = s.httpCli.
|
||||
Post("admin/log/events").
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedSort := []bool{
|
||||
true, true, true, true, false, false, false, false,
|
||||
}
|
||||
t.Require().Equal(len(expectedSort), len(response)) // nolint:testifylint
|
||||
s.Require().Equal(len(expectedSort), len(response)) // nolint:testifylint
|
||||
for i, event := range response {
|
||||
t.Require().Equal(expectedSort[i], event.Enabled)
|
||||
s.Require().Equal(expectedSort[i], event.Enabled)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *AuditSuite) Test_SetEvents_HappyPath() {
|
||||
err := t.grpcCli.
|
||||
Invoke("admin/log/set_events").
|
||||
func (s *AuditSuite) Test_SetEvents_HappyPath() {
|
||||
err := s.httpCli.
|
||||
Post("admin/log/set_events").
|
||||
JsonRequestBody([]domain.SetAuditEvent{
|
||||
{Event: entity.EventUserChanged, Enabled: true},
|
||||
{Event: entity.EventRoleChanged, Enabled: false},
|
||||
}).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedEventList := map[string]bool{
|
||||
entity.EventSuccessLogin: true,
|
||||
@@ -157,38 +154,37 @@ func (t *AuditSuite) Test_SetEvents_HappyPath() {
|
||||
entity.EventUserChanged: true,
|
||||
entity.EventUserBlocked: true,
|
||||
}
|
||||
eventRep := repository.NewAuditEvent(t.db)
|
||||
eventList, err := eventRep.All(context.Background())
|
||||
t.Require().NoError(err)
|
||||
eventRep := repository.NewAuditEvent(s.db)
|
||||
eventList, err := eventRep.All(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
for _, event := range eventList {
|
||||
enable, found := expectedEventList[event.Event]
|
||||
t.Require().True(found)
|
||||
t.Require().Equal(enable, event.Enable)
|
||||
s.Require().True(found)
|
||||
s.Require().Equal(enable, event.Enable)
|
||||
delete(expectedEventList, event.Event)
|
||||
}
|
||||
t.Require().Empty(expectedEventList)
|
||||
s.Require().Empty(expectedEventList)
|
||||
}
|
||||
|
||||
func (t *AuditSuite) Test_SetEvents_InvalidEvent() {
|
||||
err := t.grpcCli.
|
||||
Invoke("admin/log/set_events").
|
||||
func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
|
||||
err := s.httpCli.Post("admin/log/set_events").
|
||||
JsonRequestBody([]domain.SetAuditEvent{
|
||||
{Event: entity.EventUserChanged, Enabled: true},
|
||||
{Event: "новый#2", Enabled: false},
|
||||
}).
|
||||
Do(context.Background())
|
||||
t.Require().Error(err)
|
||||
s, isStatus := status.FromError(err)
|
||||
t.Require().True(isStatus)
|
||||
t.Require().Equal(codes.InvalidArgument, s.Code())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (t *AuditSuite) Test_All_Logs() {
|
||||
func (s *AuditSuite) Test_All_Logs() {
|
||||
request := domain.AuditPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 3,
|
||||
Offset: 5,
|
||||
},
|
||||
Limit: 3,
|
||||
Offset: 5,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
@@ -196,17 +192,17 @@ func (t *AuditSuite) Test_All_Logs() {
|
||||
}
|
||||
|
||||
var response *domain.AuditResponse
|
||||
err := t.grpcCli.
|
||||
Invoke("admin/log/all").
|
||||
err := s.httpCli.
|
||||
Post("admin/log/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
t.Require().Len(response.Items, 3)
|
||||
t.Require().EqualValues(5, response.Items[0].UserId)
|
||||
t.Require().EqualValues(4, response.Items[1].UserId)
|
||||
t.Require().EqualValues(3, response.Items[2].UserId)
|
||||
s.Require().Len(response.Items, 3)
|
||||
s.Require().EqualValues(5, response.Items[0].UserId)
|
||||
s.Require().EqualValues(4, response.Items[1].UserId)
|
||||
s.Require().EqualValues(3, response.Items[2].UserId)
|
||||
|
||||
request.Query = &domain.AuditQuery{
|
||||
Message: new("Выход"),
|
||||
@@ -214,25 +210,25 @@ func (t *AuditSuite) Test_All_Logs() {
|
||||
request.Limit = 10
|
||||
request.Offset = 0
|
||||
|
||||
err = t.grpcCli.
|
||||
Invoke("admin/log/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/log/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
t.Require().Len(response.Items, 6)
|
||||
t.Require().EqualValues(6, response.TotalCount)
|
||||
t.Require().EqualValues(10, response.Items[0].UserId)
|
||||
t.Require().EqualValues(9, response.Items[1].UserId)
|
||||
t.Require().EqualValues(8, response.Items[2].UserId)
|
||||
t.Require().EqualValues(7, response.Items[3].UserId)
|
||||
t.Require().EqualValues(6, response.Items[4].UserId)
|
||||
t.Require().EqualValues(5, response.Items[5].UserId)
|
||||
s.Require().Len(response.Items, 6)
|
||||
s.Require().EqualValues(6, response.TotalCount)
|
||||
s.Require().EqualValues(10, response.Items[0].UserId)
|
||||
s.Require().EqualValues(9, response.Items[1].UserId)
|
||||
s.Require().EqualValues(8, response.Items[2].UserId)
|
||||
s.Require().EqualValues(7, response.Items[3].UserId)
|
||||
s.Require().EqualValues(6, response.Items[4].UserId)
|
||||
s.Require().EqualValues(5, response.Items[5].UserId)
|
||||
}
|
||||
|
||||
func (t *AuditSuite) insertAuditLogs() {
|
||||
t.db.Must().Exec(`INSERT INTO audit (user_id, message, created_at, event)
|
||||
func (s *AuditSuite) insertAuditLogs() {
|
||||
s.db.Must().Exec(`INSERT INTO audit (user_id, message, created_at, event)
|
||||
VALUES (1, 'Успешный вход', NOW(), 'success_login'),
|
||||
(2, 'Успешный вход', NOW(), 'success_login'),
|
||||
(3, 'Неуспешный вход', NOW(), 'unsuccess_login'),
|
||||
|
||||
+113
-79
@@ -1,7 +1,6 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -11,25 +10,23 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/test/fake"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestAuthTestSuite(t *testing.T) {
|
||||
@@ -40,27 +37,35 @@ func TestAuthTestSuite(t *testing.T) {
|
||||
type AuthTestSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
oauthCli *httpcli.Client
|
||||
oauthClientName string
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
s.httpCli = httpcli.New()
|
||||
s.oauthCli = httpcli.New()
|
||||
s.oauthClientName = fake.It[string]()
|
||||
|
||||
mocksrv, host := s.initMockSudir()
|
||||
sudirHost, _ := url.JoinPath(host, "/blitz/")
|
||||
mocksrv, host := s.initMockOauth()
|
||||
oauthHost, _ := url.JoinPath(host, "/blitz/")
|
||||
s.oauthCli.GlobalRequestConfig().BaseUrl = oauthHost
|
||||
|
||||
remote := conf.Remote{
|
||||
SudirAuth: &conf.SudirAuth{
|
||||
ClientId: "admin",
|
||||
ClientSecret: "admin",
|
||||
Host: sudirHost,
|
||||
RedirectURI: "http://localhost",
|
||||
Oauth: &conf.Oauth{
|
||||
Host: host,
|
||||
Clients: []conf.OauthClientConfig{
|
||||
{
|
||||
ClientName: s.oauthClientName,
|
||||
ClientId: "admin",
|
||||
ClientSecret: "admin",
|
||||
RedirectURI: "http://localhost",
|
||||
},
|
||||
},
|
||||
},
|
||||
ExpireSec: 3600,
|
||||
AntiBruteforce: conf.AntiBruteforce{
|
||||
@@ -68,14 +73,16 @@ func (s *AuthTestSuite) SetupTest() {
|
||||
DelayLoginRequestInSec: 1,
|
||||
},
|
||||
}
|
||||
cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
|
||||
Config(context.Background(), remote, time.Minute)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
mocksrv.Close()
|
||||
})
|
||||
}
|
||||
@@ -89,13 +96,13 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
})
|
||||
|
||||
response := domain.LoginResponse{}
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||
@@ -105,16 +112,18 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginNotFound() {
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a1@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
Do(context.Background())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
@@ -128,16 +137,18 @@ func (s *AuthTestSuite) TestBlockedUser() {
|
||||
Blocked: true,
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
Do(context.Background())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
@@ -150,33 +161,36 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "WrongPassword",
|
||||
}).
|
||||
Do(context.Background())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
||||
func (s *AuthTestSuite) TestOauthLoginHappyPath() {
|
||||
response := domain.LoginResponse{}
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_sudir").
|
||||
JsonRequestBody(domain.LoginSudirRequest{
|
||||
AuthCode: "code",
|
||||
err := s.httpCli.Post("admin/auth/login_with_oauth").
|
||||
JsonRequestBody(domain.LoginOauthRequest{
|
||||
AuthCode: "code",
|
||||
ClientName: s.oauthClientName,
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
user := entity.User{}
|
||||
s.db.Must().SelectRow(&user, "select id, email, full_name from users where sudir_user_id = $1", "sudirUser1")
|
||||
s.Require().Equal("sudir@email.ru", user.Email)
|
||||
s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1")
|
||||
s.Require().Equal("oauth@email.ru", user.Email)
|
||||
s.Require().Equal("surname name patronymic", user.FullName)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||
@@ -185,6 +199,24 @@ func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
|
||||
response := domain.LoginResponse{}
|
||||
|
||||
err := s.httpCli.Post("admin/auth/login_with_oauth").
|
||||
JsonRequestBody(domain.LoginOauthRequest{
|
||||
AuthCode: "code",
|
||||
ClientName: s.oauthClientName + fake.It[string](),
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
userId := InsertUser(s.db, entity.User{Email: "suslik@mail.ru"})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
@@ -194,9 +226,9 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
CreatedAt: time.Time{},
|
||||
ExpiredAt: time.Time{},
|
||||
})
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
Do(context.Background())
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
|
||||
@@ -206,18 +238,16 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_NotFound() {
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, "0143218411981").
|
||||
Do(context.Background())
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, "0143218411981").
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
time.Sleep(time.Second)
|
||||
audit := repository.NewAudit(s.db)
|
||||
auditList, err := audit.AllByRequest(context.Background(), domain.AuditPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "created_at",
|
||||
Type: "desc",
|
||||
@@ -239,9 +269,9 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
||||
CreatedAt: time.Time{},
|
||||
ExpiredAt: time.Time{},
|
||||
})
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
Do(context.Background())
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
|
||||
@@ -260,25 +290,29 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
||||
|
||||
tooManyRequestsErrorCount := &atomic.Int32{}
|
||||
unauthorizedErrorCount := &atomic.Int32{}
|
||||
group, ctx := errgroup.WithContext(context.Background())
|
||||
group, ctx := errgroup.WithContext(s.T().Context())
|
||||
for index := range 100 {
|
||||
group.Go(func() error {
|
||||
start := time.Now()
|
||||
response := domain.LoginResponse{}
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(ctx)
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
s.Require().Error(err)
|
||||
|
||||
switch status.Code(err) { // nolint:exhaustive
|
||||
case codes.ResourceExhausted:
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
|
||||
switch httpErr.StatusCode { // nolint:exhaustive
|
||||
case http.StatusTooManyRequests:
|
||||
tooManyRequestsErrorCount.Add(1)
|
||||
s.Require().True(time.Since(start) < time.Second)
|
||||
case codes.Unauthenticated:
|
||||
case http.StatusUnauthorized:
|
||||
unauthorizedErrorCount.Add(1)
|
||||
s.Require().True(time.Since(start) > time.Second)
|
||||
default:
|
||||
@@ -298,11 +332,11 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
||||
time.Sleep(2 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
||||
func (s *AuthTestSuite) initMockOauth() (*httptest.Server, string) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/blitz/oauth/te", func(writer http.ResponseWriter, request *http.Request) {
|
||||
res := entity.SudirTokenResponse{
|
||||
SudirAuthError: nil,
|
||||
res := entity.OauthTokenResponse{
|
||||
OauthAuthError: nil,
|
||||
IdToken: "1",
|
||||
AccessToken: "token",
|
||||
}
|
||||
@@ -312,11 +346,11 @@ func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
||||
s.NoError(err)
|
||||
})
|
||||
mux.HandleFunc("/blitz/oauth/me", func(writer http.ResponseWriter, request *http.Request) {
|
||||
res := entity.SudirUserResponse{
|
||||
SudirAuthError: nil,
|
||||
Email: "sudir@email.ru",
|
||||
res := entity.OauthUserResponse{
|
||||
OauthAuthError: nil,
|
||||
Email: "oauth@email.ru",
|
||||
Groups: []string{"DIT-KKD-Admins"},
|
||||
Sub: "sudirUser1",
|
||||
Sub: "oauthUser1",
|
||||
GivenName: "name",
|
||||
FamilyName: "surname",
|
||||
Name: "surname name patronymic",
|
||||
|
||||
+15
-14
@@ -1,18 +1,18 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestCustomizationTestSuite(t *testing.T) {
|
||||
@@ -25,7 +25,7 @@ type CustomizationTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (s *CustomizationTestSuite) SetupTest() {
|
||||
@@ -40,24 +40,25 @@ func (s *CustomizationTestSuite) SetupTest() {
|
||||
},
|
||||
ExpireSec: 0,
|
||||
}
|
||||
cfg := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
||||
Config(context.Background(), remote, time.Minute)
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *CustomizationTestSuite) TestGetDesign() {
|
||||
response := conf.UIDesign{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/get_design").
|
||||
err := s.httpCli.
|
||||
Post("admin/user/get_design").
|
||||
JsonRequestBody(struct{}{}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := conf.UIDesign{
|
||||
Name: "test",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -21,15 +21,15 @@ func InsertUser(db *dbt.TestDb, user entity.User) int64 {
|
||||
return id
|
||||
}
|
||||
|
||||
func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) int64 {
|
||||
func InsertOauthUser(db *dbt.TestDb, user entity.OauthUser) int64 {
|
||||
q, args, err := query.New().
|
||||
Insert("users").
|
||||
Columns("sudir_user_id", "first_name", "last_name", "full_name", "email").
|
||||
Values(user.SudirUserId, user.FirstName, user.LastName, user.FullName, user.Email).
|
||||
Columns("oauth_user_id", "first_name", "last_name", "full_name", "email").
|
||||
Values(user.OauthUserId, user.FirstName, user.LastName, user.FullName, user.Email).
|
||||
Suffix("RETURNING id").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
panic(errors.WithMessagef(err, "insert sudir user"))
|
||||
panic(errors.WithMessagef(err, "insert oauth user"))
|
||||
}
|
||||
var id int64
|
||||
db.Must().SelectRow(&id, q, args...)
|
||||
@@ -42,9 +42,13 @@ func InsertRole(db *dbt.TestDb, role entity.Role) int64 {
|
||||
}
|
||||
q, args, err := query.New().
|
||||
Insert("roles").
|
||||
Columns("name", "permissions").
|
||||
Values(role.Name, role.Permissions).
|
||||
Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, permissions = EXCLUDED.permissions RETURNING id").
|
||||
Columns("name", "permissions", "application_group").
|
||||
Values(role.Name, role.Permissions, role.ApplicationGroup).
|
||||
Suffix(`ON CONFLICT (name) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
permissions = EXCLUDED.permissions,
|
||||
application_group = EXCLUDED.application_group
|
||||
RETURNING id`).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
panic(errors.WithMessagef(err, "insert role"))
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
// nolint: funlen
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestDownloadSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, &DownloadSuite{})
|
||||
}
|
||||
|
||||
type DownloadSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
permissions entity.PermList
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
|
||||
remote := conf.Remote{
|
||||
Permissions: []conf.Permission{
|
||||
{
|
||||
Key: "data_download",
|
||||
Name: "123",
|
||||
},
|
||||
},
|
||||
}
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
s.permissions = entity.PermList{
|
||||
"data_download",
|
||||
}
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestUsersHappyPath() {
|
||||
id1 := InsertUser(s.db, entity.User{
|
||||
FirstName: "Alice",
|
||||
LastName: "Bob",
|
||||
FullName: "Bob Alice",
|
||||
Email: "alice@a.ru",
|
||||
Password: "password",
|
||||
})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)})
|
||||
|
||||
resp, err := s.httpCli.Post("user/download").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
defer resp.Raw.Body.Close()
|
||||
s.Require().Equal(http.StatusOK, resp.StatusCode())
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
idIdx, ok := col["id"]
|
||||
s.Require().True(ok)
|
||||
emailIdx, ok := col["Email"]
|
||||
s.Require().True(ok)
|
||||
fullNameIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 4)
|
||||
|
||||
row := records[1]
|
||||
s.Require().EqualValues("3", row[idIdx])
|
||||
s.Require().EqualValues("alice@a.ru", row[emailIdx])
|
||||
s.Require().EqualValues("Bob Alice", row[fullNameIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestSessionsHappyPath() {
|
||||
timeNow := time.Now().UTC()
|
||||
userId := InsertUser(s.db, entity.User{Email: "sess1@a.ru", FullName: "Bob Alice"})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)})
|
||||
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_1",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
ExpiredAt: timeNow.Add(1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-1 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_2",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusRevoked,
|
||||
ExpiredAt: timeNow.Add(1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-2 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_3",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusExpired,
|
||||
ExpiredAt: timeNow.Add(-1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-3 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
|
||||
resp, err := s.httpCli.Post("/session/download").
|
||||
JsonRequestBody(domain.SessionPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
defer resp.Raw.Body.Close()
|
||||
s.Require().Equal(http.StatusOK, resp.StatusCode())
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
userIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
idIdx, ok := col["Идентификатор"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 4)
|
||||
row := records[1]
|
||||
s.Require().EqualValues("Bob Alice", row[userIdx])
|
||||
s.Require().EqualValues("1", row[idIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestAuditHappyPath() {
|
||||
timeNow := time.Now().UTC()
|
||||
userId := InsertUser(s.db, entity.User{Email: "audit1@a.ru", FullName: "Bob Alice"})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)})
|
||||
|
||||
auditRepo := repository.NewAudit(s.db)
|
||||
_, err := auditRepo.Insert(s.T().Context(), entity.Audit{
|
||||
Id: 1,
|
||||
UserId: int(userId),
|
||||
Message: "audit1@a.ru",
|
||||
Event: "123456",
|
||||
CreatedAt: timeNow,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
resp, err := s.httpCli.Post("log/download").
|
||||
JsonRequestBody(domain.AuditPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
StatusCodeToError().
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
idIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
moveIdx, ok := col["Действие"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 2)
|
||||
row := records[1]
|
||||
s.Require().EqualValues("Bob Alice", row[idIdx])
|
||||
s.Require().EqualValues("audit1@a.ru", row[moveIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestRolesHappyPath() {
|
||||
InsertRole(s.db, entity.Role{
|
||||
Name: "admin_1",
|
||||
ApplicationGroup: "123",
|
||||
Permissions: s.permissions,
|
||||
})
|
||||
InsertRole(s.db, entity.Role{
|
||||
Name: "admin_2",
|
||||
ApplicationGroup: "456",
|
||||
Permissions: s.permissions,
|
||||
})
|
||||
|
||||
applicationGroup := "123"
|
||||
resp, err := s.httpCli.Post("role/download").
|
||||
JsonRequestBody(domain.RoleAllRequest{
|
||||
ApplicationGroup: &applicationGroup,
|
||||
}).
|
||||
StatusCodeToError().
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
moveIdx, ok := col["Действие"]
|
||||
s.Require().True(ok)
|
||||
keyIdx, ok := col["Ключ в системе"]
|
||||
s.Require().True(ok)
|
||||
nameIdx, ok := col["admin_1"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 2)
|
||||
row := records[1]
|
||||
s.Require().EqualValues("123", row[moveIdx])
|
||||
s.Require().EqualValues("data_download", row[keyIdx])
|
||||
s.Require().EqualValues("+", row[nameIdx])
|
||||
}
|
||||
+11
-12
@@ -4,13 +4,13 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/service/inactive_worker"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
@@ -27,16 +27,17 @@ func TestInactiveWorker(t *testing.T) {
|
||||
userId := InsertUser(db, entity.User{Email: "a@test", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)})
|
||||
InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()})
|
||||
|
||||
config := assembly.NewLocator(test.Logger(), nil, db).
|
||||
config, err := assembly.NewLocator(test.Logger(), nil, db).
|
||||
Config(t.Context(), conf.Remote{
|
||||
BlockInactiveWorker: conf.BlockInactiveWorker{
|
||||
DaysThreshold: 1,
|
||||
RunIntervalInMinutes: 1,
|
||||
},
|
||||
}, 500*time.Millisecond)
|
||||
require.NoError(err)
|
||||
|
||||
bgjobCli := bgjobx.NewClient(db, test.Logger())
|
||||
err := inactive_worker.EnqueueSeedJob(t.Context(), bgjobCli)
|
||||
err = inactive_worker.EnqueueSeedJob(t.Context(), bgjobCli)
|
||||
require.NoError(err)
|
||||
err = bgjobCli.Upgrade(t.Context(), config.BgJobCfg)
|
||||
require.NoError(err)
|
||||
@@ -48,10 +49,8 @@ func TestInactiveWorker(t *testing.T) {
|
||||
require.True(user.Blocked)
|
||||
|
||||
list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "created_at",
|
||||
Type: "desc",
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestRoleTestSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, &RoleTestSuite{})
|
||||
}
|
||||
|
||||
type RoleTestSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
adminId int64
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
|
||||
remote := conf.Remote{
|
||||
ExpireSec: 0,
|
||||
}
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
|
||||
s.httpCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
roleId := InsertRole(s.db, entity.Role{
|
||||
Name: "admin_test",
|
||||
Permissions: []string{
|
||||
"role_view",
|
||||
"role_add",
|
||||
"role_update",
|
||||
},
|
||||
})
|
||||
s.adminId = InsertUser(s.db, entity.User{
|
||||
Email: "admin@test.ru",
|
||||
})
|
||||
InsertUserRole(s.db, entity.UserRole{
|
||||
UserId: int(s.adminId),
|
||||
RoleId: int(roleId),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesWithoutFilter() {
|
||||
InsertRole(s.db, entity.Role{Name: "empty"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupA_1", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupA_2", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
||||
|
||||
roles := []domain.Role{}
|
||||
_, err := s.request("admin/role/all", domain.RoleAllRequest{}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
groups := make(map[string]string, len(roles))
|
||||
for _, role := range roles {
|
||||
groups[role.Name] = role.ApplicationGroup
|
||||
}
|
||||
|
||||
s.Require().Empty(groups["empty"])
|
||||
s.Require().Equal("groupA", groups["groupA_1"])
|
||||
s.Require().Equal("groupA", groups["groupA_2"])
|
||||
s.Require().Equal("groupB", groups["groupB"])
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesInvalidArgument() {
|
||||
roles := []domain.Role{}
|
||||
statusCode, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles)
|
||||
|
||||
s.Require().Error(err)
|
||||
s.Require().Equal(http.StatusBadRequest, statusCode)
|
||||
s.Require().Empty(roles)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesFilterByApplicationGroup() {
|
||||
InsertRole(s.db, entity.Role{Name: "groupA", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
||||
|
||||
roles := []domain.Role{}
|
||||
_, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(roles, 1)
|
||||
s.Require().Equal("groupA", roles[0].ApplicationGroup)
|
||||
|
||||
roles = []domain.Role{}
|
||||
_, err = s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Empty(roles)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestCreateRoleApplicationGroup() {
|
||||
role := domain.Role{}
|
||||
_, err := s.request("admin/role/create", domain.CreateRoleRequest{
|
||||
Name: "role_new",
|
||||
ApplicationGroup: "group",
|
||||
Permissions: []string{},
|
||||
}, &role)
|
||||
s.Require().NoError(err)
|
||||
|
||||
roleEmpty := domain.Role{}
|
||||
_, err = s.request("admin/role/create", domain.CreateRoleRequest{
|
||||
Name: "role_empty",
|
||||
Permissions: []string{},
|
||||
}, &roleEmpty)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal("role_new", role.Name)
|
||||
s.Require().Equal("group", role.ApplicationGroup)
|
||||
s.Require().Equal("role_empty", roleEmpty.Name)
|
||||
s.Require().Empty(roleEmpty.ApplicationGroup)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestUpdateRoleApplicationGroup() {
|
||||
roleId := InsertRole(s.db, entity.Role{
|
||||
Name: "role_old",
|
||||
ApplicationGroup: "group_old",
|
||||
})
|
||||
|
||||
role := domain.Role{}
|
||||
_, err := s.request("admin/role/update", domain.UpdateRoleRequest{
|
||||
Id: int(roleId),
|
||||
Name: "role_new",
|
||||
ApplicationGroup: "group_new",
|
||||
Permissions: []string{},
|
||||
}, &role)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Equal("role_new", role.Name)
|
||||
s.Require().Equal("group_new", role.ApplicationGroup)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) request(path string, req, resp any) (int, error) {
|
||||
err := s.httpCli.Post(path).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(resp).
|
||||
StatusCodeToError().
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, errors.WithMessagef(err, "request %s", path)
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
+27
-27
@@ -1,22 +1,21 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestSecureSuite(t *testing.T) {
|
||||
@@ -30,7 +29,7 @@ type SecureSuite struct {
|
||||
test *test.Test
|
||||
require *require.Assertions
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (s *SecureSuite) SetupTest() {
|
||||
@@ -40,14 +39,15 @@ func (s *SecureSuite) SetupTest() {
|
||||
remote := conf.Remote{
|
||||
ExpireSec: 3600,
|
||||
}
|
||||
cfg := assembly.NewLocator(s.test.Logger(), httpCli, s.db).
|
||||
Config(context.Background(), remote, time.Minute)
|
||||
cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(s.test, cfg.Handler)
|
||||
server, apiCli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.test.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
s.grpcCli = apiCli
|
||||
s.httpCli = apiCli
|
||||
}
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||
@@ -60,12 +60,12 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "happy_path",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: true,
|
||||
@@ -84,12 +84,12 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "revoked",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -108,12 +108,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "expired",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -124,12 +124,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_NotFound() {
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "not_found",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -164,35 +164,35 @@ func (s *SecureSuite) Test_Authorize_HappyPath() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthzResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authorize").
|
||||
err := s.httpCli.Post("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm1",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.True(result.Authorized)
|
||||
|
||||
result = domain.SecureAuthzResponse{}
|
||||
err = s.grpcCli.Invoke("admin/secure/authorize").
|
||||
err = s.httpCli.Post("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm2",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.True(result.Authorized)
|
||||
|
||||
result = domain.SecureAuthzResponse{}
|
||||
err = s.grpcCli.Invoke("admin/secure/authorize").
|
||||
err = s.httpCli.Post("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm3",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.False(result.Authorized)
|
||||
}
|
||||
+87
-90
@@ -1,25 +1,23 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/service/session_worker"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/service/session_worker"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestSessionSuite(t *testing.T) {
|
||||
@@ -33,13 +31,13 @@ type SessionSuite struct {
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
config assembly.Config
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (t *SessionSuite) SetupTest() {
|
||||
testInstance, _ := test.New(t.T())
|
||||
t.test = testInstance
|
||||
t.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
func (s *SessionSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
|
||||
remote := conf.Remote{
|
||||
Audit: conf.Audit{
|
||||
@@ -72,23 +70,26 @@ func (t *SessionSuite) SetupTest() {
|
||||
AuditTTl: conf.AuditTTlSetting{},
|
||||
},
|
||||
}
|
||||
t.config = assembly.NewLocator(testInstance.Logger(), httpcli.New(), t.db).
|
||||
Config(context.Background(), remote, 500*time.Millisecond)
|
||||
config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
|
||||
Config(s.T().Context(), remote, 500*time.Millisecond)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, t.config.Handler)
|
||||
t.grpcCli = apiCli
|
||||
s.config = config
|
||||
|
||||
server, cli := httpt.TestServer(s.test, config.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:funlen
|
||||
func (t *SessionSuite) Test_All_Session() {
|
||||
userId := InsertUser(t.db, entity.User{Email: "test_1@aa.ru"})
|
||||
func (s *SessionSuite) Test_All_Session() {
|
||||
userId := InsertUser(s.db, entity.User{Email: "test_1@aa.ru"})
|
||||
timeNow := time.Now().UTC()
|
||||
|
||||
InsertTokenEntity(t.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_1",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
@@ -96,7 +97,7 @@ func (t *SessionSuite) Test_All_Session() {
|
||||
CreatedAt: timeNow.Add(-1 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
InsertTokenEntity(t.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_2",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusRevoked,
|
||||
@@ -104,7 +105,7 @@ func (t *SessionSuite) Test_All_Session() {
|
||||
CreatedAt: timeNow.Add(-2 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
InsertTokenEntity(t.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_3",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusExpired,
|
||||
@@ -115,24 +116,22 @@ func (t *SessionSuite) Test_All_Session() {
|
||||
|
||||
// Дефолт сортировка, лимит и оффсет
|
||||
request := domain.SessionPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
},
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
}
|
||||
|
||||
var response *domain.SessionResponse
|
||||
err := t.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err := s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
t.Require().Len(response.Items, 2)
|
||||
t.Require().EqualValues(3, response.TotalCount)
|
||||
t.Require().EqualValues(2, response.Items[0].Id)
|
||||
t.Require().EqualValues(3, response.Items[1].Id)
|
||||
s.Require().Len(response.Items, 2)
|
||||
s.Require().EqualValues(3, response.TotalCount)
|
||||
s.Require().EqualValues(2, response.Items[0].Id)
|
||||
s.Require().EqualValues(3, response.Items[1].Id)
|
||||
|
||||
// Дефолт сортировка, поиск по expired_at
|
||||
request.Offset = 0
|
||||
@@ -142,17 +141,17 @@ func (t *SessionSuite) Test_All_Session() {
|
||||
To: timeNow.Add(24 * time.Hour),
|
||||
},
|
||||
}
|
||||
err = t.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
t.Require().Len(response.Items, 2)
|
||||
t.Require().EqualValues(2, response.TotalCount)
|
||||
t.Require().EqualValues(1, response.Items[0].Id)
|
||||
t.Require().EqualValues(2, response.Items[1].Id)
|
||||
s.Require().Len(response.Items, 2)
|
||||
s.Require().EqualValues(2, response.TotalCount)
|
||||
s.Require().EqualValues(1, response.Items[0].Id)
|
||||
s.Require().EqualValues(2, response.Items[1].Id)
|
||||
|
||||
// Сортировка по статусу, пустой запрос
|
||||
request.Query = nil
|
||||
@@ -161,18 +160,18 @@ func (t *SessionSuite) Test_All_Session() {
|
||||
Type: "asc",
|
||||
}
|
||||
|
||||
err = t.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
t.Require().Len(response.Items, 3)
|
||||
t.Require().EqualValues(3, response.TotalCount)
|
||||
t.Require().EqualValues(1, response.Items[0].Id)
|
||||
t.Require().EqualValues(3, response.Items[1].Id)
|
||||
t.Require().EqualValues(2, response.Items[2].Id)
|
||||
s.Require().Len(response.Items, 3)
|
||||
s.Require().EqualValues(3, response.TotalCount)
|
||||
s.Require().EqualValues(1, response.Items[0].Id)
|
||||
s.Require().EqualValues(3, response.Items[1].Id)
|
||||
s.Require().EqualValues(2, response.Items[2].Id)
|
||||
|
||||
// Сортировка по статусу, поиск по userId & status
|
||||
resUserId := int(userId)
|
||||
@@ -181,21 +180,21 @@ func (t *SessionSuite) Test_All_Session() {
|
||||
Status: []string{entity.TokenStatusExpired},
|
||||
}
|
||||
|
||||
err = t.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
t.Require().Len(response.Items, 1)
|
||||
t.Require().EqualValues(1, response.TotalCount)
|
||||
t.Require().EqualValues(3, response.Items[0].Id)
|
||||
s.Require().Len(response.Items, 1)
|
||||
s.Require().EqualValues(1, response.TotalCount)
|
||||
s.Require().EqualValues(3, response.Items[0].Id)
|
||||
|
||||
// Сортировка по id, поиск по id
|
||||
for i := range 20 {
|
||||
userId = InsertUser(t.db, entity.User{Email: "test_11" + strconv.Itoa(i) + "@aa.ru"})
|
||||
InsertTokenEntity(t.db, entity.Token{
|
||||
userId = InsertUser(s.db, entity.User{Email: "test_11" + strconv.Itoa(i) + "@aa.ru"})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_1" + strconv.Itoa(i),
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
@@ -206,10 +205,8 @@ func (t *SessionSuite) Test_All_Session() {
|
||||
}
|
||||
|
||||
request = domain.SessionPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "desc",
|
||||
@@ -218,57 +215,57 @@ func (t *SessionSuite) Test_All_Session() {
|
||||
Id: new(2),
|
||||
},
|
||||
}
|
||||
err = t.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
t.Require().NoError(err)
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
t.Require().Len(response.Items, 5)
|
||||
t.Require().EqualValues(6, response.TotalCount)
|
||||
t.Require().EqualValues(23, response.Items[0].Id)
|
||||
t.Require().EqualValues(22, response.Items[1].Id)
|
||||
t.Require().EqualValues(21, response.Items[2].Id)
|
||||
t.Require().EqualValues(20, response.Items[3].Id)
|
||||
t.Require().EqualValues(12, response.Items[4].Id)
|
||||
s.Require().Len(response.Items, 5)
|
||||
s.Require().EqualValues(6, response.TotalCount)
|
||||
s.Require().EqualValues(23, response.Items[0].Id)
|
||||
s.Require().EqualValues(22, response.Items[1].Id)
|
||||
s.Require().EqualValues(21, response.Items[2].Id)
|
||||
s.Require().EqualValues(20, response.Items[3].Id)
|
||||
s.Require().EqualValues(12, response.Items[4].Id)
|
||||
}
|
||||
|
||||
func (t *SessionSuite) Test_Session_Expired_Worker() {
|
||||
userId := InsertUser(t.db, entity.User{Email: "a@test"})
|
||||
func (s *SessionSuite) Test_Session_Expired_Worker() {
|
||||
userId := InsertUser(s.db, entity.User{Email: "a@test"})
|
||||
|
||||
InsertTokenEntity(t.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "token_allowed",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
ExpiredAt: time.Now().UTC().Add(24 * time.Hour)})
|
||||
|
||||
InsertTokenEntity(t.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "token_expired",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
ExpiredAt: time.Now().UTC().Add(-2 * time.Hour)})
|
||||
|
||||
InsertTokenEntity(t.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "token_expired2",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
ExpiredAt: time.Now().UTC().Add(-24 * time.Hour)})
|
||||
|
||||
bgjobCli := bgjobx.NewClient(t.db, t.test.Logger())
|
||||
bgjobCli := bgjobx.NewClient(s.db, s.test.Logger())
|
||||
|
||||
err := session_worker.EnqueueSeedJob(t.T().Context(), bgjobCli)
|
||||
t.Require().NoError(err)
|
||||
err := session_worker.EnqueueSeedJob(s.T().Context(), bgjobCli)
|
||||
s.Require().NoError(err)
|
||||
|
||||
err = bgjobCli.Upgrade(t.T().Context(), t.config.BgJobCfg)
|
||||
t.Require().NoError(err)
|
||||
err = bgjobCli.Upgrade(s.T().Context(), s.config.BgJobCfg)
|
||||
s.Require().NoError(err)
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
tokens := make([]entity.Token, 0)
|
||||
t.db.Must().Select(&tokens, "SELECT * FROM tokens ORDER BY status ASC")
|
||||
s.db.Must().Select(&tokens, "SELECT * FROM tokens ORDER BY status ASC")
|
||||
|
||||
t.Require().EqualValues(entity.TokenStatusAllowed, tokens[0].Status)
|
||||
t.Require().EqualValues(entity.TokenStatusExpired, tokens[1].Status)
|
||||
t.Require().EqualValues(entity.TokenStatusExpired, tokens[2].Status)
|
||||
s.Require().EqualValues(entity.TokenStatusAllowed, tokens[0].Status)
|
||||
s.Require().EqualValues(entity.TokenStatusExpired, tokens[1].Status)
|
||||
s.Require().EqualValues(entity.TokenStatusExpired, tokens[2].Status)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/fake"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
type UiSettingsSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
apiCli *httpcli.Client
|
||||
oauthClientSetting conf.OauthClientConfig
|
||||
baseOauthUrl string
|
||||
}
|
||||
|
||||
func TestUiSettingsSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, &UiSettingsSuite{
|
||||
baseOauthUrl: "http://127.0.0.1/oauth",
|
||||
oauthClientSetting: conf.OauthClientConfig{
|
||||
ClientName: fake.It[string](),
|
||||
ClientId: fake.It[string](),
|
||||
ClientSecret: fake.It[string](),
|
||||
RedirectURI: "https://127.0.0.1/test/redirected",
|
||||
UiSetting: &conf.UiOauthSetting{
|
||||
LoginEndpoint: "/login?someQueryParam=1&test=true",
|
||||
LogoutEndpoint: "/logout?redirect=url",
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) SetupTest() {
|
||||
s.test, _ = test.New(s.T())
|
||||
remote := conf.Remote{
|
||||
Oauth: &conf.Oauth{
|
||||
Host: s.baseOauthUrl,
|
||||
Clients: []conf.OauthClientConfig{s.oauthClientSetting},
|
||||
},
|
||||
}
|
||||
cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil).
|
||||
Config(s.T().Context(), remote, 0)
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, s.apiCli = httpt.TestServer(s.test, cfg.Handler)
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) Test_HappyPath() {
|
||||
var resp domain.UiOauthSetting
|
||||
|
||||
err := s.apiCli.Post("admin/ui_settings/oauth").
|
||||
JsonRequestBody(domain.ClientNameRequest{
|
||||
ClientName: s.oauthClientSetting.ClientName,
|
||||
}).
|
||||
JsonResponseBody(&resp).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
loginURL, err := url.Parse(resp.LoginUrl)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(
|
||||
"http://127.0.0.1/oauth/login",
|
||||
loginURL.Scheme+"://"+loginURL.Host+loginURL.Path,
|
||||
)
|
||||
|
||||
query := loginURL.Query()
|
||||
s.Require().Equal(s.oauthClientSetting.ClientId, query.Get("client_id"))
|
||||
s.Require().Equal(s.oauthClientSetting.RedirectURI, query.Get("redirect_uri"))
|
||||
s.Require().Equal("1", query.Get("someQueryParam"))
|
||||
s.Require().Equal("true", query.Get("test"))
|
||||
|
||||
logoutURL, err := url.Parse(resp.LogoutUrl)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(
|
||||
"http://127.0.0.1/oauth/logout",
|
||||
logoutURL.Scheme+"://"+logoutURL.Host+logoutURL.Path,
|
||||
)
|
||||
s.Require().Equal("url", logoutURL.Query().Get("redirect"))
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) Test_UnknownClient() {
|
||||
err := s.apiCli.Post("admin/ui_settings/oauth").
|
||||
JsonRequestBody(domain.ClientNameRequest{
|
||||
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
|
||||
}).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
}
|
||||
+132
-123
@@ -2,30 +2,28 @@ package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
"isp-admin-service/service"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
type tokenService interface {
|
||||
@@ -42,7 +40,7 @@ type UserTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
apiCli *httpcli.Client
|
||||
httpCli *httpcli.Client
|
||||
tokenService tokenService
|
||||
}
|
||||
@@ -56,14 +54,15 @@ func (s *UserTestSuite) SetupTest() {
|
||||
remote := conf.Remote{
|
||||
ExpireSec: 0,
|
||||
}
|
||||
cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
|
||||
Config(context.Background(), remote, time.Minute)
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
|
||||
s.apiCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
|
||||
tokenRep := repository.NewToken(s.db)
|
||||
@@ -89,10 +88,10 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
|
||||
})
|
||||
|
||||
response := domain.AdminUserShort{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_profile").
|
||||
err := s.apiCli.Post("admin/user/get_profile").
|
||||
JsonResponseBody(&response).
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
Do(context.Background())
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.AdminUserShort{
|
||||
FirstName: "name",
|
||||
@@ -116,18 +115,19 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/user/get_profile").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
||||
Do(context.Background())
|
||||
err := s.apiCli.Post("admin/user/get_profile").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.NotFound, st.Code())
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusNotFound, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileSudir() {
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{
|
||||
SudirUserId: "sudirUser1",
|
||||
func (s *UserTestSuite) TestGetProfileOauth() {
|
||||
id := InsertOauthUser(s.db, entity.OauthUser{
|
||||
OauthUserId: "oauthUser1",
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
FullName: "surname name",
|
||||
@@ -144,11 +144,11 @@ func (s *UserTestSuite) TestGetProfileSudir() {
|
||||
})
|
||||
|
||||
response := domain.AdminUserShort{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/get_profile").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/get_profile").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.AdminUserShort{
|
||||
FirstName: "name",
|
||||
@@ -183,12 +183,10 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
email := "a1@"
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
err := s.apiCli.Post("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
},
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "email",
|
||||
Type: "asc",
|
||||
@@ -199,7 +197,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
roles := []int{int(roleId1), int(roleId2)}
|
||||
@@ -211,12 +209,10 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
s.Require().EqualValues(roles, response.Items[1].Roles)
|
||||
|
||||
email = "test@mail.ru"
|
||||
err = s.grpcCli.Invoke("admin/user/get_users").
|
||||
err = s.apiCli.Post("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "asc",
|
||||
@@ -227,7 +223,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
s.Require().Empty(response.Items)
|
||||
}
|
||||
@@ -250,7 +246,10 @@ func (s *UserTestSuite) TestAllGetUsers() {
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(context.Background())
|
||||
err := s.apiCli.Post("admin/user/get_all_users").
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 7)
|
||||
@@ -295,12 +294,10 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
||||
})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err = s.grpcCli.Invoke("admin/user/get_users").
|
||||
err = s.apiCli.Post("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "lastSessionCreatedAt",
|
||||
Type: "desc",
|
||||
@@ -313,7 +310,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 2)
|
||||
@@ -331,12 +328,10 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
|
||||
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
err := s.apiCli.Post("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "userId",
|
||||
Type: "asc",
|
||||
@@ -346,7 +341,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 4)
|
||||
@@ -363,9 +358,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
|
||||
response := entity.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -373,7 +368,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
postCount := 0
|
||||
@@ -383,17 +378,17 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserWithSameEmailSudirHappyPath() {
|
||||
firstSudirId := "user_a"
|
||||
admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a2@a.ru"})
|
||||
func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||
firstOauthId := "user_a"
|
||||
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a2@a.ru"})
|
||||
|
||||
preCount := 0
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
|
||||
response := entity.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -401,7 +396,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailSudirHappyPath() {
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
postCount := 0
|
||||
@@ -414,20 +409,22 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailSudirHappyPath() {
|
||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
||||
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "exists@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
Do(context.Background())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
@@ -439,12 +436,11 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
Email: "update@a.ru",
|
||||
}
|
||||
response := domain.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.UpdateUserRequest{
|
||||
Id: response.Id,
|
||||
@@ -457,21 +453,20 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: "123", Email: "sudir@a.ru", FullName: "surname name patronymic"})
|
||||
func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
|
||||
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: "123", Email: "oauth@a.ru", FullName: "surname name patronymic"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
FirstName: "nameUpd",
|
||||
LastName: "surnameUpd",
|
||||
Email: "sudir@a.ru",
|
||||
Email: "oauth@a.ru",
|
||||
}
|
||||
response := domain.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.UpdateUserRequest{
|
||||
Id: response.Id,
|
||||
@@ -494,38 +489,40 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
LastName: "surname",
|
||||
Email: "a_exists@a.ru",
|
||||
}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(req).
|
||||
Do(context.Background())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserWithSudirAlreadyExist() {
|
||||
firstSudirId := "user_a"
|
||||
secondSudirId := "user_b"
|
||||
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
||||
firstOauthId := "user_a"
|
||||
secondOauthId := "user_b"
|
||||
|
||||
admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a_exists@a.ru"})
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: secondSudirId, Email: "b_exists@b.ru"})
|
||||
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a_exists@a.ru"})
|
||||
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: secondOauthId, Email: "b_exists@b.ru"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a_exists@a.ru",
|
||||
}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(req).
|
||||
Do(context.Background())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestDeleteUsers() {
|
||||
@@ -535,12 +532,12 @@ func (s *UserTestSuite) TestDeleteUsers() {
|
||||
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
||||
|
||||
response := domain.DeleteResponse{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/delete_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/delete_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(2, response.Deleted)
|
||||
@@ -566,17 +563,18 @@ func (s *UserTestSuite) TestBlockUser() {
|
||||
UpdatedAt: time.Now(),
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/user/block_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.apiCli.Post("admin/user/block_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
StatusCodeToError().
|
||||
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
|
||||
Do(context.Background())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
user, err := repository.NewUser(s.db).GetUserById(context.Background(), id)
|
||||
user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id)
|
||||
s.Require().NoError(err)
|
||||
s.Require().True(user.Blocked)
|
||||
|
||||
t, err := repository.NewToken(s.db).Get(context.Background(), token)
|
||||
t, err := repository.NewToken(s.db).Get(s.T().Context(), token)
|
||||
s.Require().NoError(err)
|
||||
s.EqualValues(entity.TokenStatusRevoked, t.Status)
|
||||
|
||||
@@ -597,20 +595,31 @@ func (s *UserTestSuite) TestChangePasswordUser() {
|
||||
|
||||
// check for err when invalid data
|
||||
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
|
||||
err := s.grpcCli.Invoke("admin/user/change_password").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
err := s.apiCli.Post("admin/user/change_password").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
JsonRequestBody(invalidReq).
|
||||
Do(context.Background())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
err = apierrors.FromError(err)
|
||||
s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword))
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
||||
|
||||
var body struct {
|
||||
ErrorCode int `json:"errorCode"`
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
}
|
||||
s.Require().NoError(json.Unmarshal(httpErr.Body, &body))
|
||||
s.Require().Equal(domain.ErrCodeInvalidPassword, body.ErrorCode)
|
||||
|
||||
// change password
|
||||
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
|
||||
err = s.grpcCli.Invoke("admin/user/change_password").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
err = s.apiCli.Post("admin/user/change_password").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
JsonRequestBody(changePswReq).
|
||||
Do(context.Background())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
|
||||
s.Require().NoError(err)
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ package transaction
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/service/session_worker"
|
||||
"isp-admin-service/repository"
|
||||
"isp-admin-service/service"
|
||||
"isp-admin-service/service/session_worker"
|
||||
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
squirrel.test
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.11.x
|
||||
- 1.12.x
|
||||
- 1.13.x
|
||||
|
||||
services:
|
||||
- mysql
|
||||
- postgresql
|
||||
|
||||
# Setting sudo access to false will let Travis CI use containers rather than
|
||||
# VMs to run the tests. For more details see:
|
||||
# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/
|
||||
# - http://docs.travis-ci.com/user/workers/standard-infrastructure/
|
||||
sudo: false
|
||||
|
||||
before_script:
|
||||
- mysql -e 'CREATE DATABASE squirrel;'
|
||||
- psql -c 'CREATE DATABASE squirrel;' -U postgres
|
||||
|
||||
script:
|
||||
- go test
|
||||
- cd integration
|
||||
- go test -args -driver sqlite3
|
||||
- go test -args -driver mysql -dataSource travis@/squirrel
|
||||
- go test -args -driver postgres -dataSource 'postgres://postgres@localhost/squirrel?sslmode=disable'
|
||||
|
||||
notifications:
|
||||
irc: "irc.freenode.net#masterminds"
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
MIT License
|
||||
|
||||
Squirrel: The Masterminds
|
||||
Copyright (c) 2014-2015, Lann Martin. Copyright (C) 2015-2016, Google. Copyright (C) 2015, Matt Farina and Matt Butcher.
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
[](https://masterminds.github.io/stability/maintenance.html)
|
||||
### Squirrel is "complete".
|
||||
Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here.
|
||||
|
||||
|
||||
# Squirrel - fluent SQL generator for Go
|
||||
|
||||
```go
|
||||
import "github.com/Masterminds/squirrel"
|
||||
```
|
||||
|
||||
|
||||
[](https://godoc.org/github.com/Masterminds/squirrel)
|
||||
[](https://travis-ci.org/Masterminds/squirrel)
|
||||
|
||||
**Squirrel is not an ORM.** For an application of Squirrel, check out
|
||||
[structable, a table-struct mapper](https://github.com/Masterminds/structable)
|
||||
|
||||
|
||||
Squirrel helps you build SQL queries from composable parts:
|
||||
|
||||
```go
|
||||
import sq "github.com/Masterminds/squirrel"
|
||||
|
||||
users := sq.Select("*").From("users").Join("emails USING (email_id)")
|
||||
|
||||
active := users.Where(sq.Eq{"deleted_at": nil})
|
||||
|
||||
sql, args, err := active.ToSql()
|
||||
|
||||
sql == "SELECT * FROM users JOIN emails USING (email_id) WHERE deleted_at IS NULL"
|
||||
```
|
||||
|
||||
```go
|
||||
sql, args, err := sq.
|
||||
Insert("users").Columns("name", "age").
|
||||
Values("moe", 13).Values("larry", sq.Expr("? + 5", 12)).
|
||||
ToSql()
|
||||
|
||||
sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)"
|
||||
```
|
||||
|
||||
Squirrel can also execute queries directly:
|
||||
|
||||
```go
|
||||
stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}})
|
||||
three_stooges := stooges.Limit(3)
|
||||
rows, err := three_stooges.RunWith(db).Query()
|
||||
|
||||
// Behaves like:
|
||||
rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3",
|
||||
"moe", "larry", "curly", "shemp")
|
||||
```
|
||||
|
||||
Squirrel makes conditional query building a breeze:
|
||||
|
||||
```go
|
||||
if len(q) > 0 {
|
||||
users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%"))
|
||||
}
|
||||
```
|
||||
|
||||
Squirrel wants to make your life easier:
|
||||
|
||||
```go
|
||||
// StmtCache caches Prepared Stmts for you
|
||||
dbCache := sq.NewStmtCache(db)
|
||||
|
||||
// StatementBuilder keeps your syntax neat
|
||||
mydb := sq.StatementBuilder.RunWith(dbCache)
|
||||
select_users := mydb.Select("*").From("users")
|
||||
```
|
||||
|
||||
Squirrel loves PostgreSQL:
|
||||
|
||||
```go
|
||||
psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
|
||||
|
||||
// You use question marks for placeholders...
|
||||
sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql()
|
||||
|
||||
/// ...squirrel replaces them using PlaceholderFormat.
|
||||
sql == "SELECT * FROM elephants WHERE name IN ($1,$2)"
|
||||
|
||||
|
||||
/// You can retrieve id ...
|
||||
query := sq.Insert("nodes").
|
||||
Columns("uuid", "type", "data").
|
||||
Values(node.Uuid, node.Type, node.Data).
|
||||
Suffix("RETURNING \"id\"").
|
||||
RunWith(m.db).
|
||||
PlaceholderFormat(sq.Dollar)
|
||||
|
||||
query.QueryRow().Scan(&node.id)
|
||||
```
|
||||
|
||||
You can escape question marks by inserting two question marks:
|
||||
|
||||
```sql
|
||||
SELECT * FROM nodes WHERE meta->'format' ??| array[?,?]
|
||||
```
|
||||
|
||||
will generate with the Dollar Placeholder:
|
||||
|
||||
```sql
|
||||
SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2]
|
||||
```
|
||||
|
||||
## FAQ
|
||||
|
||||
* **How can I build an IN query on composite keys / tuples, e.g. `WHERE (col1, col2) IN ((1,2),(3,4))`? ([#104](https://github.com/Masterminds/squirrel/issues/104))**
|
||||
|
||||
Squirrel does not explicitly support tuples, but you can get the same effect with e.g.:
|
||||
|
||||
```go
|
||||
sq.Or{
|
||||
sq.Eq{"col1": 1, "col2": 2},
|
||||
sq.Eq{"col1": 3, "col2": 4}}
|
||||
```
|
||||
|
||||
```sql
|
||||
WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4)
|
||||
```
|
||||
|
||||
(which should produce the same query plan as the tuple version)
|
||||
|
||||
* **Why doesn't `Eq{"mynumber": []uint8{1,2,3}}` turn into an `IN` query? ([#114](https://github.com/Masterminds/squirrel/issues/114))**
|
||||
|
||||
Values of type `[]byte` are handled specially by `database/sql`. In Go, [`byte` is just an alias of `uint8`](https://golang.org/pkg/builtin/#byte), so there is no way to distinguish `[]uint8` from `[]byte`.
|
||||
|
||||
* **Some features are poorly documented!**
|
||||
|
||||
This isn't a frequent complaints section!
|
||||
|
||||
* **Some features are poorly documented?**
|
||||
|
||||
Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries.
|
||||
|
||||
## License
|
||||
|
||||
Squirrel is released under the
|
||||
[MIT License](http://www.opensource.org/licenses/MIT).
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
|
||||
"github.com/lann/builder"
|
||||
)
|
||||
|
||||
func init() {
|
||||
builder.Register(CaseBuilder{}, caseData{})
|
||||
}
|
||||
|
||||
// sqlizerBuffer is a helper that allows to write many Sqlizers one by one
|
||||
// without constant checks for errors that may come from Sqlizer
|
||||
type sqlizerBuffer struct {
|
||||
bytes.Buffer
|
||||
args []interface{}
|
||||
err error
|
||||
}
|
||||
|
||||
// WriteSql converts Sqlizer to SQL strings and writes it to buffer
|
||||
func (b *sqlizerBuffer) WriteSql(item Sqlizer) {
|
||||
if b.err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var str string
|
||||
var args []interface{}
|
||||
str, args, b.err = nestedToSql(item)
|
||||
|
||||
if b.err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
b.WriteString(str)
|
||||
b.WriteByte(' ')
|
||||
b.args = append(b.args, args...)
|
||||
}
|
||||
|
||||
func (b *sqlizerBuffer) ToSql() (string, []interface{}, error) {
|
||||
return b.String(), b.args, b.err
|
||||
}
|
||||
|
||||
// whenPart is a helper structure to describe SQLs "WHEN ... THEN ..." expression
|
||||
type whenPart struct {
|
||||
when Sqlizer
|
||||
then Sqlizer
|
||||
}
|
||||
|
||||
func newWhenPart(when interface{}, then interface{}) whenPart {
|
||||
return whenPart{newPart(when), newPart(then)}
|
||||
}
|
||||
|
||||
// caseData holds all the data required to build a CASE SQL construct
|
||||
type caseData struct {
|
||||
What Sqlizer
|
||||
WhenParts []whenPart
|
||||
Else Sqlizer
|
||||
}
|
||||
|
||||
// ToSql implements Sqlizer
|
||||
func (d *caseData) ToSql() (sqlStr string, args []interface{}, err error) {
|
||||
if len(d.WhenParts) == 0 {
|
||||
err = errors.New("case expression must contain at lease one WHEN clause")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
sql := sqlizerBuffer{}
|
||||
|
||||
sql.WriteString("CASE ")
|
||||
if d.What != nil {
|
||||
sql.WriteSql(d.What)
|
||||
}
|
||||
|
||||
for _, p := range d.WhenParts {
|
||||
sql.WriteString("WHEN ")
|
||||
sql.WriteSql(p.when)
|
||||
sql.WriteString("THEN ")
|
||||
sql.WriteSql(p.then)
|
||||
}
|
||||
|
||||
if d.Else != nil {
|
||||
sql.WriteString("ELSE ")
|
||||
sql.WriteSql(d.Else)
|
||||
}
|
||||
|
||||
sql.WriteString("END")
|
||||
|
||||
return sql.ToSql()
|
||||
}
|
||||
|
||||
// CaseBuilder builds SQL CASE construct which could be used as parts of queries.
|
||||
type CaseBuilder builder.Builder
|
||||
|
||||
// ToSql builds the query into a SQL string and bound args.
|
||||
func (b CaseBuilder) ToSql() (string, []interface{}, error) {
|
||||
data := builder.GetStruct(b).(caseData)
|
||||
return data.ToSql()
|
||||
}
|
||||
|
||||
// MustSql builds the query into a SQL string and bound args.
|
||||
// It panics if there are any errors.
|
||||
func (b CaseBuilder) MustSql() (string, []interface{}) {
|
||||
sql, args, err := b.ToSql()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return sql, args
|
||||
}
|
||||
|
||||
// what sets optional value for CASE construct "CASE [value] ..."
|
||||
func (b CaseBuilder) what(expr interface{}) CaseBuilder {
|
||||
return builder.Set(b, "What", newPart(expr)).(CaseBuilder)
|
||||
}
|
||||
|
||||
// When adds "WHEN ... THEN ..." part to CASE construct
|
||||
func (b CaseBuilder) When(when interface{}, then interface{}) CaseBuilder {
|
||||
// TODO: performance hint: replace slice of WhenPart with just slice of parts
|
||||
// where even indices of the slice belong to "when"s and odd indices belong to "then"s
|
||||
return builder.Append(b, "WhenParts", newWhenPart(when, then)).(CaseBuilder)
|
||||
}
|
||||
|
||||
// What sets optional "ELSE ..." part for CASE construct
|
||||
func (b CaseBuilder) Else(expr interface{}) CaseBuilder {
|
||||
return builder.Set(b, "Else", newPart(expr)).(CaseBuilder)
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/lann/builder"
|
||||
)
|
||||
|
||||
type deleteData struct {
|
||||
PlaceholderFormat PlaceholderFormat
|
||||
RunWith BaseRunner
|
||||
Prefixes []Sqlizer
|
||||
From string
|
||||
WhereParts []Sqlizer
|
||||
OrderBys []string
|
||||
Limit string
|
||||
Offset string
|
||||
Suffixes []Sqlizer
|
||||
}
|
||||
|
||||
func (d *deleteData) Exec() (sql.Result, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
return ExecWith(d.RunWith, d)
|
||||
}
|
||||
|
||||
func (d *deleteData) ToSql() (sqlStr string, args []interface{}, err error) {
|
||||
if len(d.From) == 0 {
|
||||
err = fmt.Errorf("delete statements must specify a From table")
|
||||
return
|
||||
}
|
||||
|
||||
sql := &bytes.Buffer{}
|
||||
|
||||
if len(d.Prefixes) > 0 {
|
||||
args, err = appendToSql(d.Prefixes, sql, " ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
sql.WriteString(" ")
|
||||
}
|
||||
|
||||
sql.WriteString("DELETE FROM ")
|
||||
sql.WriteString(d.From)
|
||||
|
||||
if len(d.WhereParts) > 0 {
|
||||
sql.WriteString(" WHERE ")
|
||||
args, err = appendToSql(d.WhereParts, sql, " AND ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if len(d.OrderBys) > 0 {
|
||||
sql.WriteString(" ORDER BY ")
|
||||
sql.WriteString(strings.Join(d.OrderBys, ", "))
|
||||
}
|
||||
|
||||
if len(d.Limit) > 0 {
|
||||
sql.WriteString(" LIMIT ")
|
||||
sql.WriteString(d.Limit)
|
||||
}
|
||||
|
||||
if len(d.Offset) > 0 {
|
||||
sql.WriteString(" OFFSET ")
|
||||
sql.WriteString(d.Offset)
|
||||
}
|
||||
|
||||
if len(d.Suffixes) > 0 {
|
||||
sql.WriteString(" ")
|
||||
args, err = appendToSql(d.Suffixes, sql, " ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String())
|
||||
return
|
||||
}
|
||||
|
||||
// Builder
|
||||
|
||||
// DeleteBuilder builds SQL DELETE statements.
|
||||
type DeleteBuilder builder.Builder
|
||||
|
||||
func init() {
|
||||
builder.Register(DeleteBuilder{}, deleteData{})
|
||||
}
|
||||
|
||||
// Format methods
|
||||
|
||||
// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the
|
||||
// query.
|
||||
func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder {
|
||||
return builder.Set(b, "PlaceholderFormat", f).(DeleteBuilder)
|
||||
}
|
||||
|
||||
// Runner methods
|
||||
|
||||
// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec.
|
||||
func (b DeleteBuilder) RunWith(runner BaseRunner) DeleteBuilder {
|
||||
return setRunWith(b, runner).(DeleteBuilder)
|
||||
}
|
||||
|
||||
// Exec builds and Execs the query with the Runner set by RunWith.
|
||||
func (b DeleteBuilder) Exec() (sql.Result, error) {
|
||||
data := builder.GetStruct(b).(deleteData)
|
||||
return data.Exec()
|
||||
}
|
||||
|
||||
// SQL methods
|
||||
|
||||
// ToSql builds the query into a SQL string and bound args.
|
||||
func (b DeleteBuilder) ToSql() (string, []interface{}, error) {
|
||||
data := builder.GetStruct(b).(deleteData)
|
||||
return data.ToSql()
|
||||
}
|
||||
|
||||
// MustSql builds the query into a SQL string and bound args.
|
||||
// It panics if there are any errors.
|
||||
func (b DeleteBuilder) MustSql() (string, []interface{}) {
|
||||
sql, args, err := b.ToSql()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return sql, args
|
||||
}
|
||||
|
||||
// Prefix adds an expression to the beginning of the query
|
||||
func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteBuilder {
|
||||
return b.PrefixExpr(Expr(sql, args...))
|
||||
}
|
||||
|
||||
// PrefixExpr adds an expression to the very beginning of the query
|
||||
func (b DeleteBuilder) PrefixExpr(expr Sqlizer) DeleteBuilder {
|
||||
return builder.Append(b, "Prefixes", expr).(DeleteBuilder)
|
||||
}
|
||||
|
||||
// From sets the table to be deleted from.
|
||||
func (b DeleteBuilder) From(from string) DeleteBuilder {
|
||||
return builder.Set(b, "From", from).(DeleteBuilder)
|
||||
}
|
||||
|
||||
// Where adds WHERE expressions to the query.
|
||||
//
|
||||
// See SelectBuilder.Where for more information.
|
||||
func (b DeleteBuilder) Where(pred interface{}, args ...interface{}) DeleteBuilder {
|
||||
return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(DeleteBuilder)
|
||||
}
|
||||
|
||||
// OrderBy adds ORDER BY expressions to the query.
|
||||
func (b DeleteBuilder) OrderBy(orderBys ...string) DeleteBuilder {
|
||||
return builder.Extend(b, "OrderBys", orderBys).(DeleteBuilder)
|
||||
}
|
||||
|
||||
// Limit sets a LIMIT clause on the query.
|
||||
func (b DeleteBuilder) Limit(limit uint64) DeleteBuilder {
|
||||
return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(DeleteBuilder)
|
||||
}
|
||||
|
||||
// Offset sets a OFFSET clause on the query.
|
||||
func (b DeleteBuilder) Offset(offset uint64) DeleteBuilder {
|
||||
return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(DeleteBuilder)
|
||||
}
|
||||
|
||||
// Suffix adds an expression to the end of the query
|
||||
func (b DeleteBuilder) Suffix(sql string, args ...interface{}) DeleteBuilder {
|
||||
return b.SuffixExpr(Expr(sql, args...))
|
||||
}
|
||||
|
||||
// SuffixExpr adds an expression to the end of the query
|
||||
func (b DeleteBuilder) SuffixExpr(expr Sqlizer) DeleteBuilder {
|
||||
return builder.Append(b, "Suffixes", expr).(DeleteBuilder)
|
||||
}
|
||||
|
||||
func (b DeleteBuilder) Query() (*sql.Rows, error) {
|
||||
data := builder.GetStruct(b).(deleteData)
|
||||
return data.Query()
|
||||
}
|
||||
|
||||
func (d *deleteData) Query() (*sql.Rows, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
return QueryWith(d.RunWith, d)
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// +build go1.8
|
||||
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/lann/builder"
|
||||
)
|
||||
|
||||
func (d *deleteData) ExecContext(ctx context.Context) (sql.Result, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
ctxRunner, ok := d.RunWith.(ExecerContext)
|
||||
if !ok {
|
||||
return nil, NoContextSupport
|
||||
}
|
||||
return ExecContextWith(ctx, ctxRunner, d)
|
||||
}
|
||||
|
||||
func (d *deleteData) QueryContext(ctx context.Context) (*sql.Rows, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
ctxRunner, ok := d.RunWith.(QueryerContext)
|
||||
if !ok {
|
||||
return nil, NoContextSupport
|
||||
}
|
||||
return QueryContextWith(ctx, ctxRunner, d)
|
||||
}
|
||||
|
||||
func (d *deleteData) QueryRowContext(ctx context.Context) RowScanner {
|
||||
if d.RunWith == nil {
|
||||
return &Row{err: RunnerNotSet}
|
||||
}
|
||||
queryRower, ok := d.RunWith.(QueryRowerContext)
|
||||
if !ok {
|
||||
if _, ok := d.RunWith.(QueryerContext); !ok {
|
||||
return &Row{err: RunnerNotQueryRunner}
|
||||
}
|
||||
return &Row{err: NoContextSupport}
|
||||
}
|
||||
return QueryRowContextWith(ctx, queryRower, d)
|
||||
}
|
||||
|
||||
// ExecContext builds and ExecContexts the query with the Runner set by RunWith.
|
||||
func (b DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error) {
|
||||
data := builder.GetStruct(b).(deleteData)
|
||||
return data.ExecContext(ctx)
|
||||
}
|
||||
|
||||
// QueryContext builds and QueryContexts the query with the Runner set by RunWith.
|
||||
func (b DeleteBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) {
|
||||
data := builder.GetStruct(b).(deleteData)
|
||||
return data.QueryContext(ctx)
|
||||
}
|
||||
|
||||
// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith.
|
||||
func (b DeleteBuilder) QueryRowContext(ctx context.Context) RowScanner {
|
||||
data := builder.GetStruct(b).(deleteData)
|
||||
return data.QueryRowContext(ctx)
|
||||
}
|
||||
|
||||
// ScanContext is a shortcut for QueryRowContext().Scan.
|
||||
func (b DeleteBuilder) ScanContext(ctx context.Context, dest ...interface{}) error {
|
||||
return b.QueryRowContext(ctx).Scan(dest...)
|
||||
}
|
||||
+419
@@ -0,0 +1,419 @@
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
// Portable true/false literals.
|
||||
sqlTrue = "(1=1)"
|
||||
sqlFalse = "(1=0)"
|
||||
)
|
||||
|
||||
type expr struct {
|
||||
sql string
|
||||
args []interface{}
|
||||
}
|
||||
|
||||
// Expr builds an expression from a SQL fragment and arguments.
|
||||
//
|
||||
// Ex:
|
||||
// Expr("FROM_UNIXTIME(?)", t)
|
||||
func Expr(sql string, args ...interface{}) Sqlizer {
|
||||
return expr{sql: sql, args: args}
|
||||
}
|
||||
|
||||
func (e expr) ToSql() (sql string, args []interface{}, err error) {
|
||||
simple := true
|
||||
for _, arg := range e.args {
|
||||
if _, ok := arg.(Sqlizer); ok {
|
||||
simple = false
|
||||
}
|
||||
}
|
||||
if simple {
|
||||
return e.sql, e.args, nil
|
||||
}
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
ap := e.args
|
||||
sp := e.sql
|
||||
|
||||
var isql string
|
||||
var iargs []interface{}
|
||||
|
||||
for err == nil && len(ap) > 0 && len(sp) > 0 {
|
||||
i := strings.Index(sp, "?")
|
||||
if i < 0 {
|
||||
// no more placeholders
|
||||
break
|
||||
}
|
||||
if len(sp) > i+1 && sp[i+1:i+2] == "?" {
|
||||
// escaped "??"; append it and step past
|
||||
buf.WriteString(sp[:i+2])
|
||||
sp = sp[i+2:]
|
||||
continue
|
||||
}
|
||||
|
||||
if as, ok := ap[0].(Sqlizer); ok {
|
||||
// sqlizer argument; expand it and append the result
|
||||
isql, iargs, err = as.ToSql()
|
||||
buf.WriteString(sp[:i])
|
||||
buf.WriteString(isql)
|
||||
args = append(args, iargs...)
|
||||
} else {
|
||||
// normal argument; append it and the placeholder
|
||||
buf.WriteString(sp[:i+1])
|
||||
args = append(args, ap[0])
|
||||
}
|
||||
|
||||
// step past the argument and placeholder
|
||||
ap = ap[1:]
|
||||
sp = sp[i+1:]
|
||||
}
|
||||
|
||||
// append the remaining sql and arguments
|
||||
buf.WriteString(sp)
|
||||
return buf.String(), append(args, ap...), err
|
||||
}
|
||||
|
||||
type concatExpr []interface{}
|
||||
|
||||
func (ce concatExpr) ToSql() (sql string, args []interface{}, err error) {
|
||||
for _, part := range ce {
|
||||
switch p := part.(type) {
|
||||
case string:
|
||||
sql += p
|
||||
case Sqlizer:
|
||||
pSql, pArgs, err := p.ToSql()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
sql += pSql
|
||||
args = append(args, pArgs...)
|
||||
default:
|
||||
return "", nil, fmt.Errorf("%#v is not a string or Sqlizer", part)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ConcatExpr builds an expression by concatenating strings and other expressions.
|
||||
//
|
||||
// Ex:
|
||||
// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName)
|
||||
// ConcatExpr("COALESCE(full_name,", name_expr, ")")
|
||||
func ConcatExpr(parts ...interface{}) concatExpr {
|
||||
return concatExpr(parts)
|
||||
}
|
||||
|
||||
// aliasExpr helps to alias part of SQL query generated with underlying "expr"
|
||||
type aliasExpr struct {
|
||||
expr Sqlizer
|
||||
alias string
|
||||
}
|
||||
|
||||
// Alias allows to define alias for column in SelectBuilder. Useful when column is
|
||||
// defined as complex expression like IF or CASE
|
||||
// Ex:
|
||||
// .Column(Alias(caseStmt, "case_column"))
|
||||
func Alias(expr Sqlizer, alias string) aliasExpr {
|
||||
return aliasExpr{expr, alias}
|
||||
}
|
||||
|
||||
func (e aliasExpr) ToSql() (sql string, args []interface{}, err error) {
|
||||
sql, args, err = e.expr.ToSql()
|
||||
if err == nil {
|
||||
sql = fmt.Sprintf("(%s) AS %s", sql, e.alias)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Eq is syntactic sugar for use with Where/Having/Set methods.
|
||||
type Eq map[string]interface{}
|
||||
|
||||
func (eq Eq) toSQL(useNotOpr bool) (sql string, args []interface{}, err error) {
|
||||
if len(eq) == 0 {
|
||||
// Empty Sql{} evaluates to true.
|
||||
sql = sqlTrue
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
exprs []string
|
||||
equalOpr = "="
|
||||
inOpr = "IN"
|
||||
nullOpr = "IS"
|
||||
inEmptyExpr = sqlFalse
|
||||
)
|
||||
|
||||
if useNotOpr {
|
||||
equalOpr = "<>"
|
||||
inOpr = "NOT IN"
|
||||
nullOpr = "IS NOT"
|
||||
inEmptyExpr = sqlTrue
|
||||
}
|
||||
|
||||
sortedKeys := getSortedKeys(eq)
|
||||
for _, key := range sortedKeys {
|
||||
var expr string
|
||||
val := eq[key]
|
||||
|
||||
switch v := val.(type) {
|
||||
case driver.Valuer:
|
||||
if val, err = v.Value(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
r := reflect.ValueOf(val)
|
||||
if r.Kind() == reflect.Ptr {
|
||||
if r.IsNil() {
|
||||
val = nil
|
||||
} else {
|
||||
val = r.Elem().Interface()
|
||||
}
|
||||
}
|
||||
|
||||
if val == nil {
|
||||
expr = fmt.Sprintf("%s %s NULL", key, nullOpr)
|
||||
} else {
|
||||
if isListType(val) {
|
||||
valVal := reflect.ValueOf(val)
|
||||
if valVal.Len() == 0 {
|
||||
expr = inEmptyExpr
|
||||
if args == nil {
|
||||
args = []interface{}{}
|
||||
}
|
||||
} else {
|
||||
for i := 0; i < valVal.Len(); i++ {
|
||||
args = append(args, valVal.Index(i).Interface())
|
||||
}
|
||||
expr = fmt.Sprintf("%s %s (%s)", key, inOpr, Placeholders(valVal.Len()))
|
||||
}
|
||||
} else {
|
||||
expr = fmt.Sprintf("%s %s ?", key, equalOpr)
|
||||
args = append(args, val)
|
||||
}
|
||||
}
|
||||
exprs = append(exprs, expr)
|
||||
}
|
||||
sql = strings.Join(exprs, " AND ")
|
||||
return
|
||||
}
|
||||
|
||||
func (eq Eq) ToSql() (sql string, args []interface{}, err error) {
|
||||
return eq.toSQL(false)
|
||||
}
|
||||
|
||||
// NotEq is syntactic sugar for use with Where/Having/Set methods.
|
||||
// Ex:
|
||||
// .Where(NotEq{"id": 1}) == "id <> 1"
|
||||
type NotEq Eq
|
||||
|
||||
func (neq NotEq) ToSql() (sql string, args []interface{}, err error) {
|
||||
return Eq(neq).toSQL(true)
|
||||
}
|
||||
|
||||
// Like is syntactic sugar for use with LIKE conditions.
|
||||
// Ex:
|
||||
// .Where(Like{"name": "%irrel"})
|
||||
type Like map[string]interface{}
|
||||
|
||||
func (lk Like) toSql(opr string) (sql string, args []interface{}, err error) {
|
||||
var exprs []string
|
||||
for key, val := range lk {
|
||||
expr := ""
|
||||
|
||||
switch v := val.(type) {
|
||||
case driver.Valuer:
|
||||
if val, err = v.Value(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if val == nil {
|
||||
err = fmt.Errorf("cannot use null with like operators")
|
||||
return
|
||||
} else {
|
||||
if isListType(val) {
|
||||
err = fmt.Errorf("cannot use array or slice with like operators")
|
||||
return
|
||||
} else {
|
||||
expr = fmt.Sprintf("%s %s ?", key, opr)
|
||||
args = append(args, val)
|
||||
}
|
||||
}
|
||||
exprs = append(exprs, expr)
|
||||
}
|
||||
sql = strings.Join(exprs, " AND ")
|
||||
return
|
||||
}
|
||||
|
||||
func (lk Like) ToSql() (sql string, args []interface{}, err error) {
|
||||
return lk.toSql("LIKE")
|
||||
}
|
||||
|
||||
// NotLike is syntactic sugar for use with LIKE conditions.
|
||||
// Ex:
|
||||
// .Where(NotLike{"name": "%irrel"})
|
||||
type NotLike Like
|
||||
|
||||
func (nlk NotLike) ToSql() (sql string, args []interface{}, err error) {
|
||||
return Like(nlk).toSql("NOT LIKE")
|
||||
}
|
||||
|
||||
// ILike is syntactic sugar for use with ILIKE conditions.
|
||||
// Ex:
|
||||
// .Where(ILike{"name": "sq%"})
|
||||
type ILike Like
|
||||
|
||||
func (ilk ILike) ToSql() (sql string, args []interface{}, err error) {
|
||||
return Like(ilk).toSql("ILIKE")
|
||||
}
|
||||
|
||||
// NotILike is syntactic sugar for use with ILIKE conditions.
|
||||
// Ex:
|
||||
// .Where(NotILike{"name": "sq%"})
|
||||
type NotILike Like
|
||||
|
||||
func (nilk NotILike) ToSql() (sql string, args []interface{}, err error) {
|
||||
return Like(nilk).toSql("NOT ILIKE")
|
||||
}
|
||||
|
||||
// Lt is syntactic sugar for use with Where/Having/Set methods.
|
||||
// Ex:
|
||||
// .Where(Lt{"id": 1})
|
||||
type Lt map[string]interface{}
|
||||
|
||||
func (lt Lt) toSql(opposite, orEq bool) (sql string, args []interface{}, err error) {
|
||||
var (
|
||||
exprs []string
|
||||
opr = "<"
|
||||
)
|
||||
|
||||
if opposite {
|
||||
opr = ">"
|
||||
}
|
||||
|
||||
if orEq {
|
||||
opr = fmt.Sprintf("%s%s", opr, "=")
|
||||
}
|
||||
|
||||
sortedKeys := getSortedKeys(lt)
|
||||
for _, key := range sortedKeys {
|
||||
var expr string
|
||||
val := lt[key]
|
||||
|
||||
switch v := val.(type) {
|
||||
case driver.Valuer:
|
||||
if val, err = v.Value(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if val == nil {
|
||||
err = fmt.Errorf("cannot use null with less than or greater than operators")
|
||||
return
|
||||
}
|
||||
if isListType(val) {
|
||||
err = fmt.Errorf("cannot use array or slice with less than or greater than operators")
|
||||
return
|
||||
}
|
||||
expr = fmt.Sprintf("%s %s ?", key, opr)
|
||||
args = append(args, val)
|
||||
|
||||
exprs = append(exprs, expr)
|
||||
}
|
||||
sql = strings.Join(exprs, " AND ")
|
||||
return
|
||||
}
|
||||
|
||||
func (lt Lt) ToSql() (sql string, args []interface{}, err error) {
|
||||
return lt.toSql(false, false)
|
||||
}
|
||||
|
||||
// LtOrEq is syntactic sugar for use with Where/Having/Set methods.
|
||||
// Ex:
|
||||
// .Where(LtOrEq{"id": 1}) == "id <= 1"
|
||||
type LtOrEq Lt
|
||||
|
||||
func (ltOrEq LtOrEq) ToSql() (sql string, args []interface{}, err error) {
|
||||
return Lt(ltOrEq).toSql(false, true)
|
||||
}
|
||||
|
||||
// Gt is syntactic sugar for use with Where/Having/Set methods.
|
||||
// Ex:
|
||||
// .Where(Gt{"id": 1}) == "id > 1"
|
||||
type Gt Lt
|
||||
|
||||
func (gt Gt) ToSql() (sql string, args []interface{}, err error) {
|
||||
return Lt(gt).toSql(true, false)
|
||||
}
|
||||
|
||||
// GtOrEq is syntactic sugar for use with Where/Having/Set methods.
|
||||
// Ex:
|
||||
// .Where(GtOrEq{"id": 1}) == "id >= 1"
|
||||
type GtOrEq Lt
|
||||
|
||||
func (gtOrEq GtOrEq) ToSql() (sql string, args []interface{}, err error) {
|
||||
return Lt(gtOrEq).toSql(true, true)
|
||||
}
|
||||
|
||||
type conj []Sqlizer
|
||||
|
||||
func (c conj) join(sep, defaultExpr string) (sql string, args []interface{}, err error) {
|
||||
if len(c) == 0 {
|
||||
return defaultExpr, []interface{}{}, nil
|
||||
}
|
||||
var sqlParts []string
|
||||
for _, sqlizer := range c {
|
||||
partSQL, partArgs, err := nestedToSql(sqlizer)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if partSQL != "" {
|
||||
sqlParts = append(sqlParts, partSQL)
|
||||
args = append(args, partArgs...)
|
||||
}
|
||||
}
|
||||
if len(sqlParts) > 0 {
|
||||
sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// And conjunction Sqlizers
|
||||
type And conj
|
||||
|
||||
func (a And) ToSql() (string, []interface{}, error) {
|
||||
return conj(a).join(" AND ", sqlTrue)
|
||||
}
|
||||
|
||||
// Or conjunction Sqlizers
|
||||
type Or conj
|
||||
|
||||
func (o Or) ToSql() (string, []interface{}, error) {
|
||||
return conj(o).join(" OR ", sqlFalse)
|
||||
}
|
||||
|
||||
func getSortedKeys(exp map[string]interface{}) []string {
|
||||
sortedKeys := make([]string, 0, len(exp))
|
||||
for k := range exp {
|
||||
sortedKeys = append(sortedKeys, k)
|
||||
}
|
||||
sort.Strings(sortedKeys)
|
||||
return sortedKeys
|
||||
}
|
||||
|
||||
func isListType(val interface{}) bool {
|
||||
if driver.IsValue(val) {
|
||||
return false
|
||||
}
|
||||
valVal := reflect.ValueOf(val)
|
||||
return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/lann/builder"
|
||||
)
|
||||
|
||||
type insertData struct {
|
||||
PlaceholderFormat PlaceholderFormat
|
||||
RunWith BaseRunner
|
||||
Prefixes []Sqlizer
|
||||
StatementKeyword string
|
||||
Options []string
|
||||
Into string
|
||||
Columns []string
|
||||
Values [][]interface{}
|
||||
Suffixes []Sqlizer
|
||||
Select *SelectBuilder
|
||||
}
|
||||
|
||||
func (d *insertData) Exec() (sql.Result, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
return ExecWith(d.RunWith, d)
|
||||
}
|
||||
|
||||
func (d *insertData) Query() (*sql.Rows, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
return QueryWith(d.RunWith, d)
|
||||
}
|
||||
|
||||
func (d *insertData) QueryRow() RowScanner {
|
||||
if d.RunWith == nil {
|
||||
return &Row{err: RunnerNotSet}
|
||||
}
|
||||
queryRower, ok := d.RunWith.(QueryRower)
|
||||
if !ok {
|
||||
return &Row{err: RunnerNotQueryRunner}
|
||||
}
|
||||
return QueryRowWith(queryRower, d)
|
||||
}
|
||||
|
||||
func (d *insertData) ToSql() (sqlStr string, args []interface{}, err error) {
|
||||
if len(d.Into) == 0 {
|
||||
err = errors.New("insert statements must specify a table")
|
||||
return
|
||||
}
|
||||
if len(d.Values) == 0 && d.Select == nil {
|
||||
err = errors.New("insert statements must have at least one set of values or select clause")
|
||||
return
|
||||
}
|
||||
|
||||
sql := &bytes.Buffer{}
|
||||
|
||||
if len(d.Prefixes) > 0 {
|
||||
args, err = appendToSql(d.Prefixes, sql, " ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
sql.WriteString(" ")
|
||||
}
|
||||
|
||||
if d.StatementKeyword == "" {
|
||||
sql.WriteString("INSERT ")
|
||||
} else {
|
||||
sql.WriteString(d.StatementKeyword)
|
||||
sql.WriteString(" ")
|
||||
}
|
||||
|
||||
if len(d.Options) > 0 {
|
||||
sql.WriteString(strings.Join(d.Options, " "))
|
||||
sql.WriteString(" ")
|
||||
}
|
||||
|
||||
sql.WriteString("INTO ")
|
||||
sql.WriteString(d.Into)
|
||||
sql.WriteString(" ")
|
||||
|
||||
if len(d.Columns) > 0 {
|
||||
sql.WriteString("(")
|
||||
sql.WriteString(strings.Join(d.Columns, ","))
|
||||
sql.WriteString(") ")
|
||||
}
|
||||
|
||||
if d.Select != nil {
|
||||
args, err = d.appendSelectToSQL(sql, args)
|
||||
} else {
|
||||
args, err = d.appendValuesToSQL(sql, args)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if len(d.Suffixes) > 0 {
|
||||
sql.WriteString(" ")
|
||||
args, err = appendToSql(d.Suffixes, sql, " ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String())
|
||||
return
|
||||
}
|
||||
|
||||
func (d *insertData) appendValuesToSQL(w io.Writer, args []interface{}) ([]interface{}, error) {
|
||||
if len(d.Values) == 0 {
|
||||
return args, errors.New("values for insert statements are not set")
|
||||
}
|
||||
|
||||
io.WriteString(w, "VALUES ")
|
||||
|
||||
valuesStrings := make([]string, len(d.Values))
|
||||
for r, row := range d.Values {
|
||||
valueStrings := make([]string, len(row))
|
||||
for v, val := range row {
|
||||
if vs, ok := val.(Sqlizer); ok {
|
||||
vsql, vargs, err := vs.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valueStrings[v] = vsql
|
||||
args = append(args, vargs...)
|
||||
} else {
|
||||
valueStrings[v] = "?"
|
||||
args = append(args, val)
|
||||
}
|
||||
}
|
||||
valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ","))
|
||||
}
|
||||
|
||||
io.WriteString(w, strings.Join(valuesStrings, ","))
|
||||
|
||||
return args, nil
|
||||
}
|
||||
|
||||
func (d *insertData) appendSelectToSQL(w io.Writer, args []interface{}) ([]interface{}, error) {
|
||||
if d.Select == nil {
|
||||
return args, errors.New("select clause for insert statements are not set")
|
||||
}
|
||||
|
||||
selectClause, sArgs, err := d.Select.ToSql()
|
||||
if err != nil {
|
||||
return args, err
|
||||
}
|
||||
|
||||
io.WriteString(w, selectClause)
|
||||
args = append(args, sArgs...)
|
||||
|
||||
return args, nil
|
||||
}
|
||||
|
||||
// Builder
|
||||
|
||||
// InsertBuilder builds SQL INSERT statements.
|
||||
type InsertBuilder builder.Builder
|
||||
|
||||
func init() {
|
||||
builder.Register(InsertBuilder{}, insertData{})
|
||||
}
|
||||
|
||||
// Format methods
|
||||
|
||||
// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the
|
||||
// query.
|
||||
func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder {
|
||||
return builder.Set(b, "PlaceholderFormat", f).(InsertBuilder)
|
||||
}
|
||||
|
||||
// Runner methods
|
||||
|
||||
// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec.
|
||||
func (b InsertBuilder) RunWith(runner BaseRunner) InsertBuilder {
|
||||
return setRunWith(b, runner).(InsertBuilder)
|
||||
}
|
||||
|
||||
// Exec builds and Execs the query with the Runner set by RunWith.
|
||||
func (b InsertBuilder) Exec() (sql.Result, error) {
|
||||
data := builder.GetStruct(b).(insertData)
|
||||
return data.Exec()
|
||||
}
|
||||
|
||||
// Query builds and Querys the query with the Runner set by RunWith.
|
||||
func (b InsertBuilder) Query() (*sql.Rows, error) {
|
||||
data := builder.GetStruct(b).(insertData)
|
||||
return data.Query()
|
||||
}
|
||||
|
||||
// QueryRow builds and QueryRows the query with the Runner set by RunWith.
|
||||
func (b InsertBuilder) QueryRow() RowScanner {
|
||||
data := builder.GetStruct(b).(insertData)
|
||||
return data.QueryRow()
|
||||
}
|
||||
|
||||
// Scan is a shortcut for QueryRow().Scan.
|
||||
func (b InsertBuilder) Scan(dest ...interface{}) error {
|
||||
return b.QueryRow().Scan(dest...)
|
||||
}
|
||||
|
||||
// SQL methods
|
||||
|
||||
// ToSql builds the query into a SQL string and bound args.
|
||||
func (b InsertBuilder) ToSql() (string, []interface{}, error) {
|
||||
data := builder.GetStruct(b).(insertData)
|
||||
return data.ToSql()
|
||||
}
|
||||
|
||||
// MustSql builds the query into a SQL string and bound args.
|
||||
// It panics if there are any errors.
|
||||
func (b InsertBuilder) MustSql() (string, []interface{}) {
|
||||
sql, args, err := b.ToSql()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return sql, args
|
||||
}
|
||||
|
||||
// Prefix adds an expression to the beginning of the query
|
||||
func (b InsertBuilder) Prefix(sql string, args ...interface{}) InsertBuilder {
|
||||
return b.PrefixExpr(Expr(sql, args...))
|
||||
}
|
||||
|
||||
// PrefixExpr adds an expression to the very beginning of the query
|
||||
func (b InsertBuilder) PrefixExpr(expr Sqlizer) InsertBuilder {
|
||||
return builder.Append(b, "Prefixes", expr).(InsertBuilder)
|
||||
}
|
||||
|
||||
// Options adds keyword options before the INTO clause of the query.
|
||||
func (b InsertBuilder) Options(options ...string) InsertBuilder {
|
||||
return builder.Extend(b, "Options", options).(InsertBuilder)
|
||||
}
|
||||
|
||||
// Into sets the INTO clause of the query.
|
||||
func (b InsertBuilder) Into(from string) InsertBuilder {
|
||||
return builder.Set(b, "Into", from).(InsertBuilder)
|
||||
}
|
||||
|
||||
// Columns adds insert columns to the query.
|
||||
func (b InsertBuilder) Columns(columns ...string) InsertBuilder {
|
||||
return builder.Extend(b, "Columns", columns).(InsertBuilder)
|
||||
}
|
||||
|
||||
// Values adds a single row's values to the query.
|
||||
func (b InsertBuilder) Values(values ...interface{}) InsertBuilder {
|
||||
return builder.Append(b, "Values", values).(InsertBuilder)
|
||||
}
|
||||
|
||||
// Suffix adds an expression to the end of the query
|
||||
func (b InsertBuilder) Suffix(sql string, args ...interface{}) InsertBuilder {
|
||||
return b.SuffixExpr(Expr(sql, args...))
|
||||
}
|
||||
|
||||
// SuffixExpr adds an expression to the end of the query
|
||||
func (b InsertBuilder) SuffixExpr(expr Sqlizer) InsertBuilder {
|
||||
return builder.Append(b, "Suffixes", expr).(InsertBuilder)
|
||||
}
|
||||
|
||||
// SetMap set columns and values for insert builder from a map of column name and value
|
||||
// note that it will reset all previous columns and values was set if any
|
||||
func (b InsertBuilder) SetMap(clauses map[string]interface{}) InsertBuilder {
|
||||
// Keep the columns in a consistent order by sorting the column key string.
|
||||
cols := make([]string, 0, len(clauses))
|
||||
for col := range clauses {
|
||||
cols = append(cols, col)
|
||||
}
|
||||
sort.Strings(cols)
|
||||
|
||||
vals := make([]interface{}, 0, len(clauses))
|
||||
for _, col := range cols {
|
||||
vals = append(vals, clauses[col])
|
||||
}
|
||||
|
||||
b = builder.Set(b, "Columns", cols).(InsertBuilder)
|
||||
b = builder.Set(b, "Values", [][]interface{}{vals}).(InsertBuilder)
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// Select set Select clause for insert query
|
||||
// If Values and Select are used, then Select has higher priority
|
||||
func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder {
|
||||
return builder.Set(b, "Select", &sb).(InsertBuilder)
|
||||
}
|
||||
|
||||
func (b InsertBuilder) statementKeyword(keyword string) InsertBuilder {
|
||||
return builder.Set(b, "StatementKeyword", keyword).(InsertBuilder)
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// +build go1.8
|
||||
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/lann/builder"
|
||||
)
|
||||
|
||||
func (d *insertData) ExecContext(ctx context.Context) (sql.Result, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
ctxRunner, ok := d.RunWith.(ExecerContext)
|
||||
if !ok {
|
||||
return nil, NoContextSupport
|
||||
}
|
||||
return ExecContextWith(ctx, ctxRunner, d)
|
||||
}
|
||||
|
||||
func (d *insertData) QueryContext(ctx context.Context) (*sql.Rows, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
ctxRunner, ok := d.RunWith.(QueryerContext)
|
||||
if !ok {
|
||||
return nil, NoContextSupport
|
||||
}
|
||||
return QueryContextWith(ctx, ctxRunner, d)
|
||||
}
|
||||
|
||||
func (d *insertData) QueryRowContext(ctx context.Context) RowScanner {
|
||||
if d.RunWith == nil {
|
||||
return &Row{err: RunnerNotSet}
|
||||
}
|
||||
queryRower, ok := d.RunWith.(QueryRowerContext)
|
||||
if !ok {
|
||||
if _, ok := d.RunWith.(QueryerContext); !ok {
|
||||
return &Row{err: RunnerNotQueryRunner}
|
||||
}
|
||||
return &Row{err: NoContextSupport}
|
||||
}
|
||||
return QueryRowContextWith(ctx, queryRower, d)
|
||||
}
|
||||
|
||||
// ExecContext builds and ExecContexts the query with the Runner set by RunWith.
|
||||
func (b InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error) {
|
||||
data := builder.GetStruct(b).(insertData)
|
||||
return data.ExecContext(ctx)
|
||||
}
|
||||
|
||||
// QueryContext builds and QueryContexts the query with the Runner set by RunWith.
|
||||
func (b InsertBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) {
|
||||
data := builder.GetStruct(b).(insertData)
|
||||
return data.QueryContext(ctx)
|
||||
}
|
||||
|
||||
// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith.
|
||||
func (b InsertBuilder) QueryRowContext(ctx context.Context) RowScanner {
|
||||
data := builder.GetStruct(b).(insertData)
|
||||
return data.QueryRowContext(ctx)
|
||||
}
|
||||
|
||||
// ScanContext is a shortcut for QueryRowContext().Scan.
|
||||
func (b InsertBuilder) ScanContext(ctx context.Context, dest ...interface{}) error {
|
||||
return b.QueryRowContext(ctx).Scan(dest...)
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
type part struct {
|
||||
pred interface{}
|
||||
args []interface{}
|
||||
}
|
||||
|
||||
func newPart(pred interface{}, args ...interface{}) Sqlizer {
|
||||
return &part{pred, args}
|
||||
}
|
||||
|
||||
func (p part) ToSql() (sql string, args []interface{}, err error) {
|
||||
switch pred := p.pred.(type) {
|
||||
case nil:
|
||||
// no-op
|
||||
case Sqlizer:
|
||||
sql, args, err = nestedToSql(pred)
|
||||
case string:
|
||||
sql = pred
|
||||
args = p.args
|
||||
default:
|
||||
err = fmt.Errorf("expected string or Sqlizer, not %T", pred)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func nestedToSql(s Sqlizer) (string, []interface{}, error) {
|
||||
if raw, ok := s.(rawSqlizer); ok {
|
||||
return raw.toSqlRaw()
|
||||
} else {
|
||||
return s.ToSql()
|
||||
}
|
||||
}
|
||||
|
||||
func appendToSql(parts []Sqlizer, w io.Writer, sep string, args []interface{}) ([]interface{}, error) {
|
||||
for i, p := range parts {
|
||||
partSql, partArgs, err := nestedToSql(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if len(partSql) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if i > 0 {
|
||||
_, err := io.WriteString(w, sep)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
_, err = io.WriteString(w, partSql)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args = append(args, partArgs...)
|
||||
}
|
||||
return args, nil
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PlaceholderFormat is the interface that wraps the ReplacePlaceholders method.
|
||||
//
|
||||
// ReplacePlaceholders takes a SQL statement and replaces each question mark
|
||||
// placeholder with a (possibly different) SQL placeholder.
|
||||
type PlaceholderFormat interface {
|
||||
ReplacePlaceholders(sql string) (string, error)
|
||||
}
|
||||
|
||||
type placeholderDebugger interface {
|
||||
debugPlaceholder() string
|
||||
}
|
||||
|
||||
var (
|
||||
// Question is a PlaceholderFormat instance that leaves placeholders as
|
||||
// question marks.
|
||||
Question = questionFormat{}
|
||||
|
||||
// Dollar is a PlaceholderFormat instance that replaces placeholders with
|
||||
// dollar-prefixed positional placeholders (e.g. $1, $2, $3).
|
||||
Dollar = dollarFormat{}
|
||||
|
||||
// Colon is a PlaceholderFormat instance that replaces placeholders with
|
||||
// colon-prefixed positional placeholders (e.g. :1, :2, :3).
|
||||
Colon = colonFormat{}
|
||||
|
||||
// AtP is a PlaceholderFormat instance that replaces placeholders with
|
||||
// "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3).
|
||||
AtP = atpFormat{}
|
||||
)
|
||||
|
||||
type questionFormat struct{}
|
||||
|
||||
func (questionFormat) ReplacePlaceholders(sql string) (string, error) {
|
||||
return sql, nil
|
||||
}
|
||||
|
||||
func (questionFormat) debugPlaceholder() string {
|
||||
return "?"
|
||||
}
|
||||
|
||||
type dollarFormat struct{}
|
||||
|
||||
func (dollarFormat) ReplacePlaceholders(sql string) (string, error) {
|
||||
return replacePositionalPlaceholders(sql, "$")
|
||||
}
|
||||
|
||||
func (dollarFormat) debugPlaceholder() string {
|
||||
return "$"
|
||||
}
|
||||
|
||||
type colonFormat struct{}
|
||||
|
||||
func (colonFormat) ReplacePlaceholders(sql string) (string, error) {
|
||||
return replacePositionalPlaceholders(sql, ":")
|
||||
}
|
||||
|
||||
func (colonFormat) debugPlaceholder() string {
|
||||
return ":"
|
||||
}
|
||||
|
||||
type atpFormat struct{}
|
||||
|
||||
func (atpFormat) ReplacePlaceholders(sql string) (string, error) {
|
||||
return replacePositionalPlaceholders(sql, "@p")
|
||||
}
|
||||
|
||||
func (atpFormat) debugPlaceholder() string {
|
||||
return "@p"
|
||||
}
|
||||
|
||||
// Placeholders returns a string with count ? placeholders joined with commas.
|
||||
func Placeholders(count int) string {
|
||||
if count < 1 {
|
||||
return ""
|
||||
}
|
||||
|
||||
return strings.Repeat(",?", count)[1:]
|
||||
}
|
||||
|
||||
func replacePositionalPlaceholders(sql, prefix string) (string, error) {
|
||||
buf := &bytes.Buffer{}
|
||||
i := 0
|
||||
for {
|
||||
p := strings.Index(sql, "?")
|
||||
if p == -1 {
|
||||
break
|
||||
}
|
||||
|
||||
if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ?
|
||||
buf.WriteString(sql[:p])
|
||||
buf.WriteString("?")
|
||||
if len(sql[p:]) == 1 {
|
||||
break
|
||||
}
|
||||
sql = sql[p+2:]
|
||||
} else {
|
||||
i++
|
||||
buf.WriteString(sql[:p])
|
||||
fmt.Fprintf(buf, "%s%d", prefix, i)
|
||||
sql = sql[p+1:]
|
||||
}
|
||||
}
|
||||
|
||||
buf.WriteString(sql)
|
||||
return buf.String(), nil
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package squirrel
|
||||
|
||||
// RowScanner is the interface that wraps the Scan method.
|
||||
//
|
||||
// Scan behaves like database/sql.Row.Scan.
|
||||
type RowScanner interface {
|
||||
Scan(...interface{}) error
|
||||
}
|
||||
|
||||
// Row wraps database/sql.Row to let squirrel return new errors on Scan.
|
||||
type Row struct {
|
||||
RowScanner
|
||||
err error
|
||||
}
|
||||
|
||||
// Scan returns Row.err or calls RowScanner.Scan.
|
||||
func (r *Row) Scan(dest ...interface{}) error {
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
return r.RowScanner.Scan(dest...)
|
||||
}
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
package squirrel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/lann/builder"
|
||||
)
|
||||
|
||||
type selectData struct {
|
||||
PlaceholderFormat PlaceholderFormat
|
||||
RunWith BaseRunner
|
||||
Prefixes []Sqlizer
|
||||
Options []string
|
||||
Columns []Sqlizer
|
||||
From Sqlizer
|
||||
Joins []Sqlizer
|
||||
WhereParts []Sqlizer
|
||||
GroupBys []string
|
||||
HavingParts []Sqlizer
|
||||
OrderByParts []Sqlizer
|
||||
Limit string
|
||||
Offset string
|
||||
Suffixes []Sqlizer
|
||||
}
|
||||
|
||||
func (d *selectData) Exec() (sql.Result, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
return ExecWith(d.RunWith, d)
|
||||
}
|
||||
|
||||
func (d *selectData) Query() (*sql.Rows, error) {
|
||||
if d.RunWith == nil {
|
||||
return nil, RunnerNotSet
|
||||
}
|
||||
return QueryWith(d.RunWith, d)
|
||||
}
|
||||
|
||||
func (d *selectData) QueryRow() RowScanner {
|
||||
if d.RunWith == nil {
|
||||
return &Row{err: RunnerNotSet}
|
||||
}
|
||||
queryRower, ok := d.RunWith.(QueryRower)
|
||||
if !ok {
|
||||
return &Row{err: RunnerNotQueryRunner}
|
||||
}
|
||||
return QueryRowWith(queryRower, d)
|
||||
}
|
||||
|
||||
func (d *selectData) ToSql() (sqlStr string, args []interface{}, err error) {
|
||||
sqlStr, args, err = d.toSqlRaw()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sqlStr)
|
||||
return
|
||||
}
|
||||
|
||||
func (d *selectData) toSqlRaw() (sqlStr string, args []interface{}, err error) {
|
||||
if len(d.Columns) == 0 {
|
||||
err = fmt.Errorf("select statements must have at least one result column")
|
||||
return
|
||||
}
|
||||
|
||||
sql := &bytes.Buffer{}
|
||||
|
||||
if len(d.Prefixes) > 0 {
|
||||
args, err = appendToSql(d.Prefixes, sql, " ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
sql.WriteString(" ")
|
||||
}
|
||||
|
||||
sql.WriteString("SELECT ")
|
||||
|
||||
if len(d.Options) > 0 {
|
||||
sql.WriteString(strings.Join(d.Options, " "))
|
||||
sql.WriteString(" ")
|
||||
}
|
||||
|
||||
if len(d.Columns) > 0 {
|
||||
args, err = appendToSql(d.Columns, sql, ", ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if d.From != nil {
|
||||
sql.WriteString(" FROM ")
|
||||
args, err = appendToSql([]Sqlizer{d.From}, sql, "", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if len(d.Joins) > 0 {
|
||||
sql.WriteString(" ")
|
||||
args, err = appendToSql(d.Joins, sql, " ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if len(d.WhereParts) > 0 {
|
||||
sql.WriteString(" WHERE ")
|
||||
args, err = appendToSql(d.WhereParts, sql, " AND ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if len(d.GroupBys) > 0 {
|
||||
sql.WriteString(" GROUP BY ")
|
||||
sql.WriteString(strings.Join(d.GroupBys, ", "))
|
||||
}
|
||||
|
||||
if len(d.HavingParts) > 0 {
|
||||
sql.WriteString(" HAVING ")
|
||||
args, err = appendToSql(d.HavingParts, sql, " AND ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if len(d.OrderByParts) > 0 {
|
||||
sql.WriteString(" ORDER BY ")
|
||||
args, err = appendToSql(d.OrderByParts, sql, ", ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if len(d.Limit) > 0 {
|
||||
sql.WriteString(" LIMIT ")
|
||||
sql.WriteString(d.Limit)
|
||||
}
|
||||
|
||||
if len(d.Offset) > 0 {
|
||||
sql.WriteString(" OFFSET ")
|
||||
sql.WriteString(d.Offset)
|
||||
}
|
||||
|
||||
if len(d.Suffixes) > 0 {
|
||||
sql.WriteString(" ")
|
||||
|
||||
args, err = appendToSql(d.Suffixes, sql, " ", args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
sqlStr = sql.String()
|
||||
return
|
||||
}
|
||||
|
||||
// Builder
|
||||
|
||||
// SelectBuilder builds SQL SELECT statements.
|
||||
type SelectBuilder builder.Builder
|
||||
|
||||
func init() {
|
||||
builder.Register(SelectBuilder{}, selectData{})
|
||||
}
|
||||
|
||||
// Format methods
|
||||
|
||||
// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the
|
||||
// query.
|
||||
func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder {
|
||||
return builder.Set(b, "PlaceholderFormat", f).(SelectBuilder)
|
||||
}
|
||||
|
||||
// Runner methods
|
||||
|
||||
// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec.
|
||||
// For most cases runner will be a database connection.
|
||||
//
|
||||
// Internally we use this to mock out the database connection for testing.
|
||||
func (b SelectBuilder) RunWith(runner BaseRunner) SelectBuilder {
|
||||
return setRunWith(b, runner).(SelectBuilder)
|
||||
}
|
||||
|
||||
// Exec builds and Execs the query with the Runner set by RunWith.
|
||||
func (b SelectBuilder) Exec() (sql.Result, error) {
|
||||
data := builder.GetStruct(b).(selectData)
|
||||
return data.Exec()
|
||||
}
|
||||
|
||||
// Query builds and Querys the query with the Runner set by RunWith.
|
||||
func (b SelectBuilder) Query() (*sql.Rows, error) {
|
||||
data := builder.GetStruct(b).(selectData)
|
||||
return data.Query()
|
||||
}
|
||||
|
||||
// QueryRow builds and QueryRows the query with the Runner set by RunWith.
|
||||
func (b SelectBuilder) QueryRow() RowScanner {
|
||||
data := builder.GetStruct(b).(selectData)
|
||||
return data.QueryRow()
|
||||
}
|
||||
|
||||
// Scan is a shortcut for QueryRow().Scan.
|
||||
func (b SelectBuilder) Scan(dest ...interface{}) error {
|
||||
return b.QueryRow().Scan(dest...)
|
||||
}
|
||||
|
||||
// SQL methods
|
||||
|
||||
// ToSql builds the query into a SQL string and bound args.
|
||||
func (b SelectBuilder) ToSql() (string, []interface{}, error) {
|
||||
data := builder.GetStruct(b).(selectData)
|
||||
return data.ToSql()
|
||||
}
|
||||
|
||||
func (b SelectBuilder) toSqlRaw() (string, []interface{}, error) {
|
||||
data := builder.GetStruct(b).(selectData)
|
||||
return data.toSqlRaw()
|
||||
}
|
||||
|
||||
// MustSql builds the query into a SQL string and bound args.
|
||||
// It panics if there are any errors.
|
||||
func (b SelectBuilder) MustSql() (string, []interface{}) {
|
||||
sql, args, err := b.ToSql()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return sql, args
|
||||
}
|
||||
|
||||
// Prefix adds an expression to the beginning of the query
|
||||
func (b SelectBuilder) Prefix(sql string, args ...interface{}) SelectBuilder {
|
||||
return b.PrefixExpr(Expr(sql, args...))
|
||||
}
|
||||
|
||||
// PrefixExpr adds an expression to the very beginning of the query
|
||||
func (b SelectBuilder) PrefixExpr(expr Sqlizer) SelectBuilder {
|
||||
return builder.Append(b, "Prefixes", expr).(SelectBuilder)
|
||||
}
|
||||
|
||||
// Distinct adds a DISTINCT clause to the query.
|
||||
func (b SelectBuilder) Distinct() SelectBuilder {
|
||||
return b.Options("DISTINCT")
|
||||
}
|
||||
|
||||
// Options adds select option to the query
|
||||
func (b SelectBuilder) Options(options ...string) SelectBuilder {
|
||||
return builder.Extend(b, "Options", options).(SelectBuilder)
|
||||
}
|
||||
|
||||
// Columns adds result columns to the query.
|
||||
func (b SelectBuilder) Columns(columns ...string) SelectBuilder {
|
||||
parts := make([]interface{}, 0, len(columns))
|
||||
for _, str := range columns {
|
||||
parts = append(parts, newPart(str))
|
||||
}
|
||||
return builder.Extend(b, "Columns", parts).(SelectBuilder)
|
||||
}
|
||||
|
||||
// RemoveColumns remove all columns from query.
|
||||
// Must add a new column with Column or Columns methods, otherwise
|
||||
// return a error.
|
||||
func (b SelectBuilder) RemoveColumns() SelectBuilder {
|
||||
return builder.Delete(b, "Columns").(SelectBuilder)
|
||||
}
|
||||
|
||||
// Column adds a result column to the query.
|
||||
// Unlike Columns, Column accepts args which will be bound to placeholders in
|
||||
// the columns string, for example:
|
||||
// Column("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)
|
||||
func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBuilder {
|
||||
return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// From sets the FROM clause of the query.
|
||||
func (b SelectBuilder) From(from string) SelectBuilder {
|
||||
return builder.Set(b, "From", newPart(from)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// FromSelect sets a subquery into the FROM clause of the query.
|
||||
func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder {
|
||||
// Prevent misnumbered parameters in nested selects (#183).
|
||||
from = from.PlaceholderFormat(Question)
|
||||
return builder.Set(b, "From", Alias(from, alias)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// JoinClause adds a join clause to the query.
|
||||
func (b SelectBuilder) JoinClause(pred interface{}, args ...interface{}) SelectBuilder {
|
||||
return builder.Append(b, "Joins", newPart(pred, args...)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// Join adds a JOIN clause to the query.
|
||||
func (b SelectBuilder) Join(join string, rest ...interface{}) SelectBuilder {
|
||||
return b.JoinClause("JOIN "+join, rest...)
|
||||
}
|
||||
|
||||
// LeftJoin adds a LEFT JOIN clause to the query.
|
||||
func (b SelectBuilder) LeftJoin(join string, rest ...interface{}) SelectBuilder {
|
||||
return b.JoinClause("LEFT JOIN "+join, rest...)
|
||||
}
|
||||
|
||||
// RightJoin adds a RIGHT JOIN clause to the query.
|
||||
func (b SelectBuilder) RightJoin(join string, rest ...interface{}) SelectBuilder {
|
||||
return b.JoinClause("RIGHT JOIN "+join, rest...)
|
||||
}
|
||||
|
||||
// InnerJoin adds a INNER JOIN clause to the query.
|
||||
func (b SelectBuilder) InnerJoin(join string, rest ...interface{}) SelectBuilder {
|
||||
return b.JoinClause("INNER JOIN "+join, rest...)
|
||||
}
|
||||
|
||||
// CrossJoin adds a CROSS JOIN clause to the query.
|
||||
func (b SelectBuilder) CrossJoin(join string, rest ...interface{}) SelectBuilder {
|
||||
return b.JoinClause("CROSS JOIN "+join, rest...)
|
||||
}
|
||||
|
||||
// Where adds an expression to the WHERE clause of the query.
|
||||
//
|
||||
// Expressions are ANDed together in the generated SQL.
|
||||
//
|
||||
// Where accepts several types for its pred argument:
|
||||
//
|
||||
// nil OR "" - ignored.
|
||||
//
|
||||
// string - SQL expression.
|
||||
// If the expression has SQL placeholders then a set of arguments must be passed
|
||||
// as well, one for each placeholder.
|
||||
//
|
||||
// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is
|
||||
// transformed into an expression like "<key> = ?", with the corresponding value
|
||||
// bound to the placeholder. If the value is nil, the expression will be "<key>
|
||||
// IS NULL". If the value is an array or slice, the expression will be "<key> IN
|
||||
// (?,?,...)", with one placeholder for each item in the value. These expressions
|
||||
// are ANDed together.
|
||||
//
|
||||
// Where will panic if pred isn't any of the above types.
|
||||
func (b SelectBuilder) Where(pred interface{}, args ...interface{}) SelectBuilder {
|
||||
if pred == nil || pred == "" {
|
||||
return b
|
||||
}
|
||||
return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// GroupBy adds GROUP BY expressions to the query.
|
||||
func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder {
|
||||
return builder.Extend(b, "GroupBys", groupBys).(SelectBuilder)
|
||||
}
|
||||
|
||||
// Having adds an expression to the HAVING clause of the query.
|
||||
//
|
||||
// See Where.
|
||||
func (b SelectBuilder) Having(pred interface{}, rest ...interface{}) SelectBuilder {
|
||||
return builder.Append(b, "HavingParts", newWherePart(pred, rest...)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// OrderByClause adds ORDER BY clause to the query.
|
||||
func (b SelectBuilder) OrderByClause(pred interface{}, args ...interface{}) SelectBuilder {
|
||||
return builder.Append(b, "OrderByParts", newPart(pred, args...)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// OrderBy adds ORDER BY expressions to the query.
|
||||
func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder {
|
||||
for _, orderBy := range orderBys {
|
||||
b = b.OrderByClause(orderBy)
|
||||
}
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// Limit sets a LIMIT clause on the query.
|
||||
func (b SelectBuilder) Limit(limit uint64) SelectBuilder {
|
||||
return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// Limit ALL allows to access all records with limit
|
||||
func (b SelectBuilder) RemoveLimit() SelectBuilder {
|
||||
return builder.Delete(b, "Limit").(SelectBuilder)
|
||||
}
|
||||
|
||||
// Offset sets a OFFSET clause on the query.
|
||||
func (b SelectBuilder) Offset(offset uint64) SelectBuilder {
|
||||
return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(SelectBuilder)
|
||||
}
|
||||
|
||||
// RemoveOffset removes OFFSET clause.
|
||||
func (b SelectBuilder) RemoveOffset() SelectBuilder {
|
||||
return builder.Delete(b, "Offset").(SelectBuilder)
|
||||
}
|
||||
|
||||
// Suffix adds an expression to the end of the query
|
||||
func (b SelectBuilder) Suffix(sql string, args ...interface{}) SelectBuilder {
|
||||
return b.SuffixExpr(Expr(sql, args...))
|
||||
}
|
||||
|
||||
// SuffixExpr adds an expression to the end of the query
|
||||
func (b SelectBuilder) SuffixExpr(expr Sqlizer) SelectBuilder {
|
||||
return builder.Append(b, "Suffixes", expr).(SelectBuilder)
|
||||
}
|
||||
Loaded 100 of 2821 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user