2024-03-26 12:21:52: merge [master:81c5af7538f121910d74b369acc5d0d02259250b];
This commit is contained in:
1 parent
e7ad092001
commit
22a34dbb86
73 files changed
+7649
-1965
No files matched your search
@@ -0,0 +1,95 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"isp-system-service/domain"
|
||||
)
|
||||
|
||||
type AccessListService interface {
|
||||
GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error)
|
||||
SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error)
|
||||
SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error)
|
||||
}
|
||||
|
||||
type AccessList struct {
|
||||
service AccessListService
|
||||
}
|
||||
|
||||
func NewAccessList(service AccessListService) AccessList {
|
||||
return AccessList{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// GetById godoc
|
||||
// @Tags accessList
|
||||
// @Summary Получить список доступности методов для приложения
|
||||
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.Identity false "идентификатор приложения"
|
||||
// @Success 200 {array} domain.MethodInfo "список доступности методов"
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /access_list/get_by_id [POST]
|
||||
func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.MethodInfo, error) {
|
||||
result, err := c.service.GetById(ctx, req.Id)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "application not found")
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// SetOne godoc
|
||||
// @Tags accessList
|
||||
// @Summary Настроить доступность метода для приложения
|
||||
// @Description Возвращает количество измененных строк
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа"
|
||||
// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк"
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /access_list/set_one [POST]
|
||||
func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
|
||||
result, err := c.service.SetOne(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "application not found")
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// SetList godoc
|
||||
// @Tags accessList
|
||||
// @Summary Настроить доступность списка методов для приложения
|
||||
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.AccessListSetListRequest false "объект настройки доступа"
|
||||
// @Success 200 {array} domain.MethodInfo "список доступности методов"
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /access_list/set_list [POST]
|
||||
func (c AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
|
||||
result, err := c.service.SetList(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "application not found")
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
+119
-161
@@ -1,191 +1,149 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"isp-system-service/entity"
|
||||
"isp-system-service/model"
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-lib/database"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"isp-system-service/domain"
|
||||
)
|
||||
|
||||
func GetApplications(list []int32) ([]*AppWithToken, error) {
|
||||
res, err := model.AppRep.GetApplications(list)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return enrichWithTokens(res...)
|
||||
type ApplicationService interface {
|
||||
GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error)
|
||||
GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error)
|
||||
GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error)
|
||||
SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error)
|
||||
CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error)
|
||||
Delete(ctx context.Context, idList []int) (int, error)
|
||||
}
|
||||
|
||||
func GetApplicationsByServiceId(identity Identity) ([]*AppWithToken, error) {
|
||||
arr, err := model.AppRep.GetApplicationsByServiceId(identity.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return enrichWithTokens(arr...)
|
||||
type Application struct {
|
||||
service ApplicationService
|
||||
}
|
||||
|
||||
func CreateUpdateApplication(app entity.Application) (*AppWithToken, error) {
|
||||
existed, err := model.AppRep.GetApplicationByNameAndServiceId(app.Name, app.ServiceId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, e := model.ServiceRep.GetServiceById(app.ServiceId)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if s == nil {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "Service with id %d not found", app.ServiceId)
|
||||
}
|
||||
if app.Id == 0 {
|
||||
if existed != nil {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "Application with name %s already exists", app.Name)
|
||||
}
|
||||
app, e := model.AppRep.CreateApplication(app)
|
||||
enrichWithTokens(app)
|
||||
return &AppWithToken{App: app, Tokens: []entity.Token{}}, e
|
||||
} else {
|
||||
if existed != nil && existed.Id != app.Id {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "Application with name %s already exists", app.Name)
|
||||
}
|
||||
existed, err = model.AppRep.GetApplicationById(app.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existed == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", app.Id)
|
||||
}
|
||||
app, e := model.AppRep.UpdateApplication(app)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
arr, err := enrichWithTokens(app)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return arr[0], nil
|
||||
func NewApplication(service ApplicationService) Application {
|
||||
return Application{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
func GetApplicationById(identity Identity) (*AppWithToken, error) {
|
||||
application, err := model.AppRep.GetApplicationById(identity.Id)
|
||||
if err != nil {
|
||||
// GetById godoc
|
||||
// @Tags application
|
||||
// @Summary Получить приложение по идентификатору
|
||||
// @Description Возвращает описание приложения по его идентификатору
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.Identity true "Идентификатор приложения"
|
||||
// @Success 200 {object} domain.ApplicationWithTokens
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /application/get_application_by_id [POST]
|
||||
func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) {
|
||||
result, err := c.service.GetById(ctx, req.Id)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
if application == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", identity.Id)
|
||||
}
|
||||
arr, err := enrichWithTokens(*application)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return arr[0], nil
|
||||
}
|
||||
|
||||
func DeleteApplications(list []int32) (DeleteResponse, error) {
|
||||
if len(list) == 0 {
|
||||
return DeleteResponse{}, status.Errorf(codes.InvalidArgument, "At least one id are required")
|
||||
}
|
||||
var count = 0
|
||||
err := database.RunInTransaction(func(appRep model.AppRepository, tokenRep model.TokenRepository) error {
|
||||
for _, appId := range list {
|
||||
_, err := revokeTokensForApp(Identity{appId}, &tokenRep)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
res, err := appRep.DeleteApplications(list)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count = res
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return DeleteResponse{}, err
|
||||
}
|
||||
return DeleteResponse{Deleted: count}, nil
|
||||
// GetByIdList godoc
|
||||
// @Tags application
|
||||
// @Summary Получить список приложений
|
||||
// @Description Возвращает массив приложений с токенами по их идентификаторам
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body []integer false "Массив идентификаторов приложений"
|
||||
// @Success 200 {array} domain.ApplicationWithTokens
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /application/get_applications [POST]
|
||||
func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) {
|
||||
return c.service.GetByIdList(ctx, req)
|
||||
}
|
||||
|
||||
func GetSystemTree(md metadata.MD) ([]*DomainWithServices, error) {
|
||||
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
domains, err := model.DomainRep.GetDomainsBySystemId(int32(sysId))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
l := len(domains)
|
||||
if l == 0 {
|
||||
return []*DomainWithServices{}, nil
|
||||
}
|
||||
idList := make([]int32, l)
|
||||
domainsMap := make(map[int32]*DomainWithServices, l)
|
||||
res := make([]*DomainWithServices, l)
|
||||
for i, d := range domains {
|
||||
idList[i] = d.Id
|
||||
dws := &DomainWithServices{Id: d.Id, Name: d.Name, Description: d.Description}
|
||||
domainsMap[d.Id] = dws
|
||||
res[i] = dws
|
||||
}
|
||||
services, err := model.ServiceRep.GetServicesByDomainId(idList...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
l = len(services)
|
||||
idList = make([]int32, l)
|
||||
servicesMap := make(map[int32]*ServiceWithApps, l)
|
||||
for i, s := range services {
|
||||
idList[i] = s.Id
|
||||
d := domainsMap[s.DomainId]
|
||||
swa := &ServiceWithApps{Id: s.Id, Name: s.Name, Description: s.Description}
|
||||
d.Services = append(d.Services, swa)
|
||||
servicesMap[s.Id] = swa
|
||||
}
|
||||
apps, err := model.AppRep.GetApplicationsByServiceId(idList...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, app := range apps {
|
||||
s := servicesMap[app.ServiceId]
|
||||
s.Apps = append(s.Apps, &SimpleApp{Id: app.Id,
|
||||
Name: app.Name,
|
||||
Type: app.Type,
|
||||
Description: app.Description,
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
// GetByServiceId godoc
|
||||
// @Tags application
|
||||
// @Summary Получить список приложений по идентификатору сервиса
|
||||
// @Description Возвращает список приложений по запрошенному идентификатору сервиса
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.Identity true "Идентификатор сервиса"
|
||||
// @Success 200 {array} domain.ApplicationWithTokens
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /application/get_applications_by_service_id [POST]
|
||||
func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) {
|
||||
return c.service.GetByServiceId(ctx, req.Id)
|
||||
}
|
||||
|
||||
func enrichWithTokens(apps ...entity.Application) ([]*AppWithToken, error) {
|
||||
l := len(apps)
|
||||
if len(apps) == 0 {
|
||||
return []*AppWithToken{}, nil
|
||||
// GetSystemTree godoc
|
||||
// @Tags application
|
||||
// @Summary Метод получения системного дерева
|
||||
// @Description Возвращает описание взаимосвязей сервисов и приложений
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.DomainWithService
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /application/get_system_tree [POST]
|
||||
func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithService, error) {
|
||||
return c.service.SystemTree(ctx, domain.DefaultSystemId)
|
||||
}
|
||||
|
||||
// CreateUpdate godoc
|
||||
// @Tags application
|
||||
// @Summary Создать/обновить приложение
|
||||
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
|
||||
// @Success 200 {object} domain.ApplicationWithTokens
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 409 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /application/create_update_application [POST]
|
||||
func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
|
||||
result, err := c.service.CreateUpdate(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrServiceNotFound):
|
||||
return nil, status.Errorf(codes.InvalidArgument, "service with id %d not found", req.ServiceId)
|
||||
case errors.Is(err, domain.ErrApplicationDuplicateName):
|
||||
return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name)
|
||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", req.Id)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
idList := make([]int32, l)
|
||||
appMap := make(map[int32]*AppWithToken, l)
|
||||
enriched := make([]*AppWithToken, l)
|
||||
for i, a := range apps {
|
||||
idList[i] = a.Id
|
||||
awt := &AppWithToken{App: a}
|
||||
appMap[a.Id] = awt
|
||||
enriched[i] = awt
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Tags application
|
||||
// @Summary Удалить приложения
|
||||
// @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body []integer false "Массив идентификаторов приложений"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /application/delete_applications [POST]
|
||||
func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
|
||||
if len(req) == 0 {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "At least one id are required")
|
||||
}
|
||||
tokens, err := model.TokenRep.GetTokensByAppId(idList...)
|
||||
|
||||
result, err := c.service.Delete(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, v := range tokens {
|
||||
app := appMap[v.AppId]
|
||||
app.Tokens = append(app.Tokens, v)
|
||||
}
|
||||
return enriched, nil
|
||||
|
||||
return &domain.DeleteResponse{
|
||||
Deleted: result,
|
||||
}, nil
|
||||
}
|
||||
+97
-68
@@ -1,87 +1,116 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"isp-system-service/entity"
|
||||
"isp-system-service/model"
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"isp-system-service/domain"
|
||||
)
|
||||
|
||||
/*func GetDomains(list []int32) ([]entity.Domain, error) {
|
||||
res, err := model.DomainRep.GetDomains(list)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, nil
|
||||
}*/
|
||||
|
||||
func GetDomainsBySystemId(md metadata.MD) ([]entity.Domain, error) {
|
||||
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return model.DomainRep.GetDomainsBySystemId(int32(sysId))
|
||||
type DomainService interface {
|
||||
GetById(ctx context.Context, id int) (*domain.Domain, error)
|
||||
GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error)
|
||||
CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error)
|
||||
Delete(ctx context.Context, idList []int) (int, error)
|
||||
}
|
||||
|
||||
func CreateUpdateDomain(domain entity.Domain, md metadata.MD) (*entity.Domain, error) {
|
||||
existed, err := model.DomainRep.GetDomainByNameAndSystemId(domain.Name, domain.SystemId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type Domain struct {
|
||||
service DomainService
|
||||
}
|
||||
|
||||
sysId, err := utils.ResolveMetadataIdentity(utils.SystemIdHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
domain.SystemId = int32(sysId)
|
||||
|
||||
sys, e := model.SystemRep.GetSystemById(domain.SystemId)
|
||||
if e != nil {
|
||||
return nil, err
|
||||
}
|
||||
if sys == nil {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "System with id %d not found", domain.SystemId)
|
||||
}
|
||||
if domain.Id == 0 {
|
||||
if existed != nil {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "Domain with name %s already exists", domain.Name)
|
||||
}
|
||||
domain, e := model.DomainRep.CreateDomain(domain)
|
||||
return &domain, e
|
||||
} else {
|
||||
if existed != nil && existed.Id != domain.Id {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "Domain with name %s already exists", domain.Name)
|
||||
}
|
||||
existed, err = model.DomainRep.GetDomainById(domain.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existed == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", domain.Id)
|
||||
}
|
||||
domain, e := model.DomainRep.UpdateDomain(domain)
|
||||
return &domain, e
|
||||
func NewDomain(service DomainService) Domain {
|
||||
return Domain{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
func GetDomainById(identity Identity) (*entity.Domain, error) {
|
||||
domain, err := model.DomainRep.GetDomainById(identity.Id)
|
||||
// GetById godoc
|
||||
// @Tags domain
|
||||
// @Summary Получить домен по идентификатору
|
||||
// @Description Возвращает описание домена по его идентификатору
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.Identity true "Идентификатор домена"
|
||||
// @Success 200 {object} domain.Domain
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /domain/get_domain_by_id [POST]
|
||||
func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domain, error) {
|
||||
result, err := c.service.GetById(ctx, req.Id)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrDomainNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// GetBySystemId godoc
|
||||
// @Tags domain
|
||||
// @Summary Получить домены по идентификатору системы
|
||||
// @Description Возвращает список доменов по системному идентификатору
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body integer false "Идентификатор системы"
|
||||
// @Success 200 {array} domain.Domain
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /domain/get_domains_by_system_id [POST]
|
||||
func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) {
|
||||
return c.service.GetBySystemId(ctx, domain.DefaultSystemId)
|
||||
}
|
||||
|
||||
// CreateUpdate godoc
|
||||
// @Tags domain
|
||||
// @Summary Создать/обновить домен
|
||||
// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.DomainCreateUpdateRequest true "Объект домена"
|
||||
// @Success 200 {object} domain.Domain
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /domain/create_update_domain [POST]
|
||||
func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest) (*domain.Domain, error) {
|
||||
result, err := c.service.CreateUpdate(ctx, req, domain.DefaultSystemId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSystemNotFound):
|
||||
return nil, status.Errorf(codes.InvalidArgument, "system with id %d not found", domain.DefaultSystemId)
|
||||
case errors.Is(err, domain.ErrDomainNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
|
||||
case errors.Is(err, domain.ErrDomainDuplicateName):
|
||||
return nil, status.Errorf(codes.AlreadyExists, "domain with name %s already exists", req.Name)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Tags domain
|
||||
// @Summary Удаление доменов
|
||||
// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body []integer false "Массив идентификаторов доменов"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /domain/delete_domains [POST]
|
||||
func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
|
||||
if len(req) == 0 {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "at least one id are required")
|
||||
}
|
||||
|
||||
result, err := c.service.Delete(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if domain == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", identity.Id)
|
||||
}
|
||||
return domain, err
|
||||
}
|
||||
|
||||
func DeleteDomains(list []int32) (DeleteResponse, error) {
|
||||
if len(list) == 0 {
|
||||
return DeleteResponse{Deleted: 0}, status.Errorf(codes.InvalidArgument, "At least one id are required")
|
||||
}
|
||||
res, err := model.DomainRep.DeleteDomains(list)
|
||||
return DeleteResponse{Deleted: res}, err
|
||||
return &domain.DeleteResponse{
|
||||
Deleted: result,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-system-service/domain"
|
||||
)
|
||||
|
||||
type SecureService interface {
|
||||
Authenticate(ctx context.Context, token string) (*domain.AuthData, error)
|
||||
Authorize(ctx context.Context, appId int, endpoint string) (bool, error)
|
||||
}
|
||||
|
||||
type Secure struct {
|
||||
service SecureService
|
||||
}
|
||||
|
||||
func NewSecure(service SecureService) Secure {
|
||||
return Secure{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Authenticate godoc
|
||||
// @Tags secure
|
||||
// @Summary Метод аутентификации токена
|
||||
// @Description Проверяет наличие токена в системе,
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.AuthenticateRequest true "Тело запроса"
|
||||
// @Success 200 {array} domain.AuthenticateResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authenticate [POST]
|
||||
func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest) (*domain.AuthenticateResponse, error) {
|
||||
result, err := c.service.Authenticate(ctx, req.Token)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrTokenNotFound):
|
||||
return &domain.AuthenticateResponse{
|
||||
Authenticated: false,
|
||||
ErrorReason: domain.ErrTokenNotFound.Error(),
|
||||
}, nil
|
||||
case errors.Is(err, domain.ErrTokenExpired):
|
||||
return &domain.AuthenticateResponse{
|
||||
Authenticated: false,
|
||||
ErrorReason: domain.ErrTokenExpired.Error(),
|
||||
}, nil
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "authenticate")
|
||||
default:
|
||||
return &domain.AuthenticateResponse{
|
||||
Authenticated: true,
|
||||
AuthData: result,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Authorize godoc
|
||||
// @Tags secure
|
||||
// @Summary Метод авторизации приложения
|
||||
// @Description Проверяет доступ приложения к запрашиваемому ендпоинту
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.AuthorizeRequest true "Тело запрос"
|
||||
// @Success 200 {array} domain.AuthorizeResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authorize [POST]
|
||||
func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) {
|
||||
result, err := c.service.Authorize(ctx, req.ApplicationId, req.Endpoint)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAccessListNotFound):
|
||||
return &domain.AuthorizeResponse{
|
||||
Authorized: false,
|
||||
}, nil
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "authorize")
|
||||
default:
|
||||
return &domain.AuthorizeResponse{
|
||||
Authorized: result,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
+116
-56
@@ -1,74 +1,134 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"isp-system-service/entity"
|
||||
"isp-system-service/model"
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"isp-system-service/domain"
|
||||
)
|
||||
|
||||
func GetService(list []int32) ([]entity.Service, error) {
|
||||
res, err := model.ServiceRep.GetServices(list)
|
||||
if err != nil {
|
||||
return res, err
|
||||
type ServiceService interface {
|
||||
GetById(ctx context.Context, id int) (*domain.Service, error)
|
||||
GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error)
|
||||
GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error)
|
||||
CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error)
|
||||
Delete(ctx context.Context, idList []int) (int, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
service ServiceService
|
||||
}
|
||||
|
||||
func NewService(service ServiceService) Service {
|
||||
return Service{
|
||||
service: service,
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func GetServicesByDomainId(identity Identity) ([]entity.Service, error) {
|
||||
return model.ServiceRep.GetServicesByDomainId(identity.Id)
|
||||
// GetById godoc
|
||||
// @Tags service
|
||||
// @Summary Получить сервис по идентификатору
|
||||
// @Description Возвращает описание сервиса по его идентификатору
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.Identity true "Идентификатор сервиса"
|
||||
// @Success 200 {object} domain.Service
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /service/get_service_by_id [POST]
|
||||
func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) {
|
||||
result, err := c.service.GetById(ctx, req.Id)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrServiceNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
func CreateUpdateService(service entity.Service) (*entity.Service, error) {
|
||||
existed, err := model.ServiceRep.GetServiceByNameAndDomainId(service.Name, service.DomainId)
|
||||
// Get godoc
|
||||
// @Tags service
|
||||
// @Summary Получить список сервисов
|
||||
// @Description Возвращает список сервисов по их идентификаторам
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body []integer false "Массив идентификаторов сервисов"
|
||||
// @Success 200 {array} domain.Service
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /service/get_service [POST]
|
||||
func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) {
|
||||
return c.service.GetByIdList(ctx, req)
|
||||
}
|
||||
|
||||
// GetByDomainId godoc
|
||||
// @Tags service
|
||||
// @Summary Получить список сервисов по идентификатору домена
|
||||
// @Description Возвращает список сервисов по идентификатору домена
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.Identity true "Идентификатор домена"
|
||||
// @Success 200 {array} domain.Service
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /service/get_services_by_domain_id [POST]
|
||||
func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.Service, error) {
|
||||
return c.service.GetByDomainId(ctx, req.Id)
|
||||
}
|
||||
|
||||
// CreateUpdate godoc
|
||||
// @Tags service
|
||||
// @Summary Создать/обновить сервис
|
||||
// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса"
|
||||
// @Success 200 {object} domain.Service
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 409 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /service/create_update_service [POST]
|
||||
func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
|
||||
result, err := c.service.CreateUpdate(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrDomainNotFound):
|
||||
return nil, status.Errorf(codes.InvalidArgument, "domain with id %d not found", req.DomainId)
|
||||
case errors.Is(err, domain.ErrServiceNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
|
||||
case errors.Is(err, domain.ErrServiceDuplicateName):
|
||||
return nil, status.Errorf(codes.AlreadyExists, "service with name %s already exists", req.Name)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Tags service
|
||||
// @Summary Удалить сервисы
|
||||
// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body []integer true "Массив идентификаторов сервисов"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /service/delete_service [POST]
|
||||
func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
|
||||
if len(req) == 0 {
|
||||
return nil, status.Error(codes.InvalidArgument, "at least one id are required")
|
||||
}
|
||||
|
||||
result, err := c.service.Delete(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
domain, e := model.DomainRep.GetDomainById(service.DomainId)
|
||||
if e != nil {
|
||||
return nil, err
|
||||
}
|
||||
if domain == nil {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "Domain with id %d not found", service.DomainId)
|
||||
}
|
||||
if service.Id == 0 {
|
||||
if existed != nil {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "Service with name %s already exists", service.Name)
|
||||
}
|
||||
service, e := model.ServiceRep.CreateService(service)
|
||||
return &service, e
|
||||
} else {
|
||||
if existed != nil && existed.Id != service.Id {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "Service with name %s already exists", service.Name)
|
||||
}
|
||||
existed, err = model.ServiceRep.GetServiceById(service.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existed == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", service.Id)
|
||||
}
|
||||
service, e := model.ServiceRep.UpdateService(service)
|
||||
return &service, e
|
||||
}
|
||||
}
|
||||
|
||||
func GetServiceById(identity Identity) (*entity.Service, error) {
|
||||
service, err := model.ServiceRep.GetServiceById(identity.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if service == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", identity.Id)
|
||||
}
|
||||
return service, err
|
||||
}
|
||||
|
||||
func DeleteService(list []int32) (DeleteResponse, error) {
|
||||
if len(list) == 0 {
|
||||
return DeleteResponse{Deleted: 0}, status.Error(codes.InvalidArgument, "At least one id are required")
|
||||
}
|
||||
res, err := model.ServiceRep.DeleteServices(list)
|
||||
return DeleteResponse{Deleted: res}, err
|
||||
return &domain.DeleteResponse{
|
||||
Deleted: result,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"isp-system-service/entity"
|
||||
)
|
||||
|
||||
type DeleteResponse struct {
|
||||
Deleted int
|
||||
}
|
||||
|
||||
type Identity struct {
|
||||
Id int32 `json:"id" valid:"required~Required"`
|
||||
}
|
||||
|
||||
type AppWithToken struct {
|
||||
App entity.Application
|
||||
Tokens []entity.Token
|
||||
}
|
||||
|
||||
type SimpleApp struct {
|
||||
Id int32
|
||||
Name string
|
||||
Description string
|
||||
Type string
|
||||
Tokens []entity.Token
|
||||
}
|
||||
|
||||
type ServiceWithApps struct {
|
||||
Id int32
|
||||
Name string
|
||||
Description string
|
||||
Apps []*SimpleApp
|
||||
}
|
||||
|
||||
type DomainWithServices struct {
|
||||
Id int32
|
||||
Name string
|
||||
Description string
|
||||
Services []*ServiceWithApps
|
||||
}
|
||||
|
||||
type RevokeTokensRequest struct {
|
||||
AppId int32 `valid:"required~Required"`
|
||||
Tokens []string
|
||||
}
|
||||
type CreateTokenRequest struct {
|
||||
AppId int32 `valid:"required~Required"`
|
||||
ExpireTimeMs int64
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"isp-system-service/entity"
|
||||
"isp-system-service/model"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func GetSystems(list []int32) ([]entity.System, error) {
|
||||
res, err := model.SystemRep.GetSystems(list)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func CreateUpdateSystem(system entity.System) (*entity.System, error) {
|
||||
existed, err := model.SystemRep.GetSystemByName(system.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if system.Id == 0 {
|
||||
if existed != nil {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "System with name %s already exists", system.Name)
|
||||
}
|
||||
sys, e := model.SystemRep.CreateSystem(system)
|
||||
return &sys, e
|
||||
} else {
|
||||
if existed != nil && existed.Id != system.Id {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "System with name %s already exists", system.Name)
|
||||
}
|
||||
existed, err = model.SystemRep.GetSystemById(system.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existed == nil {
|
||||
return nil, status.Error(codes.NotFound, fmt.Sprintf("System with id %d not found", system.Id))
|
||||
}
|
||||
sys, e := model.SystemRep.UpdateSystem(system)
|
||||
return &sys, e
|
||||
}
|
||||
}
|
||||
|
||||
func GetSystemById(identity Identity) (*entity.System, error) {
|
||||
sys, err := model.SystemRep.GetSystemById(identity.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if sys == nil {
|
||||
return nil, status.Error(codes.NotFound, fmt.Sprintf("System with id %d not found", identity.Id))
|
||||
}
|
||||
return sys, err
|
||||
}
|
||||
|
||||
func DeleteSystems(list []int32) (DeleteResponse, error) {
|
||||
if len(list) == 0 {
|
||||
return DeleteResponse{}, status.Error(codes.InvalidArgument, "At least one id are required")
|
||||
}
|
||||
res, err := model.SystemRep.DeleteSystems(list)
|
||||
return DeleteResponse{Deleted: res}, err
|
||||
}
|
||||
+78
-189
@@ -1,206 +1,95 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"time"
|
||||
"context"
|
||||
|
||||
"isp-system-service/conf"
|
||||
"isp-system-service/entity"
|
||||
"isp-system-service/model"
|
||||
|
||||
"fmt"
|
||||
"github.com/go-redis/redis"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
"github.com/integration-system/isp-lib/redis"
|
||||
"github.com/integration-system/isp-lib/token-gen"
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"isp-system-service/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
SystemIdentityFieldInDb = "1"
|
||||
DomainIdentityFieldInDb = "2"
|
||||
ServiceIdentityFieldInDb = "3"
|
||||
ApplicationIdentityFieldInDb = "4"
|
||||
)
|
||||
|
||||
var (
|
||||
generator = tg.NewGenerator(tg.DefaultAlphabet)
|
||||
)
|
||||
|
||||
type BoolResponse struct {
|
||||
Ok bool
|
||||
type ITokenService interface {
|
||||
GetByAppId(ctx context.Context, appId int) ([]domain.Token, error)
|
||||
Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error)
|
||||
Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error)
|
||||
RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error)
|
||||
}
|
||||
|
||||
func CreateToken(req CreateTokenRequest) (*AppWithToken, error) {
|
||||
m, err, app := GetIdMap(req.AppId)
|
||||
if err != nil {
|
||||
type Token struct {
|
||||
service ITokenService
|
||||
}
|
||||
|
||||
func NewToken(service ITokenService) Token {
|
||||
return Token{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// GetByAppId godoc
|
||||
// @Tags token
|
||||
// @Summary Получить токены по идентификатору приложения
|
||||
// @Description Возвращает список токенов, привязанных к приложению
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.Identity true "Идентификатор приложения"
|
||||
// @Success 200 {array} entity.Token
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /token/get_tokens_by_app_id [POST]
|
||||
func (c Token) GetByAppId(ctx context.Context, req domain.Identity) ([]domain.Token, error) {
|
||||
return c.service.GetByAppId(ctx, req.Id)
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Tags token
|
||||
// @Summary Создать токен
|
||||
// @Description Создает токен и привязывает его к приложению
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.TokenCreateRequest true "Объект создания токена"
|
||||
// @Success 200 {object} domain.ApplicationWithTokens
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /token/create_token [POST]
|
||||
func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
|
||||
result, err := c.service.Create(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrApplicationNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.AppId)
|
||||
case errors.Is(err, domain.ErrServiceNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "service for app_id id %d not found", req.AppId)
|
||||
case errors.Is(err, domain.ErrDomainNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "domain for app_id %d not found", req.AppId)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
|
||||
var id string
|
||||
var existed = true
|
||||
for existed {
|
||||
id = generator.Next(tg.DefaultTokenLength)
|
||||
t, err := model.TokenRep.GetTokenById(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
existed = t != nil
|
||||
}
|
||||
|
||||
expTime := req.ExpireTimeMs
|
||||
if expTime == 0 {
|
||||
expTime = cfg.DefaultTokenExpireTime
|
||||
}
|
||||
token := entity.Token{
|
||||
Token: id,
|
||||
ExpireTime: expTime,
|
||||
AppId: req.AppId,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
c := rd.GetClient()
|
||||
err = SetIdentityMapForToken(token, m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
token, err = model.TokenRep.SaveToken(token)
|
||||
if err != nil {
|
||||
c.Del(token.Token)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
arr, err := enrichWithTokens(*app)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return arr[0], nil
|
||||
}
|
||||
|
||||
func RevokeTokens(req RevokeTokensRequest) (*AppWithToken, error) {
|
||||
app, err := model.AppRep.GetApplicationById(req.AppId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = revokeTokens(req.Tokens, &model.TokenRep)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := enrichWithTokens(*app)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res[0], nil
|
||||
// Revoke godoc
|
||||
// @Tags token
|
||||
// @Summary Отозвать токены
|
||||
// @Description Отвязывает токены от приложений и удаляет их
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов"
|
||||
// @Success 200 {object} domain.ApplicationWithTokens
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /token/revoke_tokens [POST]
|
||||
func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
|
||||
return c.service.Revoke(ctx, req)
|
||||
}
|
||||
|
||||
func RevokeTokensForApp(identity Identity) (*DeleteResponse, error) {
|
||||
return revokeTokensForApp(identity, &model.TokenRep)
|
||||
}
|
||||
|
||||
func GetTokensByAppId(identity Identity) ([]entity.Token, error) {
|
||||
return model.TokenRep.GetTokensByAppId(identity.Id)
|
||||
}
|
||||
|
||||
func SetIdentityMapForTokenV2(token string, expireTime int64, idMap map[string]interface{}) error {
|
||||
c := rd.GetClient()
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
_, e := c.UseDbTx(rd.ApplicationTokenDb, func(p redis.Pipeliner) error {
|
||||
t := fmt.Sprintf("%s|%s", token, cfg.InstanceUuid)
|
||||
stat := p.HMSet(t, idMap)
|
||||
err := stat.Err()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if expireTime > 0 {
|
||||
err = p.Expire(token, time.Duration(expireTime)*time.Millisecond).Err()
|
||||
}
|
||||
return err
|
||||
})
|
||||
return e
|
||||
}
|
||||
|
||||
func SetIdentityMapForToken(token entity.Token, idMap map[string]interface{}) error {
|
||||
return SetIdentityMapForTokenV2(token.Token, token.ExpireTime, idMap)
|
||||
}
|
||||
|
||||
func GetIdMap(appId int32) (map[string]interface{}, error, *entity.Application) {
|
||||
app, err := model.AppRep.GetApplicationById(appId)
|
||||
if err != nil {
|
||||
return nil, err, nil
|
||||
}
|
||||
if app == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", appId), nil
|
||||
}
|
||||
|
||||
service, err := model.ServiceRep.GetServiceById(app.ServiceId)
|
||||
if err != nil {
|
||||
return nil, err, app
|
||||
}
|
||||
if service == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", app.ServiceId), app
|
||||
}
|
||||
|
||||
domain, err := model.DomainRep.GetDomainById(service.DomainId)
|
||||
if err != nil {
|
||||
return nil, err, app
|
||||
}
|
||||
if domain == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", service.DomainId), app
|
||||
}
|
||||
|
||||
system, err := model.SystemRep.GetSystemById(domain.SystemId)
|
||||
if err != nil {
|
||||
return nil, err, app
|
||||
}
|
||||
if system == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "System with id %d not found", domain.SystemId), app
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
SystemIdentityFieldInDb: system.Id,
|
||||
DomainIdentityFieldInDb: domain.Id,
|
||||
ServiceIdentityFieldInDb: service.Id,
|
||||
ApplicationIdentityFieldInDb: app.Id,
|
||||
}, nil, app
|
||||
}
|
||||
|
||||
func revokeTokensForApp(identity Identity, tokenRep *model.TokenRepository) (*DeleteResponse, error) {
|
||||
tokens, err := GetTokensByAppId(identity)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := len(tokens)
|
||||
if l == 0 {
|
||||
return &DeleteResponse{0}, nil
|
||||
}
|
||||
tokenIdList := make([]string, l)
|
||||
for i, t := range tokens {
|
||||
tokenIdList[i] = t.Token
|
||||
}
|
||||
return revokeTokens(tokenIdList, tokenRep)
|
||||
}
|
||||
|
||||
func revokeTokens(tokens []string, tokenRep *model.TokenRepository) (*DeleteResponse, error) {
|
||||
var count = 0
|
||||
if len(tokens) == 0 {
|
||||
return &DeleteResponse{0}, nil
|
||||
}
|
||||
c := rd.GetClient()
|
||||
_, e := c.UseDbTx(rd.ApplicationTokenDb, func(p redis.Pipeliner) error {
|
||||
deleted, err := tokenRep.DeleteTokens(tokens)
|
||||
count = deleted
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res := p.Del(tokens...)
|
||||
return res.Err()
|
||||
})
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return &DeleteResponse{count}, nil
|
||||
// RevokeForApp godoc
|
||||
// @Tags token
|
||||
// @Summary Отозвать токены для приложения
|
||||
// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.Identity true "Идентификатор приложения"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /token/revoke_tokens_for_app [POST]
|
||||
func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) {
|
||||
return c.service.RevokeByAppId(ctx, req.Id)
|
||||
}
|
||||
Reference in new issue
Block a user