Merge branch 'MSP-623' into 'master'

Resolve MSP-623

Closes MSP-623

See merge request integration-system/isp-system-service!6
This commit is contained in:
Грязнов Денис Владимирович committed 2022-06-07 09:49:58 +00:00
commit 636a901c66
67 files changed
+4129 -3136

No files matched your search

+2 -1
View File
@@ -71,5 +71,6 @@ fabric.properties
/vendor/
google/
package.json
structure/
yarn.lock
conf/config_dev.yml
+1 -3
View File
@@ -18,7 +18,6 @@ linters:
- goprintffuncname
- gosimple
- govet
- maligned
- nakedret
- nestif
- nolintlint
@@ -38,8 +37,6 @@ linters:
- exportloopref #for _,p := []int{1, 2, 3} { s.Bar(&p) /* If s stores the pointer, it will be bug.*/ }
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
linters-settings:
maligned:
suggest-new: true
funlen:
lines: 80
statements: 40
@@ -58,6 +55,7 @@ linters-settings:
disabled-checks:
- hugeParam
- rangeValCopy
- ifElseChain
exhaustive:
default-signifies-exhaustive: true
+1 -1
View File
@@ -1 +1 @@
2.2.7
3.0.0
+10
View File
@@ -1,3 +1,13 @@
### v3.0.0
* migrate to isp-kit
* split domain and entity structs
* prepare to remove system block
* remove CRUD for system
* use default system_id
* remove migration initializing city_module
* unite requests to redis into one directory
* prepare to remove redis
* update go to 1.17
### v2.2.7
* updated dependencies
* migrated to common local config
+108
View File
@@ -0,0 +1,108 @@
package assembly
import (
"context"
"github.com/integration-system/isp-kit/app"
"github.com/integration-system/isp-kit/bootstrap"
"github.com/integration-system/isp-kit/cluster"
"github.com/integration-system/isp-kit/dbrx"
"github.com/integration-system/isp-kit/dbx"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/log"
rd "github.com/integration-system/isp-lib/v2/redis"
"github.com/pkg/errors"
"isp-system-service/conf"
"isp-system-service/migrations"
"isp-system-service/redis"
)
type Assembly struct {
boot *bootstrap.Bootstrap
db *dbrx.Client
redis *rd.RxClient
server *grpc.Server
logger *log.Adapter
instanceUuid string
}
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
dbCli := dbrx.New(dbx.WithMigration(boot.MigrationsDir))
server := grpc.NewServer()
localConfig := conf.Local{}
err := boot.App.Config().Read(&localConfig)
if err != nil {
return nil, errors.WithMessage(err, "read local config")
}
redisCli := rd.NewRxClient(
rd.WithInitHandler(func(c *rd.Client, err error) {
if err != nil {
boot.App.Logger().Fatal(c.Context(), "redis init", log.Any("err", err))
}
}))
return &Assembly{
boot: boot,
db: dbCli,
redis: redisCli,
server: server,
logger: boot.App.Logger(),
instanceUuid: localConfig.InstanceUuid,
}, nil
}
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
var (
newCfg conf.Remote
prevCfg conf.Remote
)
err := a.boot.RemoteConfig.Upgrade(remoteConfig, &newCfg, &prevCfg)
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade remote config"))
}
a.redis.ReceiveConfiguration(newCfg.Redis)
redisCli := redis.NewClient(a.instanceUuid, a.redis)
migrations.Initialize.SetParams(redisCli, a.boot.MigrationsDir, newCfg.Database.Schema)
a.logger.SetLevel(newCfg.LogLevel)
err = a.db.Upgrade(ctx, newCfg.Database)
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"), log.Any("config", newCfg.Database))
}
locator := NewLocator(a.db, redisCli, a.logger)
handler := locator.Handler(newCfg)
a.server.Upgrade(handler)
return nil
}
func (a *Assembly) Runners() []app.Runner {
eventHandler := cluster.NewEventHandler().
RemoteConfigReceiver(a)
return []app.Runner{
app.RunnerFunc(func(ctx context.Context) error {
return a.server.ListenAndServe(a.boot.BindingAddress)
}),
app.RunnerFunc(func(ctx context.Context) error {
return a.boot.ClusterCli.Run(ctx, eventHandler)
}),
}
}
func (a *Assembly) Closers() []app.Closer {
return []app.Closer{
a.boot.ClusterCli,
app.CloserFunc(func() error {
a.server.Shutdown()
return nil
}),
a.redis,
a.db,
}
}
+70
View File
@@ -0,0 +1,70 @@
package assembly
import (
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/grpc/endpoint"
"github.com/integration-system/isp-kit/grpc/isp"
"github.com/integration-system/isp-kit/log"
"isp-system-service/conf"
"isp-system-service/controller"
"isp-system-service/redis"
"isp-system-service/repository"
"isp-system-service/routes"
"isp-system-service/service"
"isp-system-service/transaction"
)
type DB interface {
db.DB
db.Transactional
}
type Locator struct {
db DB
redis redis.Client
logger log.Logger
}
func NewLocator(db DB, redisCli redis.Client, logger log.Logger) Locator {
return Locator{
db: db,
redis: redisCli,
logger: logger,
}
}
func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
txManager := transaction.NewManager(l.db)
accessListRep := repository.NewAccessList(l.db)
applicationRep := repository.NewApplication(l.db)
domainRep := repository.NewDomain(l.db)
serviceRep := repository.NewService(l.db)
tokenRep := repository.NewToken(l.db)
accessListService := service.NewAccessList(l.redis, txManager, accessListRep, applicationRep)
applicationService := service.NewApplication(l.redis, txManager, applicationRep, domainRep, serviceRep, tokenRep)
domainService := service.NewDomain(domainRep)
serviceService := service.NewService(domainRep, serviceRep)
jwtService := service.NewJwt(cfg.ApplicationSecret)
tokenService := service.NewToken(l.redis, cfg.DefaultTokenExpireTime, jwtService, applicationService, txManager,
applicationRep, domainRep, serviceRep, tokenRep,
)
accessListController := controller.NewAccessList(accessListService)
applicationController := controller.NewApplication(applicationService)
domainController := controller.NewDomain(domainService)
serviceController := controller.NewService(serviceService)
tokenController := controller.NewToken(tokenService)
c := routes.Controllers{
AccessList: accessListController,
Domain: domainController,
Service: serviceController,
Application: applicationController,
Token: tokenController,
}
mapper := endpoint.DefaultWrapper(l.logger, endpoint.BodyLogger(l.logger))
server := routes.Handler(mapper, c)
return server
}
+6
View File
@@ -9,3 +9,9 @@ grpcInnerAddress:
port: 9005
moduleName: system
instanceUuid: 3f4faf30-8482-48ef-931a-b15575a3af1d
logfile:
path: /var/log/isp-system-service/runtime.log
maxSizeMb: 512
maxBackups: 4
compress: true
+7 -16
View File
@@ -1,12 +1,12 @@
{
"logLevel": "debug",
"database": {
"address": "127.0.0.1",
"port": "5432",
"schema": "system_service",
"database": "name",
"username": "name",
"password": "password",
"createSchema": true
"schema": "mdm_service",
"database": "{{ msp_pgsql_name }}",
"password": "{{ msp_pgsql_password }}",
"username": "{{ msp_pgsql_user }}",
"host": "{{ msp_pgsql_address }}",
"port": 5432
},
"redis": {
"address": {
@@ -15,14 +15,5 @@
},
"defaultDB": 0
},
"metrics": {
"gc": true,
"memory": true,
"address": {
"ip": "0.0.0.0",
"path": "/metrics",
"port": "9555"
}
},
"applicationSecret": "SECRET_ACCESS_KEY"
}
+10
View File
@@ -0,0 +1,10 @@
package conf
import (
"github.com/integration-system/isp-kit/bootstrap"
)
type Local struct {
*bootstrap.LocalConfig
InstanceUuid string
}
-13
View File
@@ -1,13 +0,0 @@
package conf
import (
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/structure"
)
type Configuration struct {
config.CommonLocalConfig
InstanceUuid string
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
GrpcInnerAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcInnerAddress"`
}
+26
View File
@@ -0,0 +1,26 @@
package conf
import (
"reflect"
"github.com/integration-system/isp-kit/dbx"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-kit/rc/schema"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/jsonschema"
)
func init() {
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Type) {
t.Type = "string"
t.Enum = []interface{}{"debug", "info", "error", "fatal"}
})
}
type Remote struct {
Database dbx.Config `schema:"Настройка базы данных"`
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
DefaultTokenExpireTime int `schema:"Время жизни токена по умолчанию,время жизни токена в миллисекундах с момента его создания. если = -1 - время жизни неограниченно"`
ApplicationSecret string `schema:"Ключ для подписи application токенов" valid:"required~Required"`
}
-13
View File
@@ -1,13 +0,0 @@
package conf
import (
"github.com/integration-system/isp-lib/v2/structure"
)
type RemoteConfig struct {
Database structure.DBConfiguration `schema:"Настройка базы данных"`
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
DefaultTokenExpireTime int64 `schema:"Время жизни токена по умолчанию,время жизни токена в миллисекундах с момента его создания. если = -1 - время жизни неограниченно"`
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
ApplicationSecret string `schema:"Ключ для подписи application токенов" valid:"required~Required"`
}
+45 -139
View File
@@ -2,22 +2,28 @@ package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/model"
"isp-system-service/redis"
rd "github.com/go-redis/redis/v8"
rdLib "github.com/integration-system/isp-lib/v2/redis"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
var AccessList accessListController
type AccessListService interface {
GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error)
SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error)
SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error)
}
type accessListController struct{}
type AccessList struct {
service AccessListService
}
func NewAccessList(service AccessListService) AccessList {
return AccessList{
service: service,
}
}
// GetById godoc
// @Tags accessList
@@ -30,160 +36,60 @@ type accessListController struct{}
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /access_list/get_by_id [POST]
func (c accessListController) GetById(request domain.Identity) ([]domain.MethodInfo, error) {
err := c.checkAppById(request.Id)
if err != nil {
func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.MethodInfo, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, status.Errorf(codes.NotFound, "application not found")
case err != nil:
return nil, err
default:
return result, nil
}
return c.getAccessListById(request.Id)
}
// SetOne godoc
// @Tags accessList
// @Summary Настроить доступность метода для приложения
// @Description Возвращает количество изменных строк
// @Description Возвращает количество измененных строк
// @Accept json
// @Produce json
// @Param body body entity.AccessList false "объект для настройки доступа"
// @Success 200 {object} domain.CountResponse "количество измененных строк"
// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа"
// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк"
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /access_list/set_one [POST]
func (c accessListController) SetOne(request entity.AccessList) (*domain.CountResponse, error) {
err := c.checkAppById(request.AppId)
if err != nil {
func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
result, err := c.service.SetOne(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, status.Errorf(codes.NotFound, "application not found")
case err != nil:
return nil, err
default:
return result, nil
}
resp := 0
err = model.DbClient.RunInTransaction(func(repository model.AccessListRepository) error {
resp, err = repository.Upsert(request)
if err != nil {
return err
}
_, err = redis.Client.Get().UseDb(rdLib.ApplicationPermissionDb, func(p rd.Pipeliner) error {
key := fmt.Sprintf("%d|%s", request.AppId, request.Method)
_, err := p.Set(context.Background(), key, request.Value, 0).Result()
return err
})
return err
})
if err != nil {
return nil, err
}
return &domain.CountResponse{Count: resp}, nil
}
// SetList godoc
// @Tags accessList
// @Summary Настройть доступность списка методов для приложения
// @Summary Настроить доступность списка методов для приложения
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
// @Accept json
// @Produce json
// @Param body body domain.SetListRequest false "объект настройки доступа"
// @Param body body domain.AccessListSetListRequest false "объект настройки доступа"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /access_list/set_list [POST]
func (c accessListController) SetList(request domain.SetListRequest) ([]domain.MethodInfo, error) {
err := c.checkAppById(request.AppId)
if err != nil {
func (c AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
result, err := c.service.SetList(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, status.Errorf(codes.NotFound, "application not found")
case err != nil:
return nil, err
default:
return result, nil
}
oldAccessList := make([]entity.AccessList, 0)
err = model.DbClient.RunInTransaction(func(repository model.AccessListRepository) error {
if request.RemoveOld {
oldAccessList, err = repository.DeleteById(request.AppId)
if err != nil {
return err
}
}
newAccessList := make([]entity.AccessList, len(request.Methods))
redisMsetRequest := make([]interface{}, 0)
for i, m := range request.Methods {
newAccessList[i] = entity.AccessList{
AppId: request.AppId,
Method: m.Method,
Value: m.Value,
}
redisMsetRequest = append(redisMsetRequest, fmt.Sprintf("%d|%s", request.AppId, m.Method), m.Value)
}
redisDelRequest := make([]string, len(oldAccessList))
for i, access := range oldAccessList {
redisDelRequest[i] = fmt.Sprintf("%d|%s", request.AppId, access.Method)
}
if len(newAccessList) > 0 {
_, err := repository.UpsertArray(newAccessList)
if err != nil {
return err
}
}
_, err := redis.Client.Get().UseDb(rdLib.ApplicationPermissionDb, func(p rd.Pipeliner) error {
if len(redisDelRequest) > 0 {
_, err := p.Del(context.Background(), redisDelRequest...).Result()
if err != nil {
return err
}
}
if len(redisMsetRequest) > 0 {
_, err := p.MSet(context.Background(), redisMsetRequest...).Result()
if err != nil {
return err
}
}
return nil
})
return err
})
if err != nil {
return nil, err
}
return c.getAccessListById(request.AppId)
}
func (c accessListController) getAccessListById(id int32) ([]domain.MethodInfo, error) {
accessList, err := model.AccessListRep.GetByAppId(id)
if err != nil {
return nil, err
}
return c.convertAccessList(accessList), nil
}
func (accessListController) convertAccessList(accessLists []entity.AccessList) []domain.MethodInfo {
methodInfos := make([]domain.MethodInfo, len(accessLists))
for i, access := range accessLists {
methodInfos[i] = domain.MethodInfo{
Method: access.Method,
Value: access.Value,
}
}
return methodInfos
}
func (accessListController) checkAppById(appId int32) error {
app, err := model.AppRep.GetApplicationById(appId)
if err != nil {
return err
}
if app == nil {
return status.Errorf(codes.NotFound, "application '%d' not found", appId)
}
return nil
}
+103 -289
View File
@@ -2,165 +2,127 @@ package controller
import (
"context"
"fmt"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/model"
"isp-system-service/redis"
rd "github.com/go-redis/redis/v8"
"github.com/integration-system/isp-lib/v2/config"
rdLib "github.com/integration-system/isp-lib/v2/redis"
_ "github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
var Application applicationController
type applicationController struct{}
// GetApplications godoc
// @Tags application
// @Summary Получить список приложений
// @Description Возвращает массив приложений с токенами по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {array} domain.AppWithToken
// @Failure 500 {object} structure.GrpcError
// @Router /application/get_applications [POST]
func (c applicationController) GetApplications(list []int32) ([]*domain.AppWithToken, error) {
res, err := model.AppRep.GetApplications(list)
if err != nil {
return nil, err
}
return c.enrichWithTokens(res...)
type ApplicationService interface {
GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error)
GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error)
GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error)
SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error)
CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error)
Delete(ctx context.Context, idList []int) (int, error)
}
// GetApplicationsByServiceId godoc
// @Tags application
// @Summary Получить список приложений по идентификатору сервиса
// @Description Возвращает список приложений по запрошенныму идентификатору сервиса
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор серсиса"
// @Success 200 {array} domain.AppWithToken
// @Failure 500 {object} structure.GrpcError
// @Router /application/get_applications_by_service_id [POST]
func (c applicationController) GetApplicationsByServiceId(identity domain.Identity) ([]*domain.AppWithToken, error) {
arr, err := model.AppRep.GetApplicationsByServiceId(identity.Id)
if err != nil {
return nil, err
}
return c.enrichWithTokens(arr...)
type Application struct {
service ApplicationService
}
// CreateUpdateApplication godoc
// @Tags application
// @Summary Создать/обновить приложение
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body entity.Application true "Объект приложения"
// @Success 200 {object} domain.AppWithToken
// @Failure 400 {object} structure.GrpcError
// @Failure 404 {object} structure.GrpcError
// @Failure 409 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /application/create_update_application [POST]
func (c applicationController) CreateUpdateApplication(app entity.Application) (*domain.AppWithToken, error) {
existed, err := model.AppRep.GetApplicationByNameAndServiceId(app.Name, app.ServiceId)
if err != nil {
return nil, err
func NewApplication(service ApplicationService) Application {
return Application{
service: service,
}
s, err := model.ServiceRep.GetServiceById(app.ServiceId)
if err != nil {
return nil, err
}
if s == nil {
return nil, status.Errorf(codes.InvalidArgument, "Service with id %d not found", app.ServiceId)
}
if app.Id == 0 {
if existed != nil {
return nil, status.Errorf(codes.AlreadyExists, "Application with name %s already exists", app.Name)
}
app, err = model.AppRep.CreateApplication(app)
if err != nil {
return nil, err
}
_, err = c.enrichWithTokens(app)
if err != nil {
return nil, err
}
return &domain.AppWithToken{App: app, Tokens: []entity.Token{}}, nil
}
if existed != nil && existed.Id != app.Id {
return nil, status.Errorf(codes.AlreadyExists, "Application with name %s already exists", app.Name)
}
existed, err = model.AppRep.GetApplicationById(app.Id)
if err != nil {
return nil, err
}
if existed == nil {
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", app.Id)
}
app, err = model.AppRep.UpdateApplication(app)
if err != nil {
return nil, err
}
arr, err := c.enrichWithTokens(app)
if err != nil {
return nil, err
}
return arr[0], nil
}
// GetApplicationById godoc
// GetById godoc
// @Tags application
// @Summary Получить приложение по идентификатору
// @Description Возвращает описание приложения по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {object} domain.AppWithToken
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} structure.GrpcError
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /application/get_application_by_id [POST]
func (c applicationController) GetApplicationById(identity domain.Identity) (*domain.AppWithToken, error) {
application, err := model.AppRep.GetApplicationById(identity.Id)
if err != nil {
func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id)
case err != nil:
return nil, err
default:
return result, nil
}
if application == nil {
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", identity.Id)
}
arr, err := c.enrichWithTokens(*application)
if err != nil {
return nil, err
}
return arr[0], nil
}
// DeleteApplications godoc
// GetByIdList godoc
// @Tags application
// @Summary Получить список приложений
// @Description Возвращает массив приложений с токенами по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} structure.GrpcError
// @Router /application/get_applications [POST]
func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) {
return c.service.GetByIdList(ctx, req)
}
// GetByServiceId godoc
// @Tags application
// @Summary Получить список приложений по идентификатору сервиса
// @Description Возвращает список приложений по запрошенному идентификатору сервиса
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор сервиса"
// @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} structure.GrpcError
// @Router /application/get_applications_by_service_id [POST]
func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) {
return c.service.GetByServiceId(ctx, req.Id)
}
// GetSystemTree godoc
// @Tags application
// @Summary Метод получения системного дерева
// @Description Возвращает описание взаимосвязей сервисов и приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.DomainWithService
// @Failure 500 {object} structure.GrpcError
// @Router /application/get_system_tree [POST]
func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithService, error) {
return c.service.SystemTree(ctx, domain.DefaultSystemId)
}
// CreateUpdate godoc
// @Tags application
// @Summary Создать/обновить приложение
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} structure.GrpcError
// @Failure 404 {object} structure.GrpcError
// @Failure 409 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /application/create_update_application [POST]
func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.CreateUpdate(ctx, req)
switch {
case errors.Is(err, domain.ErrServiceNotFound):
return nil, status.Errorf(codes.InvalidArgument, "service with id %d not found", req.ServiceId)
case errors.Is(err, domain.ErrApplicationDuplicateName):
return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name)
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", req.Id)
case err != nil:
return nil, err
default:
return result, nil
}
}
// Delete godoc
// @Tags application
// @Summary Удалить приложения
// @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений
@@ -171,165 +133,17 @@ func (c applicationController) GetApplicationById(identity domain.Identity) (*do
// @Failure 400 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /application/delete_applications [POST]
func (applicationController) DeleteApplications(list []int32) (domain.DeleteResponse, error) {
if len(list) == 0 {
return domain.DeleteResponse{}, status.Errorf(codes.InvalidArgument, "At least one id are required")
func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "At least one id are required")
}
var (
count = 0
instanceUuid = config.Get().(*conf.Configuration).InstanceUuid
)
_, err := redis.Client.Get().UseDb(rdLib.ApplicationTokenDb, func(p rd.Pipeliner) error {
return model.DbClient.RunInTransaction(func(
appRep model.AppRepository, tokenRep model.TokenRepository, accessRep model.AccessListRepository) error {
accessList, err := accessRep.GetByAppIdList(list)
if err != nil {
return err
}
redisDelRequest := make([]string, len(accessList))
for i, access := range accessList {
redisDelRequest[i] = fmt.Sprintf("%d|%s", access.AppId, access.Method)
}
tokens, err := tokenRep.GetTokensByAppId(list...)
if err != nil {
return err
}
tokenIdList := make([]string, len(tokens))
for i, t := range tokens {
tokenIdList[i] = t.Token
}
if len(tokenIdList) != 0 {
keys := make([]string, len(tokens))
for i, token := range tokenIdList {
keys[i] = fmt.Sprintf("%s|%s", token, instanceUuid)
}
_, err := p.Del(context.Background(), keys...).Result()
if err != nil {
return err
}
}
count, err = appRep.DeleteApplications(list)
if err != nil {
return err
}
if len(redisDelRequest) > 0 {
_, err := redis.Client.Get().UseDb(rdLib.ApplicationPermissionDb, func(p rd.Pipeliner) error {
_, err := p.Del(context.Background(), redisDelRequest...).Result()
return err
})
if err != nil {
return err
}
}
return nil
})
})
result, err := c.service.Delete(ctx, req)
if err != nil {
return domain.DeleteResponse{}, err
return nil, err
}
return domain.DeleteResponse{Deleted: count}, nil
}
// GetSystemTree godoc
// @Tags application
// @Summary Метод получения системного дерева
// @Description Возвращает описание взаимосвязей сервисов и приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.DomainWithServices
// @Failure 500 {object} structure.GrpcError
// @Router /application/get_system_tree [POST]
func (applicationController) GetSystemTree(md metadata.MD) ([]*domain.DomainWithServices, error) {
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
if err != nil {
return nil, err
}
domains, err := model.DomainRep.GetDomainsBySystemId(int32(sysId))
if err != nil {
return nil, err
}
l := len(domains)
if l == 0 {
return []*domain.DomainWithServices{}, nil
}
idList := make([]int32, l)
domainsMap := make(map[int32]*domain.DomainWithServices, l)
res := make([]*domain.DomainWithServices, l)
for i, d := range domains {
idList[i] = d.Id
dws := &domain.DomainWithServices{Id: d.Id, Name: d.Name, Description: d.Description, Services: make([]*domain.ServiceWithApps, 0)}
domainsMap[d.Id] = dws
res[i] = dws
}
services, err := model.ServiceRep.GetServicesByDomainId(idList...)
if err != nil {
return nil, err
}
l = len(services)
idList = make([]int32, l)
servicesMap := make(map[int32]*domain.ServiceWithApps, l)
for i, s := range services {
idList[i] = s.Id
d := domainsMap[s.DomainId]
swa := &domain.ServiceWithApps{Id: s.Id, Name: s.Name, Description: s.Description, Apps: make([]*domain.SimpleApp, 0)}
d.Services = append(d.Services, swa)
servicesMap[s.Id] = swa
}
apps, err := model.AppRep.GetApplicationsByServiceId(idList...)
if err != nil {
return nil, err
}
for _, app := range apps {
s := servicesMap[app.ServiceId]
s.Apps = append(s.Apps, &domain.SimpleApp{
Id: app.Id,
Name: app.Name,
Type: app.Type,
Description: app.Description,
Tokens: make([]entity.Token, 0),
})
}
return res, nil
}
func (applicationController) enrichWithTokens(apps ...entity.Application) ([]*domain.AppWithToken, error) {
l := len(apps)
if len(apps) == 0 {
return []*domain.AppWithToken{}, nil
}
idList := make([]int32, l)
appMap := make(map[int32]*domain.AppWithToken, l)
enriched := make([]*domain.AppWithToken, l)
for i, a := range apps {
idList[i] = a.Id
awt := &domain.AppWithToken{App: a, Tokens: make([]entity.Token, 0)}
appMap[a.Id] = awt
enriched[i] = awt
}
tokens, err := model.TokenRep.GetTokensByAppId(idList...)
if err != nil {
return nil, err
}
for _, v := range tokens {
app := appMap[v.AppId]
app.Tokens = append(app.Tokens, v)
}
return enriched, nil
return &domain.DeleteResponse{
Deleted: result,
}, nil
}
+75 -105
View File
@@ -1,127 +1,95 @@
package controller
import (
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/model"
"context"
_ "github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
var Domain domainController
type domainController struct{}
// GetDomainsBySystemId godoc
// @Tags domain
// @Summary Получить домены по идентификатору системы
// @Description Возвращает список доменов по системному идентификатору
// @Accept json
// @Produce json
// @Param body body integer false "Идентификатор системы"
// @Success 200 {array} entity.Domain
// @Failure 500 {object} structure.GrpcError
// @Router /domain/get_domains_by_system_id [POST]
func (domainController) GetDomainsBySystemId(md metadata.MD) ([]entity.Domain, error) {
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
if err != nil {
return nil, err
}
return model.DomainRep.GetDomainsBySystemId(int32(sysId))
type DomainService interface {
GetById(ctx context.Context, id int) (*domain.Domain, error)
GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error)
CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error)
Delete(ctx context.Context, idList []int) (int, error)
}
// CreateUpdateDomain godoc
// @Tags domain
// @Summary Создать/обновить домен
// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body entity.Domain true "Объект домена"
// @Success 200 {object} entity.Domain
// @Failure 500 {object} structure.GrpcError
// @Router /domain/create_update_domain [POST]
func (domainController) CreateUpdateDomain(domain entity.Domain, md metadata.MD) (*entity.Domain, error) {
existed, err := model.DomainRep.GetDomainByNameAndSystemId(domain.Name, domain.SystemId)
if err != nil {
return nil, err
}
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
if err != nil {
return nil, err
}
domain.SystemId = int32(sysId)
sys, err := model.SystemRep.GetSystemById(domain.SystemId)
if err != nil {
return nil, err
}
if sys == nil {
return nil, status.Errorf(codes.InvalidArgument, "System with id %d not found", domain.SystemId)
}
if domain.Id == 0 {
if existed != nil {
return nil, status.Errorf(codes.AlreadyExists, "Domain with name %s already exists", domain.Name)
}
domain, err = model.DomainRep.CreateDomain(domain)
if err != nil {
return nil, err
}
return &domain, nil
}
if existed != nil && existed.Id != domain.Id {
return nil, status.Errorf(codes.AlreadyExists, "Domain with name %s already exists", domain.Name)
}
existed, err = model.DomainRep.GetDomainById(domain.Id)
if err != nil {
return nil, err
}
if existed == nil {
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", domain.Id)
}
domain, err = model.DomainRep.UpdateDomain(domain)
if err != nil {
return nil, err
}
return &domain, nil
type Domain struct {
service DomainService
}
// GetDomainById godoc
func NewDomain(service DomainService) Domain {
return Domain{
service: service,
}
}
// GetById godoc
// @Tags domain
// @Summary Получить домен по идентификатору
// @Description Возвращает описание домена по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {object} entity.Domain
// @Success 200 {object} domain.Domain
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /domain/get_domain_by_id [POST]
func (domainController) GetDomainById(identity domain.Identity) (*entity.Domain, error) {
d, err := model.DomainRep.GetDomainById(identity.Id)
if err != nil {
func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domain, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
case err != nil:
return nil, err
default:
return result, nil
}
if d == nil {
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", identity.Id)
}
return d, err
}
// DeleteDomains godoc
// GetBySystemId godoc
// @Tags domain
// @Summary Получить домены по идентификатору системы
// @Description Возвращает список доменов по системному идентификатору
// @Accept json
// @Produce json
// @Param body body integer false "Идентификатор системы"
// @Success 200 {array} domain.Domain
// @Failure 500 {object} structure.GrpcError
// @Router /domain/get_domains_by_system_id [POST]
func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) {
return c.service.GetBySystemId(ctx, domain.DefaultSystemId)
}
// CreateUpdate godoc
// @Tags domain
// @Summary Создать/обновить домен
// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.DomainCreateUpdateRequest true "Объект домена"
// @Success 200 {object} domain.Domain
// @Failure 500 {object} structure.GrpcError
// @Router /domain/create_update_domain [POST]
func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest) (*domain.Domain, error) {
result, err := c.service.CreateUpdate(ctx, req, domain.DefaultSystemId)
switch {
case errors.Is(err, domain.ErrSystemNotFound):
return nil, status.Errorf(codes.InvalidArgument, "system with id %d not found", domain.DefaultSystemId)
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
case errors.Is(err, domain.ErrDomainDuplicateName):
return nil, status.Errorf(codes.AlreadyExists, "domain with name %s already exists", req.Name)
case err != nil:
return nil, err
default:
return result, nil
}
}
// Delete godoc
// @Tags domain
// @Summary Удаление доменов
// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов
@@ -132,15 +100,17 @@ func (domainController) GetDomainById(identity domain.Identity) (*entity.Domain,
// @Failure 400 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /domain/delete_domains [POST]
func (domainController) DeleteDomains(list []int32) (domain.DeleteResponse, error) {
if len(list) == 0 {
return domain.DeleteResponse{Deleted: 0}, status.Errorf(codes.InvalidArgument, "At least one id are required")
func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "at least one id are required")
}
res, err := model.DomainRep.DeleteDomains(list)
result, err := c.service.Delete(ctx, req)
if err != nil {
return domain.DeleteResponse{}, err
return nil, err
}
return domain.DeleteResponse{Deleted: res}, nil
return &domain.DeleteResponse{
Deleted: result,
}, nil
}
+90 -109
View File
@@ -1,134 +1,113 @@
package controller
import (
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/model"
"context"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
var Service serviceController
type serviceController struct{}
// GetService godoc
// @Tags service
// @Summary Получить список сервисов
// @Description Возвращает список сервисов по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов сервисов"
// @Success 200 {array} entity.Service
// @Failure 500 {object} structure.GrpcError
// @Router /service/get_service [POST]
func (serviceController) GetService(list []int32) ([]entity.Service, error) {
res, err := model.ServiceRep.GetServices(list)
if err != nil {
return res, err
}
return res, nil
type ServiceService interface {
GetById(ctx context.Context, id int) (*domain.Service, error)
GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error)
GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error)
CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error)
Delete(ctx context.Context, idList []int) (int, error)
}
// GetServicesByDomainId godoc
// @Tags service
// @Summary Получить список сервисов по идентификатору домена
// @Description Возвращает список сервисов по идентификатору домена
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {array} entity.Service
// @Failure 500 {object} structure.GrpcError
// @Router /service/get_services_by_domain_id [POST]
func (serviceController) GetServicesByDomainId(identity domain.Identity) ([]entity.Service, error) {
return model.ServiceRep.GetServicesByDomainId(identity.Id)
type Service struct {
service ServiceService
}
// CreateUpdateService godoc
// @Tags service
// @Summary Создать/обновить сервис
// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body entity.Service true "Объект сервиса"
// @Success 200 {object} entity.Service
// @Failure 400 {object} structure.GrpcError
// @Failure 404 {object} structure.GrpcError
// @Failure 409 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /service/create_update_service [POST]
func (serviceController) CreateUpdateService(service entity.Service) (*entity.Service, error) {
existed, err := model.ServiceRep.GetServiceByNameAndDomainId(service.Name, service.DomainId)
if err != nil {
return nil, err
func NewService(service ServiceService) Service {
return Service{
service: service,
}
d, err := model.DomainRep.GetDomainById(service.DomainId)
if err != nil {
return nil, err
}
if d == nil {
return nil, status.Errorf(codes.InvalidArgument, "Domain with id %d not found", service.DomainId)
}
if service.Id == 0 {
if existed != nil {
return nil, status.Errorf(codes.AlreadyExists, "Service with name %s already exists", service.Name)
}
service, err = model.ServiceRep.CreateService(service)
if err != nil {
return nil, err
}
return &service, nil
}
if existed != nil && existed.Id != service.Id {
return nil, status.Errorf(codes.AlreadyExists, "Service with name %s already exists", service.Name)
}
existed, err = model.ServiceRep.GetServiceById(service.Id)
if err != nil {
return nil, err
}
if existed == nil {
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", service.Id)
}
service, err = model.ServiceRep.UpdateService(service)
if err != nil {
return nil, err
}
return &service, nil
}
// GetServiceById godoc
// GetById godoc
// @Tags service
// @Summary Получить сервис по идентификатору
// @Description Возвращает описание сервиса по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор сервиса"
// @Success 200 {object} entity.Service
// @Success 200 {object} domain.Service
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /service/get_service_by_id [POST]
func (serviceController) GetServiceById(identity domain.Identity) (*entity.Service, error) {
service, err := model.ServiceRep.GetServiceById(identity.Id)
if err != nil {
func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrServiceNotFound):
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
case err != nil:
return nil, err
default:
return result, nil
}
if service == nil {
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", identity.Id)
}
return service, nil
}
// DeleteService godoc
// Get godoc
// @Tags service
// @Summary Получить список сервисов
// @Description Возвращает список сервисов по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов сервисов"
// @Success 200 {array} domain.Service
// @Failure 500 {object} structure.GrpcError
// @Router /service/get_service [POST]
func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) {
return c.service.GetByIdList(ctx, req)
}
// GetByDomainId godoc
// @Tags service
// @Summary Получить список сервисов по идентификатору домена
// @Description Возвращает список сервисов по идентификатору домена
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {array} domain.Service
// @Failure 500 {object} structure.GrpcError
// @Router /service/get_services_by_domain_id [POST]
func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.Service, error) {
return c.service.GetByDomainId(ctx, req.Id)
}
// CreateUpdate godoc
// @Tags service
// @Summary Создать/обновить сервис
// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса"
// @Success 200 {object} domain.Service
// @Failure 400 {object} structure.GrpcError
// @Failure 404 {object} structure.GrpcError
// @Failure 409 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /service/create_update_service [POST]
func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
result, err := c.service.CreateUpdate(ctx, req)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.InvalidArgument, "domain with id %d not found", req.DomainId)
case errors.Is(err, domain.ErrServiceNotFound):
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
case errors.Is(err, domain.ErrServiceDuplicateName):
return nil, status.Errorf(codes.AlreadyExists, "service with name %s already exists", req.Name)
case err != nil:
return nil, err
default:
return result, nil
}
}
// Delete godoc
// @Tags service
// @Summary Удалить сервисы
// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов
@@ -139,15 +118,17 @@ func (serviceController) GetServiceById(identity domain.Identity) (*entity.Servi
// @Failure 400 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /service/delete_service [POST]
func (serviceController) DeleteService(list []int32) (domain.DeleteResponse, error) {
if len(list) == 0 {
return domain.DeleteResponse{Deleted: 0}, status.Error(codes.InvalidArgument, "At least one id are required")
func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, status.Error(codes.InvalidArgument, "at least one id are required")
}
res, err := model.ServiceRep.DeleteServices(list)
result, err := c.service.Delete(ctx, req)
if err != nil {
return domain.DeleteResponse{}, err
return nil, err
}
return domain.DeleteResponse{Deleted: res}, nil
return &domain.DeleteResponse{
Deleted: result,
}, nil
}
-133
View File
@@ -1,133 +0,0 @@
package controller
import (
"fmt"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/model"
_ "github.com/integration-system/isp-lib/v2/structure"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var System systemController
type systemController struct{}
// GetSystems godoc
// @Tags system
// @Summary Получить список систем
// @Description Возвращает список систем по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов систем"
// @Success 200 {array} entity.System
// @Failure 500 {object} structure.GrpcError
// @Router /system/get_systems [POST]
func (systemController) GetSystems(list []int32) ([]entity.System, error) {
res, err := model.SystemRep.GetSystems(list)
if err != nil {
return res, err
}
return res, nil
}
// CreateUpdateSystem godoc
// @Tags system
// @Summary Создать/обновить систему
// @Description Если система с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body entity.System true "Объект системы"
// @Success 200 {object} entity.System
// @Failure 404 {object} structure.GrpcError
// @Failure 409 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /system/create_update_system [POST]
func (systemController) CreateUpdateSystem(system entity.System) (*entity.System, error) {
existed, err := model.SystemRep.GetSystemByName(system.Name)
if err != nil {
return nil, err
}
if system.Id == 0 {
if existed != nil {
return nil, status.Errorf(codes.AlreadyExists, "System with name %s already exists", system.Name)
}
system, err = model.SystemRep.CreateSystem(system)
if err != nil {
return nil, err
}
return &system, nil
}
if existed != nil && existed.Id != system.Id {
return nil, status.Errorf(codes.AlreadyExists, "System with name %s already exists", system.Name)
}
existed, err = model.SystemRep.GetSystemById(system.Id)
if err != nil {
return nil, err
}
if existed == nil {
return nil, status.Error(codes.NotFound, fmt.Sprintf("System with id %d not found", system.Id))
}
system, err = model.SystemRep.UpdateSystem(system)
if err != nil {
return nil, err
}
return &system, nil
}
// GetSystemById godoc
// @Tags system
// @Summary Получить систему по идентификатору
// @Description Возвращает описание системы по ее идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор системы"
// @Success 200 {object} entity.System
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /system/get_system_by_id [POST]
func (systemController) GetSystemById(identity domain.Identity) (*entity.System, error) {
sys, err := model.SystemRep.GetSystemById(identity.Id)
if err != nil {
return nil, err
}
if sys == nil {
return nil, status.Error(codes.NotFound, fmt.Sprintf("System with id %d not found", identity.Id))
}
return sys, nil
}
// DeleteSystems godoc
// @Tags system
// @Summary Удалить системы
// @Description Удаляет системы по списку их идентификаторов, возвращает количество удаленных систем
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов систем"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /system/delete_systems [POST]
func (systemController) DeleteSystems(list []int32) (domain.DeleteResponse, error) {
if len(list) == 0 {
return domain.DeleteResponse{}, status.Error(codes.InvalidArgument, "At least one id are required")
}
res, err := model.SystemRep.DeleteSystems(list)
if err != nil {
return domain.DeleteResponse{}, err
}
return domain.DeleteResponse{Deleted: res}, nil
}
+54 -210
View File
@@ -2,114 +2,85 @@ package controller
import (
"context"
"fmt"
"time"
rd "github.com/go-redis/redis/v8"
"github.com/integration-system/isp-lib/v2/config"
redisLib "github.com/integration-system/isp-lib/v2/redis"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/model"
"isp-system-service/redis"
"isp-system-service/service"
)
const (
SystemIdentityFieldInDb = "1"
DomainIdentityFieldInDb = "2"
ServiceIdentityFieldInDb = "3"
ApplicationIdentityFieldInDb = "4"
)
type ITokenService interface {
GetByAppId(ctx context.Context, appId int) ([]domain.Token, error)
Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error)
Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error)
RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error)
}
var Token tokenController
type Token struct {
service ITokenService
}
type tokenController struct{}
func NewToken(service ITokenService) Token {
return Token{
service: service,
}
}
// CreateToken godoc
// GetByAppId godoc
// @Tags token
// @Summary Получить токены по идентификатору приложения
// @Description Возвращает список токенов, привязанных к приложению
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {array} entity.Token
// @Failure 500 {object} structure.GrpcError
// @Router /token/get_tokens_by_app_id [POST]
func (c Token) GetByAppId(ctx context.Context, req domain.Identity) ([]domain.Token, error) {
return c.service.GetByAppId(ctx, req.Id)
}
// Create godoc
// @Tags token
// @Summary Создать токен
// @Description Созддает токен и привязывает его к приложению
// @Description Создает токен и привязывает его к приложению
// @Accept json
// @Produce json
// @Param body body domain.CreateTokenRequest true "Объект создания токена"
// @Success 200 {object} domain.AppWithToken
// @Param body body domain.TokenCreateRequest true "Объект создания токена"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 500 {object} structure.GrpcError
// @Router /token/create_token [POST]
func (c tokenController) CreateToken(req domain.CreateTokenRequest) (*domain.AppWithToken, error) {
m, err, app := c.getIdMap(req.AppId)
if err != nil {
func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.Create(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.AppId)
case errors.Is(err, domain.ErrServiceNotFound):
return nil, status.Errorf(codes.NotFound, "service for app_id id %d not found", req.AppId)
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.NotFound, "domain for app_id %d not found", req.AppId)
case err != nil:
return nil, err
default:
return result, nil
}
expTime := req.ExpireTimeMs
if expTime == 0 {
expTime = config.GetRemote().(*conf.RemoteConfig).DefaultTokenExpireTime
}
token, err := service.Jwt.CreateApplication(req.AppId, expTime)
if err != nil {
return nil, err
}
tokenInfo := entity.Token{
Token: token,
ExpireTime: expTime,
AppId: req.AppId,
CreatedAt: time.Now(),
}
if err := model.DbClient.RunInTransaction(func(repository model.TokenRepository) error {
tokenInfo, err = repository.SaveToken(tokenInfo)
if err != nil {
return err
}
return c.setIdentityMapForToken(tokenInfo, m)
}); err != nil {
return nil, err
}
arr, err := Application.enrichWithTokens(*app)
if err != nil {
return nil, err
}
return arr[0], nil
}
// RevokeTokens godoc
// Revoke godoc
// @Tags token
// @Summary Отозвать токены
// @Description Отвязывает токены от приложений и удялет их
// @Description Отвязывает токены от приложений и удаляет их
// @Accept json
// @Produce json
// @Param body body domain.RevokeTokensRequest true "Объект отзыва токенов"
// @Success 200 {object} domain.AppWithToken
// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 500 {object} structure.GrpcError
// @Router /token/revoke_tokens [POST]
func (c tokenController) RevokeTokens(req domain.RevokeTokensRequest) (*domain.AppWithToken, error) {
app, err := model.AppRep.GetApplicationById(req.AppId)
if err != nil {
return nil, err
}
_, err = c.revokeTokens(req.Tokens)
if err != nil {
return nil, err
}
res, err := Application.enrichWithTokens(*app)
if err != nil {
return nil, err
}
return res[0], nil
func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
return c.service.Revoke(ctx, req)
}
// RevokeTokensForApp godoc
// RevokeForApp godoc
// @Tags token
// @Summary Отозвать токены для приложения
// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения
@@ -119,133 +90,6 @@ func (c tokenController) RevokeTokens(req domain.RevokeTokensRequest) (*domain.A
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} structure.GrpcError
// @Router /token/revoke_tokens_for_app [POST]
func (c tokenController) RevokeTokensForApp(identity domain.Identity) (*domain.DeleteResponse, error) {
return c.revokeTokensForApp(identity)
}
// GetTokensByAppId godoc
// @Tags token
// @Summary Получить токены по идентификаотру приложения
// @Description Возвращает список токенов, привязанных к приложению
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {array} entity.Token
// @Failure 500 {object} structure.GrpcError
// @Router /token/get_tokens_by_app_id [POST]
func (tokenController) GetTokensByAppId(identity domain.Identity) ([]entity.Token, error) {
return model.TokenRep.GetTokensByAppId(identity.Id)
}
func (c tokenController) setIdentityMapForToken(token entity.Token, idMap map[string]interface{}) error {
return c.SetIdentityMapForTokenV2(token.Token, token.ExpireTime, idMap)
}
func (tokenController) SetIdentityMapForTokenV2(token string, expireTime int64, idMap map[string]interface{}) error {
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
_, e := redis.Client.Get().UseDbTx(redisLib.ApplicationTokenDb, func(p rd.Pipeliner) error {
key := fmt.Sprintf("%s|%s", token, instanceUuid)
stat := p.HMSet(context.Background(), key, idMap)
err := stat.Err()
if err != nil {
return err
}
if expireTime > 0 {
err = p.Expire(context.Background(), token, time.Duration(expireTime)*time.Millisecond).Err()
}
return err
})
return e
}
func (tokenController) getIdMap(appId int32) (map[string]interface{}, error, *entity.Application) {
appInfo, err := model.AppRep.GetApplicationById(appId)
if err != nil {
return nil, err, nil
}
if appInfo == nil {
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", appId), nil
}
serviceInfo, err := model.ServiceRep.GetServiceById(appInfo.ServiceId)
if err != nil {
return nil, err, appInfo
}
if serviceInfo == nil {
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", appInfo.ServiceId), appInfo
}
domainInfo, err := model.DomainRep.GetDomainById(serviceInfo.DomainId)
if err != nil {
return nil, err, appInfo
}
if domainInfo == nil {
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", serviceInfo.DomainId), appInfo
}
systemInfo, err := model.SystemRep.GetSystemById(domainInfo.SystemId)
if err != nil {
return nil, err, appInfo
}
if systemInfo == nil {
return nil, status.Errorf(codes.NotFound, "System with id %d not found", domainInfo.SystemId), appInfo
}
return map[string]interface{}{
SystemIdentityFieldInDb: systemInfo.Id,
DomainIdentityFieldInDb: domainInfo.Id,
ServiceIdentityFieldInDb: serviceInfo.Id,
ApplicationIdentityFieldInDb: appInfo.Id,
}, nil, appInfo
}
func (c tokenController) revokeTokensForApp(identity domain.Identity) (*domain.DeleteResponse, error) {
tokens, err := model.TokenRep.GetTokensByAppId(identity.Id)
if err != nil {
return nil, err
}
tokenIdList := make([]string, len(tokens))
for i, t := range tokens {
tokenIdList[i] = t.Token
}
return c.revokeTokens(tokenIdList)
}
func (tokenController) revokeTokens(tokens []string) (*domain.DeleteResponse, error) {
if len(tokens) == 0 {
return &domain.DeleteResponse{Deleted: 0}, nil
}
var (
count = 0
instanceUuid = config.Get().(*conf.Configuration).InstanceUuid
keys = make([]string, len(tokens))
)
for i, token := range tokens {
keys[i] = fmt.Sprintf("%s|%s", token, instanceUuid)
}
err := model.DbClient.RunInTransaction(func(rep model.TokenRepository) error {
deleted, err := rep.DeleteTokens(tokens)
if err != nil {
return err
}
count = deleted
_, err = redis.Client.Get().UseDbTx(redisLib.ApplicationTokenDb, func(p rd.Pipeliner) error {
_, err := p.Del(context.Background(), keys...).Result()
return err
})
return err
})
if err != nil {
return nil, err
}
return &domain.DeleteResponse{Deleted: count}, nil
func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) {
return c.service.RevokeByAppId(ctx, req.Id)
}
+272 -420
View File
@@ -1,12 +1,8 @@
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag at
// 2020-09-21 17:04:25.146581 +0300 MSK m=+89.051194375
// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag
package docs
import (
"github.com/integration-system/isp-lib/v2/docs"
)
import "github.com/integration-system/isp-lib/v2/docs"
var doc = `{
"schemes": {{ marshal .Schemes }},
@@ -83,14 +79,14 @@ var doc = `{
"tags": [
"accessList"
],
"summary": "Настройть доступность списка методов для приложения",
"summary": "Настроить доступность списка методов для приложения",
"parameters": [
{
"description": "объект настройки доступа",
"name": "body",
"in": "body",
"schema": {
"$ref": "#/definitions/domain.SetListRequest"
"$ref": "#/definitions/domain.AccessListSetListRequest"
}
}
],
@@ -121,7 +117,7 @@ var doc = `{
},
"/access_list/set_one": {
"post": {
"description": "Возвращает количество изменных строк",
"description": "Возвращает количество измененных строк",
"consumes": [
"application/json"
],
@@ -138,7 +134,7 @@ var doc = `{
"name": "body",
"in": "body",
"schema": {
"$ref": "#/definitions/entity.AccessList"
"$ref": "#/definitions/domain.AccessListSetOneRequest"
}
}
],
@@ -146,7 +142,7 @@ var doc = `{
"200": {
"description": "количество измененных строк",
"schema": {
"$ref": "#/definitions/domain.CountResponse"
"$ref": "#/definitions/domain.AccessListSetOneResponse"
}
},
"404": {
@@ -184,7 +180,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/entity.Application"
"$ref": "#/definitions/domain.ApplicationCreateUpdateRequest"
}
}
],
@@ -192,7 +188,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.AppWithToken"
"$ref": "#/definitions/domain.ApplicationWithTokens"
}
},
"400": {
@@ -298,7 +294,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.AppWithToken"
"$ref": "#/definitions/domain.ApplicationWithTokens"
}
},
"400": {
@@ -354,7 +350,7 @@ var doc = `{
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.AppWithToken"
"$ref": "#/definitions/domain.ApplicationWithTokens"
}
}
},
@@ -369,7 +365,7 @@ var doc = `{
},
"/application/get_applications_by_service_id": {
"post": {
"description": "Возвращает список приложений по запрошенныму идентификатору сервиса",
"description": "Возвращает список приложений по запрошенному идентификатору сервиса",
"consumes": [
"application/json"
],
@@ -382,7 +378,7 @@ var doc = `{
"summary": "Получить список приложений по идентификатору сервиса",
"parameters": [
{
"description": "Идентификатор серсиса",
"description": "Идентификатор сервиса",
"name": "body",
"in": "body",
"required": true,
@@ -397,7 +393,7 @@ var doc = `{
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.AppWithToken"
"$ref": "#/definitions/domain.ApplicationWithTokens"
}
}
},
@@ -429,7 +425,7 @@ var doc = `{
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.DomainWithServices"
"$ref": "#/definitions/domain.DomainWithService"
}
}
},
@@ -462,7 +458,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/entity.Domain"
"$ref": "#/definitions/domain.DomainCreateUpdateRequest"
}
}
],
@@ -470,7 +466,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/entity.Domain"
"$ref": "#/definitions/domain.Domain"
}
},
"500": {
@@ -558,7 +554,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/entity.Domain"
"$ref": "#/definitions/domain.Domain"
}
},
"404": {
@@ -605,7 +601,7 @@ var doc = `{
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/entity.Domain"
"$ref": "#/definitions/domain.Domain"
}
}
},
@@ -638,7 +634,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/entity.Service"
"$ref": "#/definitions/domain.ServiceCreateUpdateRequest"
}
}
],
@@ -646,7 +642,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/entity.Service"
"$ref": "#/definitions/domain.Service"
}
},
"400": {
@@ -757,7 +753,7 @@ var doc = `{
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/entity.Service"
"$ref": "#/definitions/domain.Service"
}
}
},
@@ -798,7 +794,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/entity.Service"
"$ref": "#/definitions/domain.Service"
}
},
"404": {
@@ -846,198 +842,7 @@ var doc = `{
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/entity.Service"
}
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/system/create_update_system": {
"post": {
"description": "Если система с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"system"
],
"summary": "Создать/обновить систему",
"parameters": [
{
"description": "Объект системы",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/entity.System"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/entity.System"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/system/delete_systems": {
"post": {
"description": "Удаляет системы по списку их идентификаторов, возвращает количество удаленных систем",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"system"
],
"summary": "Удалить системы",
"parameters": [
{
"description": "Массив идентификаторов систем",
"name": "body",
"in": "body",
"schema": {
"type": "array",
"items": {
"type": "integer"
}
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.DeleteResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/system/get_system_by_id": {
"post": {
"description": "Возвращает описание системы по ее идентификатору",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"system"
],
"summary": "Получить систему по идентификатору",
"parameters": [
{
"description": "Идентификатор системы",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.Identity"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/entity.System"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/system/get_systems": {
"post": {
"description": "Возвращает список систем по их идентификаторам",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"system"
],
"summary": "Получить список систем",
"parameters": [
{
"description": "Массив идентификаторов систем",
"name": "body",
"in": "body",
"schema": {
"type": "array",
"items": {
"type": "integer"
}
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/entity.System"
"$ref": "#/definitions/domain.Service"
}
}
},
@@ -1052,7 +857,7 @@ var doc = `{
},
"/token/create_token": {
"post": {
"description": "Созддает токен и привязывает его к приложению",
"description": "Создает токен и привязывает его к приложению",
"consumes": [
"application/json"
],
@@ -1070,7 +875,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.CreateTokenRequest"
"$ref": "#/definitions/domain.TokenCreateRequest"
}
}
],
@@ -1078,7 +883,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.AppWithToken"
"$ref": "#/definitions/domain.ApplicationWithTokens"
}
},
"500": {
@@ -1102,7 +907,7 @@ var doc = `{
"tags": [
"token"
],
"summary": "Получить токены по идентификаотру приложения",
"summary": "Получить токены по идентификатору приложения",
"parameters": [
{
"description": "Идентификатор приложения",
@@ -1135,7 +940,7 @@ var doc = `{
},
"/token/revoke_tokens": {
"post": {
"description": "Отвязывает токены от приложений и удялет их",
"description": "Отвязывает токены от приложений и удаляет их",
"consumes": [
"application/json"
],
@@ -1153,7 +958,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.RevokeTokensRequest"
"$ref": "#/definitions/domain.TokenRevokeRequest"
}
}
],
@@ -1161,7 +966,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.AppWithToken"
"$ref": "#/definitions/domain.ApplicationWithTokens"
}
},
"500": {
@@ -1215,30 +1020,7 @@ var doc = `{
}
},
"definitions": {
"domain.AppWithToken": {
"type": "object",
"properties": {
"app": {
"type": "object",
"$ref": "#/definitions/entity.Application"
},
"tokens": {
"type": "array",
"items": {
"$ref": "#/definitions/entity.Token"
}
}
}
},
"domain.CountResponse": {
"type": "object",
"properties": {
"count": {
"type": "integer"
}
}
},
"domain.CreateTokenRequest": {
"domain.AccessListSetListRequest": {
"type": "object",
"required": [
"appId"
@@ -1247,8 +1029,132 @@ var doc = `{
"appId": {
"type": "integer"
},
"expireTimeMs": {
"methods": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.MethodInfo"
}
},
"removeOld": {
"type": "boolean"
}
}
},
"domain.AccessListSetOneRequest": {
"type": "object",
"required": [
"appId",
"method"
],
"properties": {
"appId": {
"type": "integer"
},
"method": {
"type": "string"
},
"value": {
"type": "boolean"
}
}
},
"domain.AccessListSetOneResponse": {
"type": "object",
"properties": {
"count": {
"type": "integer"
}
}
},
"domain.Application": {
"type": "object",
"properties": {
"createdAt": {
"type": "string"
},
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"serviceId": {
"type": "integer"
},
"type": {
"type": "string"
},
"updatedAt": {
"type": "string"
}
}
},
"domain.ApplicationCreateUpdateRequest": {
"type": "object",
"required": [
"name",
"serviceId",
"type"
],
"properties": {
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"serviceId": {
"type": "integer"
},
"type": {
"type": "string",
"enum": [
"SYSTEM",
"MOBILE"
]
}
}
},
"domain.ApplicationSimple": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"tokens": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.Token"
}
},
"type": {
"type": "string"
}
}
},
"domain.ApplicationWithTokens": {
"type": "object",
"properties": {
"app": {
"$ref": "#/definitions/domain.Application"
},
"tokens": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.Token"
}
}
}
},
@@ -1260,7 +1166,47 @@ var doc = `{
}
}
},
"domain.DomainWithServices": {
"domain.Domain": {
"type": "object",
"properties": {
"createdAt": {
"type": "string"
},
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"systemId": {
"type": "integer"
},
"updatedAt": {
"type": "string"
}
}
},
"domain.DomainCreateUpdateRequest": {
"type": "object",
"required": [
"name"
],
"properties": {
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
}
},
"domain.DomainWithService": {
"type": "object",
"properties": {
"description": {
@@ -1302,164 +1248,8 @@ var doc = `{
}
}
},
"domain.RevokeTokensRequest": {
"domain.Service": {
"type": "object",
"required": [
"appId"
],
"properties": {
"appId": {
"type": "integer"
},
"tokens": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"domain.ServiceWithApps": {
"type": "object",
"properties": {
"apps": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.SimpleApp"
}
},
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
}
},
"domain.SetListRequest": {
"type": "object",
"properties": {
"appId": {
"type": "integer"
},
"methods": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.MethodInfo"
}
},
"removeOld": {
"type": "boolean"
}
}
},
"domain.SimpleApp": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"tokens": {
"type": "array",
"items": {
"$ref": "#/definitions/entity.Token"
}
},
"type": {
"type": "string"
}
}
},
"entity.AccessList": {
"type": "object",
"properties": {
"appId": {
"type": "integer"
},
"method": {
"type": "string"
},
"value": {
"type": "boolean"
}
}
},
"entity.Application": {
"type": "object",
"required": [
"name",
"serviceId",
"type"
],
"properties": {
"createdAt": {
"type": "string"
},
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"serviceId": {
"type": "integer"
},
"type": {
"type": "string",
"enum": [
"SYSTEM",
"MOBILE"
]
},
"updatedAt": {
"type": "string"
}
}
},
"entity.Domain": {
"type": "object",
"required": [
"name"
],
"properties": {
"createdAt": {
"type": "string"
},
"description": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"systemId": {
"type": "integer"
},
"updatedAt": {
"type": "string"
}
}
},
"entity.Service": {
"type": "object",
"required": [
"domainId",
"name"
],
"properties": {
"createdAt": {
"type": "string"
@@ -1481,15 +1271,36 @@ var doc = `{
}
}
},
"entity.System": {
"domain.ServiceCreateUpdateRequest": {
"type": "object",
"required": [
"domainId",
"name"
],
"properties": {
"createdAt": {
"description": {
"type": "string"
},
"domainId": {
"type": "integer"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
}
},
"domain.ServiceWithApps": {
"type": "object",
"properties": {
"apps": {
"type": "array",
"items": {
"$ref": "#/definitions/domain.ApplicationSimple"
}
},
"description": {
"type": "string"
},
@@ -1498,18 +1309,59 @@ var doc = `{
},
"name": {
"type": "string"
}
}
},
"domain.Token": {
"type": "object",
"properties": {
"appId": {
"type": "integer"
},
"updatedAt": {
"createdAt": {
"type": "string"
},
"expireTime": {
"type": "integer"
},
"token": {
"type": "string"
}
}
},
"domain.TokenCreateRequest": {
"type": "object",
"required": [
"appId"
],
"properties": {
"appId": {
"type": "integer"
},
"expireTimeMs": {
"type": "integer"
}
}
},
"domain.TokenRevokeRequest": {
"type": "object",
"required": [
"appId"
],
"properties": {
"appId": {
"type": "integer"
},
"tokens": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"entity.Token": {
"type": "object",
"required": [
"appId",
"token"
],
"properties": {
"appId": {
"type": "integer"
@@ -1547,11 +1399,11 @@ var doc = `{
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = docs.SwaggerInfo{
Version: "1.1.2",
Host: "localhost:9003",
Version: "1.0.0",
Host: "localhost:9000",
BasePath: "/api/system",
Schemes: []string{},
Title: "ISP system service",
Title: "isp-system-service",
Description: "Сервис управления реестром внешних приложений и токенами аутентификации",
}
+201 -286
View File
@@ -1,35 +1,128 @@
basePath: /api/system
definitions:
domain.AppWithToken:
domain.AccessListSetListRequest:
properties:
app:
$ref: '#/definitions/entity.Application'
type: object
tokens:
appId:
type: integer
methods:
items:
$ref: '#/definitions/entity.Token'
$ref: '#/definitions/domain.MethodInfo'
type: array
removeOld:
type: boolean
required:
- appId
type: object
domain.CountResponse:
domain.AccessListSetOneRequest:
properties:
appId:
type: integer
method:
type: string
value:
type: boolean
required:
- appId
- method
type: object
domain.AccessListSetOneResponse:
properties:
count:
type: integer
type: object
domain.CreateTokenRequest:
domain.Application:
properties:
appId:
createdAt:
type: string
description:
type: string
id:
type: integer
expireTimeMs:
name:
type: string
serviceId:
type: integer
type:
type: string
updatedAt:
type: string
type: object
domain.ApplicationCreateUpdateRequest:
properties:
description:
type: string
id:
type: integer
name:
type: string
serviceId:
type: integer
type:
enum:
- SYSTEM
- MOBILE
type: string
required:
- appId
- name
- serviceId
- type
type: object
domain.ApplicationSimple:
properties:
description:
type: string
id:
type: integer
name:
type: string
tokens:
items:
$ref: '#/definitions/domain.Token'
type: array
type:
type: string
type: object
domain.ApplicationWithTokens:
properties:
app:
$ref: '#/definitions/domain.Application'
tokens:
items:
$ref: '#/definitions/domain.Token'
type: array
type: object
domain.DeleteResponse:
properties:
deleted:
type: integer
type: object
domain.DomainWithServices:
domain.Domain:
properties:
createdAt:
type: string
description:
type: string
id:
type: integer
name:
type: string
systemId:
type: integer
updatedAt:
type: string
type: object
domain.DomainCreateUpdateRequest:
properties:
description:
type: string
id:
type: integer
name:
type: string
required:
- name
type: object
domain.DomainWithService:
properties:
description:
type: string
@@ -56,107 +149,7 @@ definitions:
value:
type: boolean
type: object
domain.RevokeTokensRequest:
properties:
appId:
type: integer
tokens:
items:
type: string
type: array
required:
- appId
type: object
domain.ServiceWithApps:
properties:
apps:
items:
$ref: '#/definitions/domain.SimpleApp'
type: array
description:
type: string
id:
type: integer
name:
type: string
type: object
domain.SetListRequest:
properties:
appId:
type: integer
methods:
items:
$ref: '#/definitions/domain.MethodInfo'
type: array
removeOld:
type: boolean
type: object
domain.SimpleApp:
properties:
description:
type: string
id:
type: integer
name:
type: string
tokens:
items:
$ref: '#/definitions/entity.Token'
type: array
type:
type: string
type: object
entity.AccessList:
properties:
appId:
type: integer
method:
type: string
value:
type: boolean
type: object
entity.Application:
properties:
createdAt:
type: string
description:
type: string
id:
type: integer
name:
type: string
serviceId:
type: integer
type:
enum:
- SYSTEM
- MOBILE
type: string
updatedAt:
type: string
required:
- name
- serviceId
- type
type: object
entity.Domain:
properties:
createdAt:
type: string
description:
type: string
id:
type: integer
name:
type: string
systemId:
type: integer
updatedAt:
type: string
required:
- name
type: object
entity.Service:
domain.Service:
properties:
createdAt:
type: string
@@ -170,24 +163,64 @@ definitions:
type: string
updatedAt:
type: string
type: object
domain.ServiceCreateUpdateRequest:
properties:
description:
type: string
domainId:
type: integer
id:
type: integer
name:
type: string
required:
- domainId
- name
type: object
entity.System:
domain.ServiceWithApps:
properties:
createdAt:
type: string
apps:
items:
$ref: '#/definitions/domain.ApplicationSimple'
type: array
description:
type: string
id:
type: integer
name:
type: string
updatedAt:
type: object
domain.Token:
properties:
appId:
type: integer
createdAt:
type: string
expireTime:
type: integer
token:
type: string
type: object
domain.TokenCreateRequest:
properties:
appId:
type: integer
expireTimeMs:
type: integer
required:
- name
- appId
type: object
domain.TokenRevokeRequest:
properties:
appId:
type: integer
tokens:
items:
type: string
type: array
required:
- appId
type: object
entity.Token:
properties:
@@ -199,9 +232,6 @@ definitions:
type: integer
token:
type: string
required:
- appId
- token
type: object
structure.GrpcError:
properties:
@@ -214,20 +244,21 @@ definitions:
errorMessage:
type: string
type: object
host: localhost:9003
host: localhost:9000
info:
contact: {}
description: Сервис управления реестром внешних приложений и токенами аутентификации
license:
name: GNU GPL v3.0
title: ISP system service
version: 1.1.2
title: isp-system-service
version: 1.0.0
paths:
/access_list/get_by_id:
post:
consumes:
- application/json
description: Возвращает список методов для приложения, для которых заданы настройки доступа
description: Возвращает список методов для приложения, для которых заданы настройки
доступа
parameters:
- description: идентификатор приложения
in: body
@@ -258,13 +289,14 @@ paths:
post:
consumes:
- application/json
description: Возвращает список методов для приложения, для которых заданы настройки доступа
description: Возвращает список методов для приложения, для которых заданы настройки
доступа
parameters:
- description: объект настройки доступа
in: body
name: body
schema:
$ref: '#/definitions/domain.SetListRequest'
$ref: '#/definitions/domain.AccessListSetListRequest'
produces:
- application/json
responses:
@@ -282,27 +314,27 @@ paths:
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Настройть доступность списка методов для приложения
summary: Настроить доступность списка методов для приложения
tags:
- accessList
/access_list/set_one:
post:
consumes:
- application/json
description: Возвращает количество изменных строк
description: Возвращает количество измененных строк
parameters:
- description: объект для настройки доступа
in: body
name: body
schema:
$ref: '#/definitions/entity.AccessList'
$ref: '#/definitions/domain.AccessListSetOneRequest'
produces:
- application/json
responses:
"200":
description: количество измененных строк
schema:
$ref: '#/definitions/domain.CountResponse'
$ref: '#/definitions/domain.AccessListSetOneResponse'
"404":
description: Not Found
schema:
@@ -318,21 +350,22 @@ paths:
post:
consumes:
- application/json
description: Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
description: Если приложение с такими идентификатором существует, то обновляет
данные, если нет, то добавляет данные в базу
parameters:
- description: Объект приложения
in: body
name: body
required: true
schema:
$ref: '#/definitions/entity.Application'
$ref: '#/definitions/domain.ApplicationCreateUpdateRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.AppWithToken'
$ref: '#/definitions/domain.ApplicationWithTokens'
"400":
description: Bad Request
schema:
@@ -356,7 +389,8 @@ paths:
post:
consumes:
- application/json
description: Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений
description: Удаляет приложения по списку их идентификаторов, возвращает количество
удаленных приложений
parameters:
- description: Массив идентификаторов приложений
in: body
@@ -401,7 +435,7 @@ paths:
"200":
description: OK
schema:
$ref: '#/definitions/domain.AppWithToken'
$ref: '#/definitions/domain.ApplicationWithTokens'
"400":
description: Bad Request
schema:
@@ -437,7 +471,7 @@ paths:
description: OK
schema:
items:
$ref: '#/definitions/domain.AppWithToken'
$ref: '#/definitions/domain.ApplicationWithTokens'
type: array
"500":
description: Internal Server Error
@@ -450,9 +484,9 @@ paths:
post:
consumes:
- application/json
description: Возвращает список приложений по запрошенныму идентификатору сервиса
description: Возвращает список приложений по запрошенному идентификатору сервиса
parameters:
- description: Идентификатор серсиса
- description: Идентификатор сервиса
in: body
name: body
required: true
@@ -465,7 +499,7 @@ paths:
description: OK
schema:
items:
$ref: '#/definitions/domain.AppWithToken'
$ref: '#/definitions/domain.ApplicationWithTokens'
type: array
"500":
description: Internal Server Error
@@ -486,7 +520,7 @@ paths:
description: OK
schema:
items:
$ref: '#/definitions/domain.DomainWithServices'
$ref: '#/definitions/domain.DomainWithService'
type: array
"500":
description: Internal Server Error
@@ -499,21 +533,22 @@ paths:
post:
consumes:
- application/json
description: Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
description: Если домен с такими идентификатором существует, то обновляет данные,
если нет, то добавляет данные в базу
parameters:
- description: Объект домена
in: body
name: body
required: true
schema:
$ref: '#/definitions/entity.Domain'
$ref: '#/definitions/domain.DomainCreateUpdateRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.Domain'
$ref: '#/definitions/domain.Domain'
"500":
description: Internal Server Error
schema:
@@ -525,7 +560,8 @@ paths:
post:
consumes:
- application/json
description: Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов
description: Удаляет домены по списку их идентификаторов, возвращает количество
удаленных доменов
parameters:
- description: Массив идентификаторов доменов
in: body
@@ -570,7 +606,7 @@ paths:
"200":
description: OK
schema:
$ref: '#/definitions/entity.Domain'
$ref: '#/definitions/domain.Domain'
"404":
description: Not Found
schema:
@@ -600,7 +636,7 @@ paths:
description: OK
schema:
items:
$ref: '#/definitions/entity.Domain'
$ref: '#/definitions/domain.Domain'
type: array
"500":
description: Internal Server Error
@@ -613,21 +649,22 @@ paths:
post:
consumes:
- application/json
description: Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
description: Если сервис с такими идентификатором существует, то обновляет данные,
если нет, то добавляет данные в базу
parameters:
- description: Объект сервиса
in: body
name: body
required: true
schema:
$ref: '#/definitions/entity.Service'
$ref: '#/definitions/domain.ServiceCreateUpdateRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.Service'
$ref: '#/definitions/domain.Service'
"400":
description: Bad Request
schema:
@@ -651,7 +688,8 @@ paths:
post:
consumes:
- application/json
description: Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов
description: Удаляет сервисов по списку их идентификаторов, возвращает количество
удаленных сервисов
parameters:
- description: Массив идентификаторов сервисов
in: body
@@ -699,7 +737,7 @@ paths:
description: OK
schema:
items:
$ref: '#/definitions/entity.Service'
$ref: '#/definitions/domain.Service'
type: array
"500":
description: Internal Server Error
@@ -726,7 +764,7 @@ paths:
"200":
description: OK
schema:
$ref: '#/definitions/entity.Service'
$ref: '#/definitions/domain.Service'
"404":
description: Not Found
schema:
@@ -757,7 +795,7 @@ paths:
description: OK
schema:
items:
$ref: '#/definitions/entity.Service'
$ref: '#/definitions/domain.Service'
type: array
"500":
description: Internal Server Error
@@ -766,149 +804,25 @@ paths:
summary: Получить список сервисов по идентификатору домена
tags:
- service
/system/create_update_system:
post:
consumes:
- application/json
description: Если система с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
parameters:
- description: Объект системы
in: body
name: body
required: true
schema:
$ref: '#/definitions/entity.System'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.System'
"404":
description: Not Found
schema:
$ref: '#/definitions/structure.GrpcError'
"409":
description: Conflict
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Создать/обновить систему
tags:
- system
/system/delete_systems:
post:
consumes:
- application/json
description: Удаляет системы по списку их идентификаторов, возвращает количество удаленных систем
parameters:
- description: Массив идентификаторов систем
in: body
name: body
schema:
items:
type: integer
type: array
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Удалить системы
tags:
- system
/system/get_system_by_id:
post:
consumes:
- application/json
description: Возвращает описание системы по ее идентификатору
parameters:
- description: Идентификатор системы
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.Identity'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.System'
"404":
description: Not Found
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Получить систему по идентификатору
tags:
- system
/system/get_systems:
post:
consumes:
- application/json
description: Возвращает список систем по их идентификаторам
parameters:
- description: Массив идентификаторов систем
in: body
name: body
schema:
items:
type: integer
type: array
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/entity.System'
type: array
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Получить список систем
tags:
- system
/token/create_token:
post:
consumes:
- application/json
description: Созддает токен и привязывает его к приложению
description: Создает токен и привязывает его к приложению
parameters:
- description: Объект создания токена
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.CreateTokenRequest'
$ref: '#/definitions/domain.TokenCreateRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.AppWithToken'
$ref: '#/definitions/domain.ApplicationWithTokens'
"500":
description: Internal Server Error
schema:
@@ -941,28 +855,28 @@ paths:
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Получить токены по идентификаотру приложения
summary: Получить токены по идентификатору приложения
tags:
- token
/token/revoke_tokens:
post:
consumes:
- application/json
description: Отвязывает токены от приложений и удялет их
description: Отвязывает токены от приложений и удаляет их
parameters:
- description: Объект отзыва токенов
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.RevokeTokensRequest'
$ref: '#/definitions/domain.TokenRevokeRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.AppWithToken'
$ref: '#/definitions/domain.ApplicationWithTokens'
"500":
description: Internal Server Error
schema:
@@ -974,7 +888,8 @@ paths:
post:
consumes:
- application/json
description: Отвязывает токены от приложений и удаляет их по идентификатору приложения
description: Отвязывает токены от приложений и удаляет их по идентификатору
приложения
parameters:
- description: Идентификатор приложения
in: body
+22
View File
@@ -0,0 +1,22 @@
package domain
type AccessListSetOneRequest struct {
AppId int `valid:"required~Required"`
Method string `valid:"required~Required"`
Value bool
}
type AccessListSetOneResponse struct {
Count int
}
type AccessListSetListRequest struct {
AppId int `valid:"required~Required"`
RemoveOld bool
Methods []MethodInfo
}
type MethodInfo struct {
Method string
Value bool
}
+36
View File
@@ -0,0 +1,36 @@
package domain
import (
"time"
)
type Application struct {
Id int
Name string
Description string
ServiceId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
}
type ApplicationCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Description string
ServiceId int `valid:"required~Required"`
Type string `valid:"required~Required,in(SYSTEM|MOBILE)"`
}
type ApplicationWithTokens struct {
App Application
Tokens []Token
}
type ApplicationSimple struct {
Id int
Name string
Description string
Type string
Tokens []Token
}
+11
View File
@@ -0,0 +1,11 @@
package domain
type (
Identity struct {
Id int `valid:"required~Required"`
}
DeleteResponse struct {
Deleted int
}
)
+27
View File
@@ -0,0 +1,27 @@
package domain
import (
"time"
)
type DomainCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Description string
}
type Domain struct {
Id int
Name string
Description string
SystemId int
CreatedAt time.Time
UpdatedAt time.Time
}
type DomainWithService struct {
Id int
Name string
Description string
Services []*ServiceWithApps
}
+18
View File
@@ -0,0 +1,18 @@
package domain
import (
"github.com/pkg/errors"
)
var (
ErrDomainNotFound = errors.New("domain not found")
ErrDomainDuplicateName = errors.New("domain name already exist")
ErrServiceNotFound = errors.New("service not found")
ErrServiceDuplicateName = errors.New("service name already exist")
ErrSystemNotFound = errors.New("system not found")
ErrApplicationNotFound = errors.New("application not found")
ErrApplicationDuplicateName = errors.New("application name already exist")
)
-17
View File
@@ -1,17 +0,0 @@
package domain
type (
Identity struct {
Id int32 `json:"id" valid:"required~Required"`
}
RevokeTokensRequest struct {
AppId int32 `valid:"required~Required"`
Tokens []string
}
CreateTokenRequest struct {
AppId int32 `valid:"required~Required"`
ExpireTimeMs int64
}
)
-51
View File
@@ -1,51 +0,0 @@
package domain
import "isp-system-service/entity"
type (
DeleteResponse struct {
Deleted int
}
CountResponse struct {
Count int
}
AppWithToken struct {
App entity.Application
Tokens []entity.Token
}
DomainWithServices struct {
Id int32
Name string
Description string
Services []*ServiceWithApps
}
ServiceWithApps struct {
Id int32
Name string
Description string
Apps []*SimpleApp
}
SimpleApp struct {
Id int32
Name string
Description string
Type string
Tokens []entity.Token
}
MethodInfo struct {
Method string
Value bool
}
SetListRequest struct {
AppId int32
RemoveOld bool
Methods []MethodInfo
}
)
+28
View File
@@ -0,0 +1,28 @@
package domain
import (
"time"
)
type Service struct {
Id int
Name string
Description string
DomainId int
CreatedAt time.Time
UpdatedAt time.Time
}
type ServiceCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Description string
DomainId int `valid:"required~Required"`
}
type ServiceWithApps struct {
Id int
Name string
Description string
Apps []*ApplicationSimple
}
+5
View File
@@ -0,0 +1,5 @@
package domain
const (
DefaultSystemId = 1
)
+22
View File
@@ -0,0 +1,22 @@
package domain
import (
"time"
)
type Token struct {
Token string
AppId int
ExpireTime int
CreatedAt time.Time
}
type TokenRevokeRequest struct {
AppId int `valid:"required~Required"`
Tokens []string
}
type TokenCreateRequest struct {
AppId int `valid:"required~Required"`
ExpireTimeMs int
}
+7
View File
@@ -0,0 +1,7 @@
package entity
type AccessList struct {
AppId int
Method string
Value bool
}
+15
View File
@@ -0,0 +1,15 @@
package entity
import (
"time"
)
type Application struct {
Id int
Name string
Description *string
ServiceId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
}
+14
View File
@@ -0,0 +1,14 @@
package entity
import (
"time"
)
type Domain struct {
Id int
Name string
Description *string
SystemId int
CreatedAt time.Time
UpdatedAt time.Time
}
-67
View File
@@ -1,67 +0,0 @@
package entity
import "time"
const (
RootAdminApplicationId = 1
)
const (
AppTypeSystem = "SYSTEM"
AppTypeMobile = "MOBILE"
)
type System struct {
tableName string `pg:"system_service.system" json:"-"` //nolint
Id int32
Name string `valid:"required~Required"`
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
type Domain struct {
tableName string `pg:"system_service.domain" json:"-"` //nolint
Name string `valid:"required~Required"`
Id int32
SystemId int32
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
type Service struct {
tableName string `pg:"system_service.service" json:"-"` //nolint
Id int32
DomainId int32 `valid:"required~Required"`
Name string `valid:"required~Required"`
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
type Application struct {
tableName string `pg:"system_service.application" json:"-"` //nolint
Name string `valid:"required~Required"`
Description string
Type string `valid:"required~Required,in(SYSTEM|MOBILE)"`
ServiceId int32 `valid:"required~Required"`
Id int32
CreatedAt time.Time
UpdatedAt time.Time
}
type Token struct {
tableName string `pg:"system_service.token" json:"-"` //nolint
Token string `valid:"required~Required" pg:"pk:token"`
AppId int32 `valid:"required~Required"`
ExpireTime int64
CreatedAt time.Time
}
type AccessList struct {
tableName string `pg:"system_service.access_list" json:"-"` //nolint
Method string `pg:",pk"`
AppId int32 `pg:",pk"`
Value bool
}
+15
View File
@@ -0,0 +1,15 @@
package entity
type RedisSetToken struct {
Token string
ExpireTime int
DomainIdentity int
ServiceIdentity int
ApplicationIdentity int
}
type RedisApplicationPermission struct {
AppId int
Method string
Value bool
}
+14
View File
@@ -0,0 +1,14 @@
package entity
import (
"time"
)
type Service struct {
Id int
Name string
Description *string
DomainId int
CreatedAt time.Time
UpdatedAt time.Time
}
+12
View File
@@ -0,0 +1,12 @@
package entity
import (
"time"
)
type Token struct {
Token string
AppId int
ExpireTime int
CreatedAt time.Time
}
+80 -6
View File
@@ -1,13 +1,87 @@
module isp-system-service
go 1.16
go 1.17
require (
github.com/integration-system/isp-kit v1.7.0
github.com/integration-system/jsonschema v1.0.1
github.com/pkg/errors v0.9.1
)
require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/fsnotify/fsnotify v1.5.3 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect
github.com/integration-system/bellows v1.0.1 // indirect
github.com/integration-system/go-cmp v0.0.0-20190131081942-ac5582987a2f // indirect
github.com/integration-system/isp-etp-go/v2 v2.1.3 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.12.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.3.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.11.0 // indirect
github.com/jackc/pgx/v4 v4.16.0 // indirect
github.com/jmoiron/sqlx v1.3.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.15.1 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.0-beta.8 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.11.0 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/swaggo/swag v1.7.0 // indirect
go.opentelemetry.io/otel v0.19.0 // indirect
go.opentelemetry.io/otel/metric v0.19.0 // indirect
go.opentelemetry.io/otel/trace v0.19.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
go.uber.org/zap v1.21.0 // indirect
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect
golang.org/x/net v0.0.0-20220421235706-1d1ef9303861 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/genproto v0.0.0-20220422154200-b37d22cd5731 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.66.4 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
nhooyr.io/websocket v1.8.7 // indirect
)
require (
github.com/BurntSushi/toml v1.1.0 // indirect
github.com/Masterminds/squirrel v1.5.2
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-pg/pg/v9 v9.2.1
github.com/go-openapi/spec v0.20.5 // indirect
github.com/go-openapi/swag v0.21.1 // indirect
github.com/go-redis/redis/v8 v8.8.2
github.com/integration-system/isp-lib/v2 v2.8.7
github.com/integration-system/isp-log v1.1.8
github.com/pressly/goose v2.6.0+incompatible
google.golang.org/grpc v1.38.0
github.com/integration-system/isp-lib/v2 v2.10.0
github.com/mailru/easyjson v0.7.7 // indirect
github.com/pressly/goose v2.7.0+incompatible
golang.org/x/tools v0.1.10 // indirect
google.golang.org/grpc v1.46.0
)
+400 -359
View File
File diff suppressed because it is too large. Load diff
-120
View File
@@ -1,120 +0,0 @@
package helper
import (
"isp-system-service/controller"
"isp-system-service/domain"
"isp-system-service/entity"
"google.golang.org/grpc/metadata"
)
type SystemHandler struct {
GetSystems func([]int32) ([]entity.System, error) `method:"get_systems" group:"system" inner:"true"`
CreateUpdateSystem func(entity.System) (*entity.System, error) `method:"create_update_system" group:"system" inner:"true"`
GetSystemById func(domain.Identity) (*entity.System, error) `method:"get_system_by_id" group:"system" inner:"true"`
DeleteSystems func([]int32) (domain.DeleteResponse, error) `method:"delete_systems" group:"system" inner:"true"`
}
type DomainHandler struct {
GetDomainsBySystemId func(metadata.MD) ([]entity.Domain, error) `method:"get_domains_by_system_id" group:"domain" inner:"true"`
CreateUpdateDomain func(entity.Domain, metadata.MD) (*entity.Domain, error) `method:"create_update_domain" group:"domain" inner:"true"`
GetDomainById func(domain.Identity) (*entity.Domain, error) `method:"get_domain_by_id" group:"domain" inner:"true"`
DeleteDomains func([]int32) (domain.DeleteResponse, error) `method:"delete_domains" group:"domain" inner:"true"`
}
type ServiceHandler struct {
GetService func([]int32) ([]entity.Service, error) `method:"get_service" group:"service" inner:"true"`
GetServicesByDomainId func(domain.Identity) ([]entity.Service, error) `method:"get_services_by_domain_id" group:"service" inner:"true"`
CreateUpdateService func(entity.Service) (*entity.Service, error) `method:"create_update_service" group:"service" inner:"true"`
GetServiceById func(domain.Identity) (*entity.Service, error) `method:"get_service_by_id" group:"service" inner:"true"`
DeleteService func([]int32) (domain.DeleteResponse, error) `method:"delete_service" group:"service" inner:"true"`
}
type ApplicationHandler struct {
GetApplications func([]int32) ([]*domain.AppWithToken, error) `method:"get_applications" group:"application" inner:"true"`
GetApplicationsByServiceId func(domain.Identity) ([]*domain.AppWithToken, error) `method:"get_applications_by_service_id" group:"application" inner:"true"`
CreateUpdateApplication func(entity.Application) (*domain.AppWithToken, error) `method:"create_update_application" group:"application" inner:"true"`
GetApplicationById func(domain.Identity) (*domain.AppWithToken, error) `method:"get_application_by_id" group:"application" inner:"true"`
DeleteApplications func([]int32) (domain.DeleteResponse, error) `method:"delete_applications" group:"application" inner:"true"`
GetSystemTree func(metadata.MD) ([]*domain.DomainWithServices, error) `method:"get_system_tree" group:"application" inner:"true"`
}
type TokenHandler struct {
CreateToken func(domain.CreateTokenRequest) (*domain.AppWithToken, error) `method:"create_token" group:"token" inner:"true"`
RevokeTokens func(domain.RevokeTokensRequest) (*domain.AppWithToken, error) `method:"revoke_tokens" group:"token" inner:"true"`
RevokeTokensForApp func(domain.Identity) (*domain.DeleteResponse, error) `method:"revoke_tokens_for_app" group:"token" inner:"true"`
GetTokensByAppId func(domain.Identity) ([]entity.Token, error) `method:"get_tokens_by_app_id" group:"token" inner:"true"`
}
type AccessListHandler struct {
GetById func(domain.Identity) ([]domain.MethodInfo, error) `method:"get_by_id" group:"access_list" inner:"true"`
SetOne func(entity.AccessList) (*domain.CountResponse, error) `method:"set_one" group:"access_list" inner:"true"`
SetList func(domain.SetListRequest) ([]domain.MethodInfo, error) `method:"set_list" group:"access_list" inner:"true"`
}
func GetSystemHandler() *SystemHandler {
return &SystemHandler{
GetSystems: controller.System.GetSystems,
CreateUpdateSystem: controller.System.CreateUpdateSystem,
GetSystemById: controller.System.GetSystemById,
DeleteSystems: controller.System.DeleteSystems,
}
}
func GetDomainHandler() *DomainHandler {
return &DomainHandler{
GetDomainsBySystemId: controller.Domain.GetDomainsBySystemId,
CreateUpdateDomain: controller.Domain.CreateUpdateDomain,
GetDomainById: controller.Domain.GetDomainById,
DeleteDomains: controller.Domain.DeleteDomains,
}
}
func GetServiceHandler() *ServiceHandler {
return &ServiceHandler{
GetService: controller.Service.GetService,
GetServicesByDomainId: controller.Service.GetServicesByDomainId,
CreateUpdateService: controller.Service.CreateUpdateService,
GetServiceById: controller.Service.GetServiceById,
DeleteService: controller.Service.DeleteService,
}
}
func GetApplicationHandler() *ApplicationHandler {
return &ApplicationHandler{
GetApplications: controller.Application.GetApplications,
GetApplicationsByServiceId: controller.Application.GetApplicationsByServiceId,
CreateUpdateApplication: controller.Application.CreateUpdateApplication,
GetApplicationById: controller.Application.GetApplicationById,
DeleteApplications: controller.Application.DeleteApplications,
GetSystemTree: controller.Application.GetSystemTree,
}
}
func GetTokenHandler() *TokenHandler {
return &TokenHandler{
CreateToken: controller.Token.CreateToken,
GetTokensByAppId: controller.Token.GetTokensByAppId,
RevokeTokens: controller.Token.RevokeTokens,
RevokeTokensForApp: controller.Token.RevokeTokensForApp,
}
}
func GetAccessListHandler() *AccessListHandler {
return &AccessListHandler{
GetById: controller.AccessList.GetById,
SetOne: controller.AccessList.SetOne,
SetList: controller.AccessList.SetList,
}
}
func GetAllHandlers() []interface{} {
return []interface{}{
GetSystemHandler(),
GetDomainHandler(),
GetServiceHandler(),
GetApplicationHandler(),
GetTokenHandler(),
GetAccessListHandler(),
}
}
-6
View File
@@ -1,6 +0,0 @@
package log_code
const (
ErrorDatabaseClient = 801
ErrorRedisClient = 802
)
+27 -80
View File
@@ -1,28 +1,19 @@
package main
import (
"context"
"os"
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/bootstrap"
"github.com/integration-system/isp-lib/v2/config/schema"
"github.com/integration-system/isp-lib/v2/metric"
"github.com/integration-system/isp-lib/v2/structure"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"github.com/integration-system/isp-kit/bootstrap"
"github.com/integration-system/isp-kit/shutdown"
"isp-system-service/assembly"
"isp-system-service/conf"
_ "isp-system-service/docs"
"isp-system-service/helper"
"isp-system-service/migrations"
"isp-system-service/model"
"isp-system-service/redis"
"isp-system-service/routes"
)
var version = "0.1.0"
var (
version = "1.0.0"
)
// @title ISP system service
// @version 1.1.2
// @title isp-system-service
// @version 1.0.0
// @description Сервис управления реестром внешних приложений и токенами аутентификации
// @license.name GNU GPL v3.0
@@ -33,70 +24,26 @@ var version = "0.1.0"
//go:generate swag init --parseDependency
//go:generate rm -f docs/swagger.json
func main() {
bootstrap.
ServiceBootstrap(&conf.Configuration{}, &conf.RemoteConfig{}).
OnLocalConfigLoad(onLocalConfigLoad).
DefaultRemoteConfigPath(schema.ResolveDefaultConfigPath("default_remote_config.json")).
SocketConfiguration(socketConfiguration).
DeclareMe(routesData).
OnRemoteConfigReceive(onRemoteConfigReceive).
OnShutdown(onShutdown).
OnSocketErrorReceive(onRemoteErrorReceive).
OnConfigErrorReceive(onRemoteConfigErrorReceive).
SubscribeBroadcastEvent(bootstrap.ListenRestartEvent()).
Run()
}
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors())
app := boot.App
logger := app.Logger()
func onRemoteErrorReceive(errorMessage map[string]interface{}) {
log.WithMetadata(errorMessage).Error(stdcodes.ReceiveErrorFromConfig, "error from config service")
}
assembly, err := assembly.New(boot)
if err != nil {
logger.Fatal(app.Context(), err)
}
app.AddRunners(assembly.Runners()...)
app.AddClosers(assembly.Closers()...)
func onRemoteConfigErrorReceive(errorMessage string) {
log.WithMetadata(map[string]interface{}{
"message": errorMessage,
}).Error(stdcodes.ReceiveErrorOnGettingConfigFromConfig, "error on getting remote configuration")
}
shutdown.On(func() {
logger.Info(app.Context(), "starting shutdown")
app.Shutdown()
logger.Info(app.Context(), "shutdown completed")
})
func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
appConfig := cfg.(*conf.Configuration)
return structure.SocketConfiguration{
Host: appConfig.ConfigServiceAddress.IP,
Port: appConfig.ConfigServiceAddress.Port,
Secure: false,
UrlParams: map[string]string{
"module_name": appConfig.ModuleName,
},
}
}
func onShutdown(_ context.Context, _ os.Signal) {
backend.StopGrpcServer()
_ = model.DbClient.Close()
redis.Client.Close()
}
func onRemoteConfigReceive(remoteConfig, oldConfig *conf.RemoteConfig) {
migrations.DatabaseConfig = remoteConfig.Database
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
model.DbClient.ReceiveConfiguration(remoteConfig.Database)
metric.InitCollectors(remoteConfig.Metrics, oldConfig.Metrics)
metric.InitHttpServer(remoteConfig.Metrics)
}
func onLocalConfigLoad(cfg *conf.Configuration) {
handlers := helper.GetAllHandlers()
service := backend.GetDefaultService(cfg.ModuleName, handlers...)
backend.StartBackendGrpcServer(cfg.GrpcInnerAddress, service)
}
func routesData(localConfig interface{}) bootstrap.ModuleInfo {
cfg := localConfig.(*conf.Configuration)
return bootstrap.ModuleInfo{
ModuleName: cfg.ModuleName,
ModuleVersion: version,
GrpcOuterAddress: cfg.GrpcOuterAddress,
Handlers: helper.GetAllHandlers(),
err = app.Run()
if err != nil {
app.Shutdown()
logger.Fatal(app.Context(), err)
}
}
+120 -70
View File
@@ -1,17 +1,17 @@
package migrations
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"github.com/integration-system/isp-lib/v2/database"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/pkg/errors"
"github.com/pressly/goose"
"isp-system-service/controller"
"isp-system-service/domain"
"isp-system-service/entity"
)
const (
@@ -25,105 +25,155 @@ const (
initFile = "init.json"
)
var DatabaseConfig structure.DBConfiguration
func init() {
goose.AddMigration(Up, Down)
goose.AddMigration(Initialize.Up, Initialize.Down)
}
func Up(tx *sql.Tx) error {
path := filepath.Join(database.ResolveMigrationsDirectory(), initFile)
type IRedis interface {
SetApplicationToken(ctx context.Context, req entity.RedisSetToken) error
}
var Initialize = &initializeMigration{}
type initializeMigration struct {
redis IRedis
migrationDir string
schema string
}
type identity struct {
domainId int
appId int
serviceId int
}
func (i *initializeMigration) SetParams(redis IRedis, migrationDir string, schema string) {
i.redis = redis
i.migrationDir = migrationDir
i.schema = schema
}
func (i *initializeMigration) Up(tx *sql.Tx) error {
path := filepath.Join(i.migrationDir, initFile)
bytes, err := ioutil.ReadFile(path)
if err != nil {
return err
return errors.WithMessage(err, "read file")
}
var list []domain.DomainWithServices
if err := json.Unmarshal(bytes, &list); err != nil {
return err
list := make([]domain.DomainWithService, 0)
err = json.Unmarshal(bytes, &list)
if err != nil {
return errors.WithMessage(err, "json unmarshal")
}
schema := DatabaseConfig.Schema
lastDomainId := int64(0)
lastServiceId := int64(0)
lastAppId := int64(0)
lastDomainId := 0
lastServiceId := 0
lastAppId := 0
for _, domainInfo := range list {
domainId := int64(0)
if domainId, err = insertNode(tx, insertDomain, true, schema, domainInfo.Id, domainInfo.Name, domainInfo.Description, 1); err != nil {
return err
last, err := i.insert(tx, domainInfo)
if err != nil {
return errors.WithMessage(err, "")
}
if domainId > lastDomainId {
lastDomainId = domainId
if last.domainId > lastDomainId {
lastDomainId = last.domainId
}
for _, service := range domainInfo.Services {
serviceId := int64(0)
if serviceId, err = insertNode(tx, insertService, true, schema, service.Id, service.Name, service.Description, domainId); err != nil {
return err
}
if serviceId > lastServiceId {
lastServiceId = serviceId
}
for _, app := range service.Apps {
appId := int64(0)
if appId, err = insertNode(tx, insertApp, true, schema, app.Id, app.Name, app.Description, serviceId, app.Type); err != nil {
return err
}
if appId > lastAppId {
lastAppId = appId
}
for _, t := range app.Tokens {
if _, err := insertNode(tx, insertToken, false, schema, t.Token, appId, t.ExpireTime); err != nil {
return err
} else {
idMap := map[string]interface{}{
controller.SystemIdentityFieldInDb: 1,
controller.DomainIdentityFieldInDb: domainId,
controller.ServiceIdentityFieldInDb: serviceId,
controller.ApplicationIdentityFieldInDb: appId,
}
if err := controller.Token.SetIdentityMapForTokenV2(t.Token, t.ExpireTime, idMap); err != nil {
return err
}
}
}
}
if last.serviceId > lastServiceId {
lastServiceId = last.serviceId
}
if last.appId > lastAppId {
lastAppId = last.appId
}
}
if err := setSeq(tx, schema, "domain", lastDomainId); err != nil {
return err
} else if err := setSeq(tx, schema, "service", lastServiceId); err != nil {
return err
} else if err := setSeq(tx, schema, "application", lastAppId); err != nil {
return err
err = i.setSeq(tx, "domain", lastDomainId)
if err != nil {
return errors.WithMessage(err, "set domain")
}
err = i.setSeq(tx, "service", lastServiceId)
if err != nil {
return errors.WithMessage(err, "set service")
}
err = i.setSeq(tx, "application", lastAppId)
if err != nil {
return errors.WithMessage(err, "set application")
}
return nil
}
func Down(tx *sql.Tx) error {
func (i *initializeMigration) Down(tx *sql.Tx) error {
return nil
}
func insertNode(tx *sql.Tx, query string, scan bool, args ...interface{}) (int64, error) {
var id int64
func (i *initializeMigration) insert(tx *sql.Tx, domainInfo domain.DomainWithService) (*identity, error) {
domainId, err := i.insertNode(tx, insertDomain, true, i.schema, domainInfo.Id, domainInfo.Name, domainInfo.Description, 1)
if err != nil {
return nil, errors.WithMessage(err, "insert domain")
}
serviceId := 0
appId := 0
for _, service := range domainInfo.Services {
serviceId, err = i.insertNode(tx, insertService, true, i.schema, service.Id, service.Name, service.Description, domainId)
if err != nil {
return nil, errors.WithMessage(err, "insert service")
}
for _, app := range service.Apps {
appId, err = i.insertNode(tx, insertApp, true, i.schema, app.Id, app.Name, app.Description, serviceId, app.Type)
if err != nil {
return nil, errors.WithMessage(err, "insert application")
}
for _, t := range app.Tokens {
_, err = i.insertNode(tx, insertToken, false, i.schema, t.Token, appId, t.ExpireTime)
if err != nil {
return nil, errors.WithMessage(err, "insert token")
}
err = i.redis.SetApplicationToken(context.Background(), entity.RedisSetToken{
Token: t.Token,
ExpireTime: t.ExpireTime,
DomainIdentity: domainId,
ServiceIdentity: serviceId,
ApplicationIdentity: appId,
})
if err != nil {
return nil, errors.WithMessage(err, "redis set token")
}
}
}
}
return &identity{
domainId: domainId,
appId: appId,
serviceId: serviceId,
}, nil
}
func (i *initializeMigration) insertNode(tx *sql.Tx, query string, scan bool, args ...interface{}) (int, error) {
var id int
query = fmt.Sprintf(query, args...)
row := tx.QueryRow(query)
if scan {
if err := row.Scan(&id); err != nil {
return 0, err
err := row.Scan(&id)
if err != nil {
return 0, errors.WithMessage(err, "row scan")
}
}
return id, nil
}
func setSeq(tx *sql.Tx, schema, table string, value int64) error {
q := fmt.Sprintf(setSeqQuery, schema, table, value)
func (i *initializeMigration) setSeq(tx *sql.Tx, table string, value int) error {
q := fmt.Sprintf(setSeqQuery, i.schema, table, value)
_, err := tx.Exec(q)
if err != nil {
return errors.WithMessage(err, "exec db")
}
return err
return nil
}
@@ -0,0 +1,7 @@
-- +goose Up
UPDATE access_list SET value = false WHERE value is null;
ALTER TABLE access_list
ALTER COLUMN value SET NOT NULL;
-- +goose Down
-62
View File
@@ -24,67 +24,5 @@
]
}
]
},
{
"id": 2,
"name": "citymodule",
"description": "",
"services": [
{
"id": 2,
"name": "citymodule_service",
"description": "",
"apps": [
{
"id": 2,
"name": "cityservice",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_token }}",
"expireTime": -1
}
]
},
{
"id": 3,
"name": "citymodule",
"description": "",
"type": "MOBILE",
"tokens": [
{
"token": "{{ isp_service_citymodule_token }}",
"expireTime": -1
}
]
},
{
"id": 4,
"name": "cityservice_operator_ui",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_operator_ui_token }}",
"expireTime": -1
}
]
},
{
"id": 5,
"name": "cityservice_web_portal",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_cityservice_web_portal_token }}",
"expireTime": -1
}
]
}
]
}
]
}
]
-91
View File
@@ -1,91 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg/v9"
"github.com/go-pg/pg/v9/orm"
"github.com/integration-system/isp-lib/v2/database"
)
type AccessListRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
func (r *AccessListRepository) GetByAppId(appId int32) ([]entity.AccessList, error) {
model := make([]entity.AccessList, 0)
if err := r.getDb().Model(&model).Where("app_id = ?", appId).Select(); err != nil {
if err == pg.ErrNoRows {
return nil, nil
}
return nil, err
}
return model, nil
}
func (r *AccessListRepository) GetByAppIdList(list []int32) ([]entity.AccessList, error) {
model := make([]entity.AccessList, 0)
if err := r.getDb().Model(&model).Where("app_id IN (?)", pg.In(list)).Select(); err != nil {
if err == pg.ErrNoRows {
return nil, nil
}
return nil, err
}
return model, nil
}
func (r *AccessListRepository) DeleteById(id int32) ([]entity.AccessList, error) {
model := make([]entity.AccessList, 0)
if _, err := r.getDb().Model(&model).Where("app_id = ?", id).Returning("*").Delete(); err != nil {
if err == pg.ErrNoRows {
return nil, nil
}
return nil, err
} else {
return model, nil
}
}
func (r *AccessListRepository) DeleteByIdList(list []int32) ([]entity.AccessList, error) {
model := make([]entity.AccessList, 0)
if _, err := r.getDb().Model(&model).Where("app_id IN (?)", pg.In(list)).Returning("*").Delete(); err != nil {
if err == pg.ErrNoRows {
return nil, nil
}
return nil, err
} else {
return model, nil
}
}
func (r *AccessListRepository) UpsertArray(model []entity.AccessList) (int, error) {
_, _ = r.getDb().Model(&model).WherePK().Delete()
if result, err := r.getDb().Model(&model).Insert(); err != nil {
return 0, err
} else {
return result.RowsAffected(), nil
}
}
func (r *AccessListRepository) Upsert(model entity.AccessList) (int, error) {
if result, err := r.getDb().Model(&model).OnConflict("(app_id, method) DO UPDATE").Insert(); err != nil {
return 0, err
} else {
return result.RowsAffected(), nil
}
}
func (r *AccessListRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}
-83
View File
@@ -1,83 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg/v9"
"github.com/go-pg/pg/v9/orm"
"github.com/integration-system/isp-lib/v2/database"
)
var emptyApplication = (*entity.Application)(nil)
type AppRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
func (r *AppRepository) GetApplications(list []int32) ([]entity.Application, error) {
res := make([]entity.Application, 0)
q := r.getDb().Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (r *AppRepository) GetApplicationsByServiceId(serviceId ...int32) ([]entity.Application, error) {
res := make([]entity.Application, 0)
err := r.getDb().Model(&res).Where("service_id IN (?)", pg.In(serviceId)).Order("created_at DESC").Select()
return res, err
}
func (r *AppRepository) CreateApplication(service entity.Application) (entity.Application, error) {
_, err := r.getDb().Model(&service).Insert()
return service, err
}
func (r *AppRepository) GetApplicationByNameAndServiceId(name string, serviceId int32) (*entity.Application, error) {
app := new(entity.Application)
err := r.getDb().Model(app).Where("name = ? AND service_id = ?", name, serviceId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return app, err
}
func (r *AppRepository) UpdateApplication(app entity.Application) (entity.Application, error) {
_, err := r.getDb().Model(&app).Column("name", "description").WherePK().Returning("*").Update()
return app, err
}
func (r *AppRepository) GetApplicationById(id int32) (*entity.Application, error) {
app := &entity.Application{Id: id}
err := r.getDb().Select(app)
if err == pg.ErrNoRows {
return nil, nil
}
return app, err
}
func (r *AppRepository) DeleteApplications(list []int32) (int, error) {
res, err := r.getDb().Model(emptyApplication).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
func (r *AppRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}
-25
View File
@@ -1,25 +0,0 @@
package model
import (
"isp-system-service/log_code"
"github.com/integration-system/isp-lib/v2/database"
log "github.com/integration-system/isp-log"
)
var (
DbClient = database.NewRxDbClient(
database.WithSchemaEnsuring(),
database.WithSchemaAutoInjecting(),
database.WithMigrationsEnsuring(),
database.WithInitializingErrorHandler(func(err *database.ErrorEvent) {
log.Error(log_code.ErrorDatabaseClient, err)
}))
AppRep = AppRepository{rxClient: DbClient}
DomainRep = DomainRepository{rxClient: DbClient}
ServiceRep = ServiceRepository{rxClient: DbClient}
SystemRep = SystemRepository{rxClient: DbClient}
TokenRep = TokenRepository{rxClient: DbClient}
AccessListRep = AccessListRepository{rxClient: DbClient}
)
-83
View File
@@ -1,83 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg/v9"
"github.com/go-pg/pg/v9/orm"
"github.com/integration-system/isp-lib/v2/database"
)
var emptyDomain = (*entity.Domain)(nil)
type DomainRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
func (r *DomainRepository) GetDomains(list []int32) ([]entity.Domain, error) {
res := make([]entity.Domain, 0)
q := r.getDb().Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (r *DomainRepository) GetDomainsBySystemId(systemId int32) ([]entity.Domain, error) {
res := make([]entity.Domain, 0)
err := r.getDb().Model(&res).Where("system_id = ?", systemId).Order("created_at DESC").Select()
return res, err
}
func (r *DomainRepository) CreateDomain(domain entity.Domain) (entity.Domain, error) {
_, err := r.getDb().Model(&domain).Insert()
return domain, err
}
func (r *DomainRepository) GetDomainByNameAndSystemId(name string, systemId int32) (*entity.Domain, error) {
domain := new(entity.Domain)
err := r.getDb().Model(domain).Where("name = ? AND system_id = ?", name, systemId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return domain, err
}
func (r *DomainRepository) UpdateDomain(domain entity.Domain) (entity.Domain, error) {
_, err := r.getDb().Model(&domain).Column("name", "description").WherePK().Returning("*").Update()
return domain, err
}
func (r *DomainRepository) GetDomainById(id int32) (*entity.Domain, error) {
domain := &entity.Domain{Id: id}
err := r.getDb().Select(domain)
if err == pg.ErrNoRows {
return nil, nil
}
return domain, err
}
func (r *DomainRepository) DeleteDomains(list []int32) (int, error) {
res, err := r.getDb().Model(emptyDomain).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
func (r *DomainRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}
-83
View File
@@ -1,83 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg/v9"
"github.com/go-pg/pg/v9/orm"
"github.com/integration-system/isp-lib/v2/database"
)
var emptyService = (*entity.Service)(nil)
type ServiceRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
func (r *ServiceRepository) GetServices(list []int32) ([]entity.Service, error) {
res := make([]entity.Service, 0)
q := r.getDb().Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (r *ServiceRepository) GetServicesByDomainId(domainId ...int32) ([]entity.Service, error) {
res := make([]entity.Service, 0)
err := r.getDb().Model(&res).Where("domain_id IN (?)", pg.In(domainId)).Order("created_at DESC").Select()
return res, err
}
func (r *ServiceRepository) CreateService(service entity.Service) (entity.Service, error) {
_, err := r.getDb().Model(&service).Insert()
return service, err
}
func (r *ServiceRepository) GetServiceByNameAndDomainId(name string, domainId int32) (*entity.Service, error) {
service := new(entity.Service)
err := r.getDb().Model(service).Where("name = ? AND domain_id = ?", name, domainId).First()
if err == pg.ErrNoRows {
return nil, nil
}
return service, err
}
func (r *ServiceRepository) UpdateService(service entity.Service) (entity.Service, error) {
_, err := r.getDb().Model(&service).Column("name", "description").WherePK().Returning("*").Update()
return service, err
}
func (r *ServiceRepository) GetServiceById(id int32) (*entity.Service, error) {
service := &entity.Service{Id: id}
err := r.getDb().Select(service)
if err == pg.ErrNoRows {
return nil, nil
}
return service, err
}
func (r *ServiceRepository) DeleteServices(list []int32) (int, error) {
res, err := r.getDb().Model(emptyService).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
func (r *ServiceRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}
-76
View File
@@ -1,76 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg/v9"
"github.com/go-pg/pg/v9/orm"
"github.com/integration-system/isp-lib/v2/database"
)
var emptySystem = (*entity.System)(nil)
type SystemRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
func (r *SystemRepository) GetSystems(list []int32) ([]entity.System, error) {
res := make([]entity.System, 0)
q := r.getDb().Model(&res)
if len(res) > 0 {
q = q.Where("id IN (?)", pg.In(list))
}
err := q.Order("created_at DESC").Select()
return res, err
}
func (r *SystemRepository) CreateSystem(system entity.System) (entity.System, error) {
_, err := r.getDb().Model(&system).Insert()
return system, err
}
func (r *SystemRepository) GetSystemByName(name string) (*entity.System, error) {
sys := new(entity.System)
err := r.getDb().Model(sys).Where("name = ?", name).First()
if err == pg.ErrNoRows {
return nil, nil
}
return sys, err
}
func (r *SystemRepository) UpdateSystem(system entity.System) (entity.System, error) {
_, err := r.getDb().Model(&system).Column("name", "description").WherePK().Returning("*").Update()
return system, err
}
func (r *SystemRepository) GetSystemById(id int32) (*entity.System, error) {
sys := &entity.System{Id: id}
err := r.getDb().Select(sys)
if err == pg.ErrNoRows {
return nil, nil
}
return sys, err
}
func (r *SystemRepository) DeleteSystems(list []int32) (int, error) {
res, err := r.getDb().Model(emptySystem).Where("id IN (?)", pg.In(list)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
func (r *SystemRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}
-56
View File
@@ -1,56 +0,0 @@
package model
import (
"isp-system-service/entity"
"github.com/go-pg/pg/v9"
"github.com/go-pg/pg/v9/orm"
"github.com/integration-system/isp-lib/v2/database"
)
var emptyToken = (*entity.Token)(nil)
type TokenRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
func (r *TokenRepository) SaveToken(token entity.Token) (entity.Token, error) {
_, err := r.getDb().Model(&token).Insert()
return token, err
}
func (r *TokenRepository) GetTokenById(id string) (*entity.Token, error) {
token := &entity.Token{Token: id}
err := r.getDb().Select(token)
if err == pg.ErrNoRows {
return nil, nil
}
return token, err
}
func (r *TokenRepository) GetTokensByAppId(appId ...int32) ([]entity.Token, error) {
res := make([]entity.Token, 0)
err := r.getDb().Model(&res).Where("app_id IN (?)", pg.In(appId)).Order("created_at DESC").Select()
return res, err
}
func (r *TokenRepository) DeleteTokens(tokens []string) (int, error) {
res, err := r.getDb().Model(emptyToken).Where("token IN (?)", pg.In(tokens)).Delete()
if err != nil {
return 0, err
}
return res.RowsAffected(), nil
}
func (r *TokenRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}
-34
View File
@@ -1,34 +0,0 @@
package redis
import (
"isp-system-service/log_code"
rd "github.com/integration-system/isp-lib/v2/redis"
"github.com/integration-system/isp-lib/v2/structure"
log "github.com/integration-system/isp-log"
)
var Client = &redisClient{
cli: rd.NewRxClient(
rd.WithInitHandler(func(c *rd.Client, err error) {
if err != nil {
log.Fatal(log_code.ErrorRedisClient, err)
}
})),
}
type redisClient struct {
cli *rd.RxClient
}
func (c *redisClient) ReceiveConfiguration(configuration structure.RedisConfiguration) {
c.cli.ReceiveConfiguration(configuration)
}
func (c *redisClient) Get() *rd.RxClient {
return c.cli
}
func (c *redisClient) Close() {
_ = c.cli.Close()
}
+164
View File
@@ -0,0 +1,164 @@
package redis
import (
"context"
"fmt"
"time"
rd "github.com/go-redis/redis/v8"
"github.com/integration-system/isp-lib/v2/redis"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
const (
systemIdentityFieldInDb = "1"
domainIdentityFieldInDb = "2"
serviceIdentityFieldInDb = "3"
applicationIdentityFieldInDb = "4"
)
type Client struct {
instanceUuid string
cli *redis.RxClient
}
func NewClient(instanceUuid string, cli *redis.RxClient) Client {
return Client{
cli: cli,
instanceUuid: instanceUuid,
}
}
func (r Client) SetApplicationToken(ctx context.Context, req entity.RedisSetToken) error {
_, err := r.cli.UseDbTx(redis.ApplicationTokenDb, func(pipeline rd.Pipeliner) error {
idMap := map[string]interface{}{
systemIdentityFieldInDb: domain.DefaultSystemId,
domainIdentityFieldInDb: req.DomainIdentity,
serviceIdentityFieldInDb: req.ServiceIdentity,
applicationIdentityFieldInDb: req.ApplicationIdentity,
}
key := fmt.Sprintf("%s|%s", req.Token, r.instanceUuid)
stat := pipeline.HMSet(ctx, key, idMap)
err := stat.Err()
if err != nil {
return errors.WithMessagef(err, "pipeline hmset")
}
if req.ExpireTime > 0 {
err = pipeline.Expire(ctx, req.Token, time.Duration(req.ExpireTime)*time.Millisecond).Err()
if err != nil {
return errors.WithMessage(err, "pipeline expire token")
}
}
return nil
})
if err != nil {
return errors.WithMessage(err, "application_token transaction")
}
return nil
}
func (r Client) UpdateApplicationPermission(ctx context.Context, req entity.RedisApplicationPermission) error {
_, err := r.cli.UseDb(redis.ApplicationPermissionDb, func(pipeline rd.Pipeliner) error {
key := fmt.Sprintf("%d|%s", req.AppId, req.Method)
_, err := pipeline.Set(ctx, key, req.Value, 0).Result()
if err != nil {
return errors.WithMessage(err, "pipeline set")
}
return nil
})
if err != nil {
return errors.WithMessage(err, "application_permission transaction")
}
return nil
}
func (r Client) UpdateApplicationPermissionList(ctx context.Context, removed []string, added []interface{}) error {
_, err := r.cli.UseDb(redis.ApplicationPermissionDb, func(pipeline rd.Pipeliner) error {
if len(removed) > 0 {
_, err := pipeline.Del(ctx, removed...).Result()
if err != nil {
return errors.WithMessage(err, "pipeline del")
}
}
if len(added) > 0 {
_, err := pipeline.MSet(ctx, added...).Result()
if err != nil {
return errors.WithMessage(err, "pipeline mset")
}
}
return nil
})
if err != nil {
return errors.WithMessage(err, "application_permission transaction")
}
return nil
}
func (r Client) DeleteApplication(ctx context.Context, appTokens []string, applicationPermissionList []string) error {
keys := make([]string, len(appTokens))
for i, token := range appTokens {
keys[i] = fmt.Sprintf("%s|%s", token, r.instanceUuid)
}
_, err := r.cli.UseDbTx(redis.ApplicationTokenDb, func(pipeline rd.Pipeliner) error {
if len(appTokens) > 0 {
_, err := pipeline.Del(ctx, keys...).Result()
if err != nil {
return errors.WithMessage(err, "pipeline del")
}
}
if len(applicationPermissionList) > 0 {
_, err := r.cli.UseDb(redis.ApplicationPermissionDb, func(pipeliner rd.Pipeliner) error {
_, err := pipeliner.Del(ctx, applicationPermissionList...).Result()
if err != nil {
return errors.WithMessage(err, "pipeline del")
}
return nil
})
if err != nil {
return errors.WithMessage(err, "application_permission transaction")
}
}
return nil
})
if err != nil {
return errors.WithMessage(err, "application_token transaction")
}
return nil
}
func (r Client) DeleteToken(ctx context.Context, tokens []string) error {
keys := make([]string, len(tokens))
for i, token := range tokens {
keys[i] = fmt.Sprintf("%s|%s", token, r.instanceUuid)
}
_, err := r.cli.UseDbTx(redis.ApplicationTokenDb, func(p rd.Pipeliner) error {
_, err := p.Del(ctx, keys...).Result()
if err != nil {
return errors.WithMessage(err, "del keys")
}
return nil
})
if err != nil {
return errors.WithMessage(err, "application_token transaction")
}
return nil
}
+133
View File
@@ -0,0 +1,133 @@
package repository
import (
"context"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/entity"
)
type AccessList struct {
db db.DB
}
func NewAccessList(db db.DB) AccessList {
return AccessList{
db: db,
}
}
func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
q := `
SELECT app_id, method, value
FROM access_list
WHERE app_id = $1
`
result := make([]entity.AccessList, 0)
err := r.db.Select(ctx, &result, q, appId)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []int) ([]entity.AccessList, error) {
q, args, err := query.New().
Select("app_id", "method", "value").
From("access_list").
Where(squirrel.Eq{"app_id": appIdList}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.AccessList, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error {
qBuilder := query.New().
Insert("access_list").
Columns("app_id", "method", "value")
for _, e := range entity {
qBuilder = qBuilder.Values(e.AppId, e.Method, e.Value)
}
q, args, err := qBuilder.ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, q, args...)
if err != nil {
return errors.WithMessage(err, "exec db")
}
return nil
}
func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) {
q := `
INSERT INTO access_list
(app_id, method, value)
VALUES ($1, $2, $3)
ON CONFLICT (app_id, method)
DO UPDATE
SET (value) = (SELECT EXCLUDED.value)
`
result, err := r.db.Exec(ctx, q, e.AppId, e.Method, e.Value)
if err != nil {
return 0, errors.WithMessage(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessage(err, "get rows affected")
}
return int(rowsAffected), nil
}
func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []string) error {
q, args, err := query.New().
Delete("access_list").
Where(squirrel.Eq{
"app_id": appId,
"method": methods,
}).
Suffix("RETURNING app_id, method, value").
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, q, args...)
if err != nil {
return errors.WithMessagef(err, "exec db")
}
return nil
}
func (r AccessList) DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
q := `
DELETE FROM access_list
WHERE app_id = $1
RETURNING app_id, method, value
`
result := make([]entity.AccessList, 0)
err := r.db.Select(ctx, &result, q, appId)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
+155
View File
@@ -0,0 +1,155 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Application struct {
db db.DB
}
func NewApplication(db db.DB) Application {
return Application{
db: db,
}
}
func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Application, error) {
q := `
SELECT id, name, description, service_id, type, created_at, updated_at
FROM application
WHERE id = $1
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrApplicationNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) {
q, args, err := query.New().
Select("id", "name", "description", "service_id", "type", "created_at", "updated_at").
From("application").
Where(squirrel.Eq{"id": idList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Application, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Application) GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error) {
q, args, err := query.New().
Select("id", "name", "description", "service_id", "type", "created_at", "updated_at").
From("application").
Where(squirrel.Eq{"service_id": serviceIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Application, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Application) GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error) {
q := `
SELECT id, name, description, service_id, type, created_at, updated_at
FROM application
WHERE name = $1 AND service_id = $2
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, name, serviceId)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (
*entity.Application, error) {
q := `
INSERT INTO application
(name, description, service_id, type)
VALUES ($1, $2, $3, $4)
RETURNING id, name, description, service_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, name, desc, serviceId, appType)
if err != nil {
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) {
q := `
UPDATE application
SET name = $2,
description = $3
WHERE id = $1
RETURNING id, name, description, service_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id, name, description)
if err != nil {
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) {
q, args, err := query.New().
Delete("application").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessage(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessage(err, "get rows affected")
}
return int(rowsAffected), nil
}
+153
View File
@@ -0,0 +1,153 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Domain struct {
db db.DB
}
func NewDomain(db db.DB) Domain {
return Domain{
db: db,
}
}
func (r Domain) GetDomainById(ctx context.Context, id int) (*entity.Domain, error) {
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE id = $1
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.Domain, error) {
q, args, err := query.New().
Select("id", "name", "description", "system_id", "created_at", "updated_at").
From("domain").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Domain, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessage(err, "select db")
}
return result, nil
}
func (r Domain) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) {
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE system_id = $1
ORDER BY created_at DESC
`
result := make([]entity.Domain, 0)
err := r.db.Select(ctx, &result, q, systemId)
if err != nil {
return nil, errors.WithMessage(err, "select db")
}
return result, nil
}
func (r Domain) GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) {
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE name = $1 AND system_id = $2
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, systemId)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) {
q := `
INSERT INTO domain
(name, description, system_id)
VALUES ($1, $2, $3)
RETURNING id, name, description, system_id, created_at, updated_at
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, desc, systemId)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) {
q := `
UPDATE domain
SET name = $1, description = $2
WHERE id = $3
RETURNING id, name, description, system_id, created_at, updated_at
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) {
q, args, err := query.New().
Delete("domain").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
+156
View File
@@ -0,0 +1,156 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Service struct {
db db.DB
}
func NewService(db db.DB) Service {
return Service{
db: db,
}
}
func (r Service) GetServiceById(ctx context.Context, id int) (*entity.Service, error) {
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM service
WHERE id = $1
`
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Service) GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("service").
Where(squirrel.Eq{"id": idList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Service, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Service) GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("service").
Where(squirrel.Eq{"domain_id": domainIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Service, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Service) GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error) {
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM service
WHERE name = $1 AND domain_id = $2
`
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, name, domainId)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select db")
}
return &result, nil
}
func (r Service) CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error) {
q := `
INSERT INTO service
(name, description, domain_id)
VALUES ($1, $2, $3)
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, name, desc, domainId)
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Service) UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error) {
q := `
UPDATE service
SET name = $1, description = $2
WHERE id = $3
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Service) DeleteService(ctx context.Context, idList []int) (int, error) {
q, args, err := query.New().
Delete("service").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
+94
View File
@@ -0,0 +1,94 @@
package repository
import (
"context"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"isp-system-service/entity"
)
type Token struct {
db db.DB
}
func NewToken(db db.DB) Token {
return Token{
db: db,
}
}
func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) {
q := `
INSERT INTO token
(token, app_id, expire_time)
VALUES ($1, $2, $3)
RETURNING token, app_id, expire_time, created_at
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token, appId, expireTime)
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, error) {
q := `
SELECT token, app_id, expire_time, created_at
FROM system
WHERE token = $1
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token)
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) {
q, args, err := query.New().
Select("token", "app_id", "expire_time", "created_at").
From("token").
Where(squirrel.Eq{"app_id": appIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Token, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
q, args, err := query.New().
Delete("token").
Where(squirrel.Eq{"token": tokens}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
+182
View File
@@ -0,0 +1,182 @@
package routes
import (
"github.com/integration-system/isp-kit/cluster"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/grpc/endpoint"
"github.com/integration-system/isp-kit/grpc/isp"
"isp-system-service/controller"
)
type Controllers struct {
AccessList controller.AccessList
Domain controller.Domain
Service controller.Service
Application controller.Application
Token controller.Token
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
return endpointDescriptors(Controllers{})
}
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
muxer := grpc.NewMux()
for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
return muxer
}
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return concatCluster([][]cluster.EndpointDescriptor{
accessListCluster(c),
domainCluster(c),
serviceCluster(c),
applicationCluster(c),
tokenCluster(c),
})
}
func accessListCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/access_list/get_by_id",
Inner: true,
Handler: c.AccessList.GetById,
},
{
Path: "system/access_list/set_one",
Inner: true,
Handler: c.AccessList.SetOne,
},
{
Path: "system/access_list/set_list",
Inner: true,
Handler: c.AccessList.SetList,
},
}
}
func domainCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/domain/get_domains_by_system_id",
Inner: true,
Handler: c.Domain.GetBySystemId,
},
{
Path: "system/domain/create_update_domain",
Inner: true,
Handler: c.Domain.CreateUpdate,
},
{
Path: "system/domain/get_domain_by_id",
Inner: true,
Handler: c.Domain.GetById,
},
{
Path: "system/domain/delete_domains",
Inner: true,
Handler: c.Domain.Delete,
},
}
}
func serviceCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/service/get_service",
Inner: true,
Handler: c.Service.Get,
},
{
Path: "system/service/get_services_by_domain_id",
Inner: true,
Handler: c.Service.GetByDomainId,
},
{
Path: "system/service/create_update_service",
Inner: true,
Handler: c.Service.CreateUpdate,
},
{
Path: "system/service/get_service_by_id",
Inner: true,
Handler: c.Service.GetById,
},
{
Path: "system/service/delete_service",
Inner: true,
Handler: c.Service.Delete,
},
}
}
func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/application/get_applications",
Inner: true,
Handler: c.Application.GetByIdList,
},
{
Path: "system/application/get_applications_by_service_id",
Inner: true,
Handler: c.Application.GetByServiceId,
},
{
Path: "system/application/create_update_application",
Inner: true,
Handler: c.Application.CreateUpdate,
},
{
Path: "system/application/get_application_by_id",
Inner: true,
Handler: c.Application.GetById,
},
{
Path: "system/application/delete_applications",
Inner: true,
Handler: c.Application.Delete,
},
{
Path: "system/application/get_system_tree",
Inner: true,
Handler: c.Application.GetSystemTree,
},
}
}
func tokenCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/token/create_token",
Inner: true,
Handler: c.Token.Create,
},
{
Path: "system/token/revoke_tokens",
Inner: true,
Handler: c.Token.Revoke,
},
{
Path: "system/token/revoke_tokens_for_app",
Inner: true,
Handler: c.Token.RevokeForApp,
},
{
Path: "system/token/get_tokens_by_app_id",
Inner: true,
Handler: c.Token.GetByAppId,
},
}
}
func concatCluster(clusters [][]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
var result []cluster.EndpointDescriptor
for _, c := range clusters {
result = append(result, c...)
}
return result
}
+191
View File
@@ -0,0 +1,191 @@
package service
import (
"context"
"fmt"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IAccessListAccessListRep interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
}
type IAccessListApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
}
type IAccessListSetOneTx interface {
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
}
type IAccessListSetListTx interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error
DeleteAccessList(ctx context.Context, appId int, methods []string) error
DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
}
type IAccessListTxRunner interface {
AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetOneTx) error) error
AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetListTx) error) error
}
type IAccessListRedis interface {
UpdateApplicationPermission(ctx context.Context, req entity.RedisApplicationPermission) error
UpdateApplicationPermissionList(ctx context.Context, removed []string, added []interface{}) error
}
type AccessList struct {
redis IAccessListRedis
tx IAccessListTxRunner
accessListRep IAccessListAccessListRep
applicationRep IAccessListApplicationRep
}
func NewAccessList(
redis IAccessListRedis,
tx IAccessListTxRunner,
accessListRep IAccessListAccessListRep,
applicationRep IAccessListApplicationRep,
) AccessList {
return AccessList{
redis: redis,
tx: tx,
accessListRep: accessListRep,
applicationRep: applicationRep,
}
}
func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error) {
_, err := s.applicationRep.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
accessList, err := s.accessListRep.GetAccessListByAppId(ctx, appId)
if err != nil {
return nil, errors.WithMessagef(err, "get access list by app_id")
}
methodInfos := make([]domain.MethodInfo, len(accessList))
for i, access := range accessList {
methodInfos[i] = domain.MethodInfo{
Method: access.Method,
Value: access.Value,
}
}
return methodInfos, nil
}
func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
_, err := s.applicationRep.GetApplicationById(ctx, request.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
var resp int
err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx IAccessListSetOneTx) error {
resp, err = tx.UpsertAccessList(ctx, entity.AccessList{
AppId: request.AppId,
Method: request.Method,
Value: request.Value,
})
if err != nil {
return errors.WithMessagef(err, "upsert access list")
}
err = s.redis.UpdateApplicationPermission(ctx, entity.RedisApplicationPermission{
AppId: request.AppId,
Method: request.Method,
Value: request.Value,
})
if err != nil {
return errors.WithMessagef(err, "redis update application permission")
}
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "transaction access list set one")
}
return &domain.AccessListSetOneResponse{
Count: resp,
}, nil
}
func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
_, err := s.applicationRep.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
err = s.tx.AccessListSetListTx(ctx, func(ctx context.Context, tx IAccessListSetListTx) error {
oldAccessList := make([]entity.AccessList, 0)
if req.RemoveOld {
oldAccessList, err = tx.DeleteAccessListByAppId(ctx, req.AppId)
if err != nil {
return errors.WithMessage(err, "delete access list by app_id")
}
}
newAccessList := make([]entity.AccessList, len(req.Methods))
updateMethods := make([]string, len(req.Methods))
redisMsetRequest := make([]interface{}, 0)
for i, m := range req.Methods {
updateMethods[i] = m.Method
newAccessList[i] = entity.AccessList{
AppId: req.AppId,
Method: m.Method,
Value: m.Value,
}
redisMsetRequest = append(redisMsetRequest, fmt.Sprintf("%d|%s", req.AppId, m.Method), m.Value)
}
redisDelRequest := make([]string, len(oldAccessList))
for i, access := range oldAccessList {
redisDelRequest[i] = fmt.Sprintf("%d|%s", req.AppId, access.Method)
}
if len(newAccessList) > 0 {
err = tx.DeleteAccessList(ctx, req.AppId, updateMethods)
if err != nil {
return errors.WithMessage(err, "delete access_list")
}
err = tx.InsertArrayAccessList(ctx, newAccessList)
if err != nil {
return errors.WithMessage(err, "insert access_list")
}
}
err = s.redis.UpdateApplicationPermissionList(ctx, redisDelRequest, redisMsetRequest)
if err != nil {
return errors.WithMessage(err, "redis update application permission list")
}
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "transaction access list set list")
}
accessList, err := s.accessListRep.GetAccessListByAppId(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessagef(err, "get access list by app_id")
}
methodInfos := make([]domain.MethodInfo, len(accessList))
for i, access := range accessList {
methodInfos[i] = domain.MethodInfo{
Method: access.Method,
Value: access.Value,
}
}
return methodInfos, nil
}
+329
View File
@@ -0,0 +1,329 @@
package service
import (
"context"
"fmt"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IApplicationApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error)
GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error)
GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error)
CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (*entity.Application, error)
UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error)
}
type IApplicationTokenRep interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
}
type IApplicationServiceRep interface {
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error)
}
type IApplicationDomainRep interface {
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
}
type IApplicationDeleteTx interface {
GetAccessListByAppIdList(ctx context.Context, appIdList []int) ([]entity.AccessList, error)
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error)
}
type IApplicationTxRunner interface {
ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx IApplicationDeleteTx) error) error
}
type IApplicationRedis interface {
DeleteApplication(ctx context.Context, appTokens []string, applicationPermissionList []string) error
}
type Application struct {
redis IApplicationRedis
tx IApplicationTxRunner
applicationRep IApplicationApplicationRep
domainRep IApplicationDomainRep
serviceRep IApplicationServiceRep
tokenRep IApplicationTokenRep
}
func NewApplication(
redis IApplicationRedis,
tx IApplicationTxRunner,
applicationRep IApplicationApplicationRep,
domainRep IApplicationDomainRep,
serviceRep IApplicationServiceRep,
tokenRep IApplicationTokenRep,
) Application {
return Application{
redis: redis,
tx: tx,
applicationRep: applicationRep,
domainRep: domainRep,
serviceRep: serviceRep,
tokenRep: tokenRep,
}
}
func (s Application) GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error) {
application, err := s.applicationRep.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
arr, err := s.EnrichWithTokens(ctx, []entity.Application{*application})
if err != nil {
return nil, errors.WithMessage(err, "enrich application with tokens")
}
return arr[0], nil
}
func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error) {
res, err := s.applicationRep.GetApplicationByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get application by id list")
}
return s.EnrichWithTokens(ctx, res)
}
func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) {
arr, err := s.applicationRep.GetApplicationByServiceIdList(ctx, []int{id})
if err != nil {
return nil, errors.WithMessage(err, "get application by service_id")
}
return s.EnrichWithTokens(ctx, arr)
}
func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) {
domainEntityList, err := s.domainRep.GetDomainBySystemId(ctx, systemId)
if err != nil {
return nil, errors.WithMessage(err, "get domains by system_id")
}
if len(domainEntityList) == 0 {
return []*domain.DomainWithService{}, nil
}
result := make([]*domain.DomainWithService, len(domainEntityList))
resultByDomainId := make(map[int]*domain.DomainWithService, len(domainEntityList))
domainIdList := make([]int, len(domainEntityList))
for i, domainEntity := range domainEntityList {
domainIdList[i] = domainEntity.Id
description := ""
if domainEntity.Description != nil {
description = *domainEntity.Description
}
r := &domain.DomainWithService{
Id: domainEntity.Id,
Name: domainEntity.Name,
Description: description,
Services: make([]*domain.ServiceWithApps, 0),
}
resultByDomainId[domainEntity.Id] = r
result[i] = r
}
serviceEntityList, err := s.serviceRep.GetServiceByDomainId(ctx, domainIdList)
if err != nil {
return nil, errors.WithMessage(err, "get service by domain_id")
}
serviceIdList := make([]int, len(serviceEntityList))
resultServiceByServiceId := make(map[int]*domain.ServiceWithApps, len(serviceEntityList))
for i, serviceEntity := range serviceEntityList {
serviceIdList[i] = serviceEntity.Id
description := ""
if serviceEntity.Description != nil {
description = *serviceEntity.Description
}
resultService := &domain.ServiceWithApps{
Id: serviceEntity.Id,
Name: serviceEntity.Name,
Description: description,
Apps: make([]*domain.ApplicationSimple, 0),
}
r := resultByDomainId[serviceEntity.DomainId]
r.Services = append(r.Services, resultService)
resultServiceByServiceId[serviceEntity.Id] = resultService
}
applicationEntityList, err := s.applicationRep.GetApplicationByServiceIdList(ctx, serviceIdList)
if err != nil {
return nil, errors.WithMessagef(err, "get application by service_id")
}
for _, applicationEntity := range applicationEntityList {
resultService := resultServiceByServiceId[applicationEntity.ServiceId]
description := ""
if applicationEntity.Description != nil {
description = *applicationEntity.Description
}
resultService.Apps = append(resultService.Apps, &domain.ApplicationSimple{
Id: applicationEntity.Id,
Name: applicationEntity.Name,
Type: applicationEntity.Type,
Description: description,
Tokens: make([]domain.Token, 0),
})
}
return result, nil
}
func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
existed, err := s.applicationRep.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
case err != nil:
return nil, errors.WithMessage(err, "get application by name and service_id")
}
_, err = s.serviceRep.GetServiceById(ctx, req.ServiceId)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
}
if req.Id == 0 {
if existed != nil {
return nil, domain.ErrApplicationDuplicateName
}
_, err = s.applicationRep.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId)
if err != nil {
return nil, errors.WithMessage(err, "get application by name and service_id")
}
app, err := s.applicationRep.CreateApplication(ctx, req.Name, req.Description, req.ServiceId, req.Type)
if err != nil {
return nil, errors.WithMessage(err, "create application")
}
result, err := s.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessage(err, "enrich application with tokens")
}
return result[0], nil
}
if existed.Id != req.Id {
return nil, domain.ErrApplicationDuplicateName
}
_, err = s.applicationRep.GetApplicationById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
app, err := s.applicationRep.UpdateApplication(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update application")
}
result, err := s.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessage(err, "enrich application with tokens")
}
return result[0], nil
}
func (s Application) Delete(ctx context.Context, idList []int) (int, error) {
count := 0
err := s.tx.ApplicationDeleteTx(ctx, func(ctx context.Context, tx IApplicationDeleteTx) error {
accessList, err := tx.GetAccessListByAppIdList(ctx, idList)
if err != nil {
return errors.WithMessage(err, "get access list by app_id list")
}
permissionDeleteList := make([]string, 0)
for _, access := range accessList {
permissionDeleteList = append(permissionDeleteList, fmt.Sprintf("%d|%s", access.AppId, access.Method))
}
tokens, err := tx.GetTokenByAppIdList(ctx, idList)
if err != nil {
return errors.WithMessage(err, "get token by app_id list")
}
tokenIdList := make([]string, len(tokens))
for i, t := range tokens {
tokenIdList[i] = t.Token
}
deletedApp, err := tx.DeleteApplicationByIdList(ctx, idList)
if err != nil {
return errors.WithMessage(err, "delete application by id list")
}
err = s.redis.DeleteApplication(ctx, tokenIdList, permissionDeleteList)
if err != nil {
return errors.WithMessage(err, "redis delete application")
}
count = deletedApp
return nil
})
if err != nil {
return 0, errors.WithMessage(err, "transaction application delete")
}
return count, nil
}
func (s Application) EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error) {
if len(apps) == 0 {
return []*domain.ApplicationWithTokens{}, nil
}
appIdList := make([]int, len(apps))
resultByAppId := make(map[int]*domain.ApplicationWithTokens, len(apps))
result := make([]*domain.ApplicationWithTokens, len(apps))
for i, a := range apps {
appIdList[i] = a.Id
awt := &domain.ApplicationWithTokens{
App: s.convertApplication(a),
Tokens: make([]domain.Token, 0),
}
resultByAppId[a.Id] = awt
result[i] = awt
}
tokens, err := s.tokenRep.GetTokenByAppIdList(ctx, appIdList)
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
for _, token := range tokens {
r := resultByAppId[token.AppId]
r.Tokens = append(r.Tokens, domain.Token(token))
}
return result, nil
}
func (s Application) convertApplication(req entity.Application) domain.Application {
desc := ""
if req.Description != nil {
desc = *req.Description
}
return domain.Application{
Id: req.Id,
Name: req.Name,
Description: desc,
ServiceId: req.ServiceId,
Type: req.Type,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
}
+119
View File
@@ -0,0 +1,119 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IDomainDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error)
CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error)
UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error)
DeleteDomain(ctx context.Context, idList []int) (int, error)
}
type Domain struct {
domainRep IDomainDomainRep
}
func NewDomain(
domainRep IDomainDomainRep,
) Domain {
return Domain{
domainRep: domainRep,
}
}
func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) {
domainEntity, err := s.domainRep.GetDomainById(ctx, id)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
result := s.convertDomain(*domainEntity)
return &result, nil
}
func (s Domain) GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error) {
domainEntity, err := s.domainRep.GetDomainBySystemId(ctx, systemId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by system_id")
}
result := make([]domain.Domain, len(domainEntity))
for i := range domainEntity {
result[i] = s.convertDomain(domainEntity[i])
}
return result, nil
}
func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error) {
existed, err := s.domainRep.GetDomainByNameAndSystemId(ctx, req.Name, systemId)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
case err != nil:
return nil, errors.WithMessage(err, "get domain by name and system_id")
}
if req.Id == 0 {
if existed != nil {
return nil, domain.ErrDomainDuplicateName
}
domainEntity, err := s.domainRep.CreateDomain(ctx, req.Name, req.Description, systemId)
if err != nil {
return nil, errors.WithMessagef(err, "create domain")
}
result := s.convertDomain(*domainEntity)
return &result, nil
}
if existed != nil && existed.Id != req.Id {
return nil, domain.ErrDomainDuplicateName
}
_, err = s.domainRep.GetDomainById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
domainEntity, err := s.domainRep.UpdateDomain(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update domain")
}
result := s.convertDomain(*domainEntity)
return &result, nil
}
func (s Domain) Delete(ctx context.Context, idList []int) (int, error) {
result, err := s.domainRep.DeleteDomain(ctx, idList)
if err != nil {
return 0, errors.WithMessage(err, "delete domain")
}
return result, nil
}
func (s Domain) convertDomain(req entity.Domain) domain.Domain {
desc := ""
if req.Description != nil {
desc = *req.Description
}
result := domain.Domain{
Id: req.Id,
Name: req.Name,
Description: desc,
SystemId: req.SystemId,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
return result
}
+37 -29
View File
@@ -3,46 +3,54 @@ package service
import (
"crypto/rand"
"encoding/hex"
mathRand "math/rand"
"time"
"isp-system-service/conf"
"github.com/dgrijalva/jwt-go"
"github.com/integration-system/isp-lib/v2/config"
"github.com/pkg/errors"
)
var Jwt jwtService
type jwtService struct{}
func init() {
mathRand.Seed(time.Now().UnixNano())
type Jwt struct {
secret string
}
func (s jwtService) CreateApplication(appId int32, expTime int64) (string, error) {
var (
claims = jwt.MapClaims{}
created = time.Now()
secret = config.GetRemote().(*conf.RemoteConfig).ApplicationSecret
)
func NewJwt(secret string) Jwt {
return Jwt{
secret: secret,
}
}
claims["appId"] = appId
claims["iat"] = created.Unix()
claims["salt"] = s.getSalt()
if expTime > 0 {
claims["exp"] = created.Add(time.Millisecond * time.Duration(expTime)).Unix()
func (s Jwt) CreateApplicationToken(appId int, expireTime int) (string, error) {
random, err := s.generateSalt()
if err != nil {
return "", errors.WithMessage(err, "generate salt")
}
return jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString([]byte(secret))
created := time.Now().UTC()
claims := jwt.MapClaims{
"appId": appId,
"iat": created.Unix(),
"salt": random,
}
if expireTime > 0 {
claims["exp"] = created.Add(time.Millisecond * time.Duration(expireTime)).Unix()
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS512, claims).
SignedString([]byte(s.secret))
if err != nil {
return "", errors.WithMessage(err, "signed token")
}
return token, nil
}
func (jwtService) getSalt() string {
const randIntSize = 30
const minLen = 10
randomInt := mathRand.Intn(randIntSize) //nolint:gosec
salt := make([]byte, randomInt+minLen)
_, _ = rand.Read(salt)
func (Jwt) generateSalt() (string, error) {
cryptoRand := make([]byte, 16) //nolint:gomnd
_, err := rand.Read(cryptoRand)
if err != nil {
return "", errors.WithMessage(err, "crypto/rand read")
}
random := hex.EncodeToString(cryptoRand)
return hex.EncodeToString(salt)
return random, nil
}
+145
View File
@@ -0,0 +1,145 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IServiceServiceRep interface {
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error)
GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error)
GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error)
CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error)
UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error)
DeleteService(ctx context.Context, idList []int) (int, error)
}
type IServiceDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
}
type Service struct {
domainRep IServiceDomainRep
serviceRep IServiceServiceRep
}
func NewService(
domainRep IServiceDomainRep,
serviceRep IServiceServiceRep,
) Service {
return Service{
domainRep: domainRep,
serviceRep: serviceRep,
}
}
func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) {
serviceEntity, err := s.serviceRep.GetServiceById(ctx, id)
if err != nil {
return nil, errors.WithMessagef(err, "get service by id")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error) {
serviceEntity, err := s.serviceRep.GetServiceByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get system by id list")
}
result := make([]domain.Service, len(serviceEntity))
for i := range serviceEntity {
result[i] = s.convertService(serviceEntity[i])
}
return result, nil
}
func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error) {
serviceEntity, err := s.serviceRep.GetServiceByDomainId(ctx, []int{domainId})
if err != nil {
return nil, errors.WithMessage(err, "get system by id list")
}
result := make([]domain.Service, len(serviceEntity))
for i := range serviceEntity {
result[i] = s.convertService(serviceEntity[i])
}
return result, nil
}
func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
existed, err := s.serviceRep.GetServiceByNameAndDomainId(ctx, req.Name, req.DomainId)
switch {
case errors.Is(err, domain.ErrServiceNotFound):
case err != nil:
return nil, errors.WithMessage(err, "get service by name and domain_id")
}
_, err = s.domainRep.GetDomainById(ctx, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
if req.Id == 0 {
if existed != nil {
return nil, domain.ErrDomainDuplicateName
}
serviceEntity, err := s.serviceRep.CreateService(ctx, req.Name, req.Description, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "create service")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
if existed != nil && existed.Id != req.Id {
return nil, domain.ErrDomainDuplicateName
}
_, err = s.serviceRep.GetServiceById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
}
serviceEntity, err := s.serviceRep.UpdateService(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update service")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
func (s Service) Delete(ctx context.Context, idList []int) (int, error) {
result, err := s.serviceRep.DeleteService(ctx, idList)
if err != nil {
return 0, errors.WithMessage(err, "delete service")
}
return result, nil
}
func (s Service) convertService(req entity.Service) domain.Service {
desc := ""
if req.Description != nil {
desc = *req.Description
}
result := domain.Service{
Id: req.Id,
Name: req.Name,
Description: desc,
DomainId: req.DomainId,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
return result
}
+220
View File
@@ -0,0 +1,220 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type ITokenJwt interface {
CreateApplicationToken(appId int, expireTime int) (string, error)
}
type ITokenAppEnrich interface {
EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error)
}
type ITokenApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
}
type ITokenServiceRep interface {
GetServiceById(ctx context.Context, id int) (*entity.Service, error)
}
type ITokenDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
}
type ITokenTokenRep interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
}
type ITokenCreateTx interface {
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
}
type ITokenRevokeTx interface {
DeleteToken(ctx context.Context, tokens []string) (int, error)
}
type ITokenTxRunner interface {
TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx ITokenCreateTx) error) error
TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx ITokenRevokeTx) error) error
}
type ITokenRedis interface {
SetApplicationToken(ctx context.Context, req entity.RedisSetToken) error
DeleteToken(ctx context.Context, tokens []string) error
}
type Token struct {
redisRep ITokenRedis
defaultExpireTime int
jwt ITokenJwt
appEnrich ITokenAppEnrich
tx ITokenTxRunner
appRep ITokenApplicationRep
domainRep ITokenDomainRep
serviceRep ITokenServiceRep
tokenRep ITokenTokenRep
}
func NewToken(
redisRep ITokenRedis,
defaultExpireTime int,
jwtGenerate ITokenJwt,
appEnrich ITokenAppEnrich,
tx ITokenTxRunner,
appRep ITokenApplicationRep,
domainRep ITokenDomainRep,
serviceRep ITokenServiceRep,
tokenRep ITokenTokenRep,
) Token {
return Token{
redisRep: redisRep,
defaultExpireTime: defaultExpireTime,
appEnrich: appEnrich,
jwt: jwtGenerate,
tx: tx,
appRep: appRep,
domainRep: domainRep,
serviceRep: serviceRep,
tokenRep: tokenRep,
}
}
func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error) {
tokenEntity, err := s.tokenRep.GetTokenByAppIdList(ctx, []int{appId})
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
result := make([]domain.Token, len(tokenEntity))
for i, token := range tokenEntity {
result[i] = domain.Token(token)
}
return result, nil
}
func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
applicationEntity, err := s.appRep.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessagef(err, "get application by id")
}
serviceEntity, err := s.serviceRep.GetServiceById(ctx, applicationEntity.ServiceId)
if err != nil {
return nil, errors.WithMessagef(err, "get service by id")
}
domainEntity, err := s.domainRep.GetDomainById(ctx, serviceEntity.DomainId)
if err != nil {
return nil, errors.WithMessagef(err, "get domain by id")
}
expTime := req.ExpireTimeMs
if expTime == 0 {
expTime = s.defaultExpireTime
}
token, err := s.jwt.CreateApplicationToken(req.AppId, expTime)
if err != nil {
return nil, errors.WithMessagef(err, "jwt create application token")
}
err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx ITokenCreateTx) error {
tokenEntity, err := tx.SaveToken(ctx, token, req.AppId, expTime)
if err != nil {
return errors.WithMessagef(err, "tx save token")
}
err = s.redisRep.SetApplicationToken(ctx, entity.RedisSetToken{
Token: tokenEntity.Token,
ExpireTime: tokenEntity.ExpireTime,
DomainIdentity: domainEntity.Id,
ServiceIdentity: serviceEntity.Id,
ApplicationIdentity: applicationEntity.Id,
})
if err != nil {
return errors.WithMessage(err, "redis set token")
}
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "token create transaction")
}
arr, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*applicationEntity})
if err != nil {
return nil, errors.WithMessagef(err, "application enrich with tokens")
}
return arr[0], nil
}
func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
app, err := s.appRep.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessagef(err, "get application by id")
}
_, err = s.revokeTokens(ctx, req.Tokens)
if err != nil {
return nil, errors.WithMessagef(err, "reboke tokens")
}
res, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessagef(err, "application enrich")
}
return res[0], nil
}
func (s Token) RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error) {
tokens, err := s.tokenRep.GetTokenByAppIdList(ctx, []int{appId})
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
tokenIdList := make([]string, len(tokens))
for i, t := range tokens {
tokenIdList[i] = t.Token
}
return s.revokeTokens(ctx, tokenIdList)
}
func (s Token) revokeTokens(ctx context.Context, tokens []string) (*domain.DeleteResponse, error) {
if len(tokens) == 0 {
return &domain.DeleteResponse{Deleted: 0}, nil
}
var count int
err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx ITokenRevokeTx) error {
deleted, err := tx.DeleteToken(ctx, tokens)
if err != nil {
return errors.WithMessagef(err, "tx delete token")
}
err = s.redisRep.DeleteToken(ctx, tokens)
if err != nil {
return errors.WithMessage(err, "redis delete token")
}
count = deleted
return nil
})
if err != nil {
return nil, errors.WithMessage(err, "token revoke transaction")
}
return &domain.DeleteResponse{
Deleted: count,
}, nil
}
+90
View File
@@ -0,0 +1,90 @@
package transaction
import (
"context"
"github.com/integration-system/isp-kit/db"
"isp-system-service/repository"
"isp-system-service/service"
)
type Manager struct {
db db.Transactional
}
func NewManager(db db.Transactional) *Manager {
return &Manager{
db: db,
}
}
type accessListSetOneTx struct {
repository.AccessList
}
func (m Manager) AccessListSetOneTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IAccessListSetOneTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
accessListRepository := repository.NewAccessList(tx)
return msgTx(ctx, accessListSetOneTx{
AccessList: accessListRepository,
})
})
}
type accessListSetListTx struct {
repository.AccessList
}
func (m Manager) AccessListSetListTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IAccessListSetListTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
accessListRep := repository.NewAccessList(tx)
return msgTx(ctx, accessListSetListTx{
AccessList: accessListRep,
})
})
}
type applicationDeleteTx struct {
repository.AccessList
repository.Application
repository.Token
}
func (m Manager) ApplicationDeleteTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IApplicationDeleteTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
accessListRep := repository.NewAccessList(tx)
applicationRep := repository.NewApplication(tx)
tokenRep := repository.NewToken(tx)
return msgTx(ctx, applicationDeleteTx{
AccessList: accessListRep,
Application: applicationRep,
Token: tokenRep,
})
})
}
type tokenCreateTx struct {
repository.Token
}
func (m Manager) TokenCreateTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ITokenCreateTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
tokenRep := repository.NewToken(tx)
return msgTx(ctx, tokenCreateTx{
Token: tokenRep,
})
})
}
type tokenRevokeTx struct {
repository.Token
}
func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ITokenRevokeTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
tokenRep := repository.NewToken(tx)
return msgTx(ctx, tokenRevokeTx{
Token: tokenRep,
})
})
}