From 9d79063c9d6d230cb6498e843bfc4abe5c63350e Mon Sep 17 00:00:00 2001 From: "boweian@creditease.cn" Date: Thu, 6 Jun 2024 10:27:33 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/service/service_start.go | 31 +- src/pkg/sysauth/endpoint.go | 286 ++++++++++++++++++ src/pkg/sysauth/http.go | 504 +++++++++++++++++++++++++++++++ src/pkg/sysauth/logging.go | 207 +++++++++++++ src/pkg/sysauth/middleware.go | 3 + src/pkg/sysauth/service.go | 435 ++++++++++++++++++++++++++ src/pkg/sysauth/service_test.go | 33 ++ src/pkg/sysauth/tracing.go | 228 ++++++++++++++ src/pkg/sysauth/types.go | 115 +++++++ src/repository/auth/logging.go | 215 ++++++++++--- src/repository/auth/service.go | 61 ++-- src/repository/auth/tracing.go | 246 ++++++++++++--- src/repository/model/logging.go | 456 ++++++++++++++++++++-------- src/repository/model/service.go | 11 +- src/repository/model/tracing.go | 425 +++++++++++++++++++++----- src/repository/tenant/logging.go | 90 +++++- src/repository/tenant/service.go | 9 + src/repository/tenant/tracing.go | 89 +++++- 18 files changed, 3116 insertions(+), 328 deletions(-) create mode 100644 src/pkg/sysauth/endpoint.go create mode 100644 src/pkg/sysauth/http.go create mode 100644 src/pkg/sysauth/logging.go create mode 100644 src/pkg/sysauth/middleware.go create mode 100644 src/pkg/sysauth/service.go create mode 100644 src/pkg/sysauth/service_test.go create mode 100644 src/pkg/sysauth/tracing.go create mode 100644 src/pkg/sysauth/types.go diff --git a/cmd/service/service_start.go b/cmd/service/service_start.go index dd43252..ff5a29c 100644 --- a/cmd/service/service_start.go +++ b/cmd/service/service_start.go @@ -4,6 +4,17 @@ import ( "context" "embed" "fmt" + "io/fs" + "net" + "net/http" + "net/http/httputil" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + "time" + tiktoken2 "github.com/IceBearAI/aigc/src/helpers/tiktoken" "github.com/IceBearAI/aigc/src/pkg/assistants" "github.com/IceBearAI/aigc/src/pkg/auth" @@ -16,22 +27,13 @@ import ( "github.com/IceBearAI/aigc/src/pkg/modelevaluate" "github.com/IceBearAI/aigc/src/pkg/models" "github.com/IceBearAI/aigc/src/pkg/sys" + "github.com/IceBearAI/aigc/src/pkg/sysauth" "github.com/IceBearAI/aigc/src/pkg/terminal" "github.com/IceBearAI/aigc/src/pkg/tools" "github.com/IceBearAI/aigc/src/repository/types" "github.com/igm/sockjs-go/v3/sockjs" "github.com/pkoukk/tiktoken-go" "github.com/tmc/langchaingo/llms/openai" - "io/fs" - "net" - "net/http" - "net/http/httputil" - "os" - "os/signal" - "strconv" - "strings" - "syscall" - "time" "github.com/go-kit/kit/tracing/opentracing" @@ -66,9 +68,9 @@ aigc-server start -p :8080 return err } - _ = generateTable() // 判断是否需要初始化数据,如果没有则初始化数据 if !gormDB.Migrator().HasTable(types.Accounts{}) { + _ = generateTable() if err = initData(); err != nil { _ = level.Error(logger).Log("cmd.start.PreRunE", "initData", "err", err.Error()) return err @@ -107,6 +109,7 @@ aigc-server start -p :8080 assistantsSvc assistants.Service modelEvaluateSvc modelevaluate.Service terminalSvc terminal.Service + sysauthSvc sysauth.Service ) func start(ctx context.Context) (err error) { @@ -183,6 +186,8 @@ func start(ctx context.Context) (err error) { datasetTaskSvc = datasettask.NewLogging(logger, logging.TraceId)(datasetTaskSvc) modelEvaluateSvc = modelevaluate.NewLogging(logger, logging.TraceId)(modelEvaluateSvc) terminalSvc = terminal.NewLogging(logger, logging.TraceId)(terminalSvc) + sysauthSvc = sysauth.NewLogging(logger, logging.TraceId)(sysauthSvc) + } if tracer != nil { @@ -198,6 +203,7 @@ func start(ctx context.Context) (err error) { datasetTaskSvc = datasettask.NewTracing(tracer)(datasetTaskSvc) modelEvaluateSvc = modelevaluate.NewTracing(tracer)(modelEvaluateSvc) terminalSvc = terminal.NewTracing(tracer)(terminalSvc) + sysauthSvc = sysauth.NewTracing(tracer)(sysauthSvc) } g := &group.Group{} @@ -302,7 +308,8 @@ func initHttpHandler(ctx context.Context, g *group.Group) { r := mux.NewRouter() // auth模块 r.PathPrefix("/api/auth").Handler(http.StripPrefix("/api/auth", auth.MakeHTTPHandler(authSvc, authEms, opts))) - + // sysauth模块 + r.PathPrefix("/api/sysauth").Handler(http.StripPrefix("/api/sysauth", sysauth.MakeHTTPHandler(sysauthSvc, authEms, opts))) // file模块 r.PathPrefix("/api/files").Handler(http.StripPrefix("/api", files.MakeHTTPHandler(fileSvc, authEms, opts))) // channel模块 diff --git a/src/pkg/sysauth/endpoint.go b/src/pkg/sysauth/endpoint.go new file mode 100644 index 0000000..99ff881 --- /dev/null +++ b/src/pkg/sysauth/endpoint.go @@ -0,0 +1,286 @@ +// Code generated . DO NOT EDIT. +package sysauth + +import ( + "context" + + "github.com/IceBearAI/aigc/src/encode" + endpoint "github.com/go-kit/kit/endpoint" +) + +const ( + AccountMethodName = "Account" + + CreateAccountMethodName = "CreateAccount" + + CreateTenantMethodName = "CreateTenant" + + DeleteAccountMethodName = "DeleteAccount" + + DeleteTenantMethodName = "DeleteTenant" + + ListAccountMethodName = "ListAccount" + + ListTenantsMethodName = "ListTenants" + + LoginMethodName = "Login" + + UpdateAccountMethodName = "UpdateAccount" + + UpdateTenantMethodName = "UpdateTenant" +) + +type Endpoints struct { + AccountEndpoint endpoint.Endpoint + + CreateAccountEndpoint endpoint.Endpoint + + CreateTenantEndpoint endpoint.Endpoint + + DeleteAccountEndpoint endpoint.Endpoint + + DeleteTenantEndpoint endpoint.Endpoint + + ListAccountEndpoint endpoint.Endpoint + + ListTenantsEndpoint endpoint.Endpoint + + LoginEndpoint endpoint.Endpoint + + UpdateAccountEndpoint endpoint.Endpoint + + UpdateTenantEndpoint endpoint.Endpoint +} + +func NewEndpoint(s Service, dmw map[string][]endpoint.Middleware) Endpoints { + eps := Endpoints{ + + CreateAccountEndpoint: makeCreateAccountEndpoint(s), + + CreateTenantEndpoint: makeCreateTenantEndpoint(s), + + DeleteAccountEndpoint: makeDeleteAccountEndpoint(s), + + DeleteTenantEndpoint: makeDeleteTenantEndpoint(s), + + ListAccountEndpoint: makeListAccountEndpoint(s), + + ListTenantsEndpoint: makeListTenantsEndpoint(s), + + UpdateAccountEndpoint: makeUpdateAccountEndpoint(s), + + UpdateTenantEndpoint: makeUpdateTenantEndpoint(s), + } + + for _, m := range dmw[AccountMethodName] { + eps.AccountEndpoint = m(eps.AccountEndpoint) + } + + for _, m := range dmw[CreateAccountMethodName] { + eps.CreateAccountEndpoint = m(eps.CreateAccountEndpoint) + } + + for _, m := range dmw[CreateTenantMethodName] { + eps.CreateTenantEndpoint = m(eps.CreateTenantEndpoint) + } + + for _, m := range dmw[DeleteAccountMethodName] { + eps.DeleteAccountEndpoint = m(eps.DeleteAccountEndpoint) + } + + for _, m := range dmw[DeleteTenantMethodName] { + eps.DeleteTenantEndpoint = m(eps.DeleteTenantEndpoint) + } + + for _, m := range dmw[ListAccountMethodName] { + eps.ListAccountEndpoint = m(eps.ListAccountEndpoint) + } + + for _, m := range dmw[ListTenantsMethodName] { + eps.ListTenantsEndpoint = m(eps.ListTenantsEndpoint) + } + + for _, m := range dmw[LoginMethodName] { + eps.LoginEndpoint = m(eps.LoginEndpoint) + } + + for _, m := range dmw[UpdateAccountMethodName] { + eps.UpdateAccountEndpoint = m(eps.UpdateAccountEndpoint) + } + + for _, m := range dmw[UpdateTenantMethodName] { + eps.UpdateTenantEndpoint = m(eps.UpdateTenantEndpoint) + } + + return eps +} + +func makeCreateAccountEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(CreateAccountRequest) + + var res Account + + res, err = s.CreateAccount( + ctx, + + req, + ) + + return encode.Response{ + Data: res, + Error: err, + }, nil + + } +} + +func makeCreateTenantEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(CreateTenantRequest) + + var res TenantDetail + + res, err = s.CreateTenant( + ctx, + + req, + ) + + return encode.Response{ + Data: res, + Error: err, + }, nil + + } +} + +func makeDeleteAccountEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(DeleteAccountRequest) + + err = s.DeleteAccount( + ctx, + + req.Id, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + + } +} + +func makeDeleteTenantEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(DeleteTenantRequest) + + err = s.DeleteTenant( + ctx, + + req.Id, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + + } +} + +func makeListAccountEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(ListAccountRequest) + + var list []Account + + var total int64 + + list, total, err = s.ListAccount( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{ + "list": list, + "total": total}, + Error: err, + }, nil + + } +} + +func makeListTenantsEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(ListTenantRequest) + + var list []TenantDetail + + var total int64 + + list, total, err = s.ListTenants( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{ + "list": list, + "total": total}, + Error: err, + }, nil + + } +} + + + +func makeUpdateAccountEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(UpdateAccountRequest) + + err = s.UpdateAccount( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + + } +} + +func makeUpdateTenantEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(UpdateTenantRequest) + + err = s.UpdateTenant( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + + } +} diff --git a/src/pkg/sysauth/http.go b/src/pkg/sysauth/http.go new file mode 100644 index 0000000..51c3d49 --- /dev/null +++ b/src/pkg/sysauth/http.go @@ -0,0 +1,504 @@ +// Code generated . DO NOT EDIT. +package sysauth + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/IceBearAI/aigc/src/encode" + endpoint "github.com/go-kit/kit/endpoint" + kithttp "github.com/go-kit/kit/transport/http" + "github.com/go-playground/validator/v10" + "github.com/gorilla/mux" + "github.com/pkg/errors" + "github.com/spf13/cast" +) + +var validate = validator.New() +func MakeHTTPHandler(s Service, dmw []endpoint.Middleware, opts []kithttp.ServerOption) http.Handler { + var ems []endpoint.Middleware + + opts = append(opts, kithttp.ServerBefore(func(ctx context.Context, request *http.Request) context.Context { + return ctx + })) + + ems = append(ems, dmw...) + + eps := NewEndpoint(s, map[string][]endpoint.Middleware{ + + AccountMethodName: ems, + + CreateAccountMethodName: ems, + + CreateTenantMethodName: ems, + + DeleteAccountMethodName: ems, + + DeleteTenantMethodName: ems, + + ListAccountMethodName: ems, + + ListTenantsMethodName: ems, + + LoginMethodName: ems, + + UpdateAccountMethodName: ems, + + UpdateTenantMethodName: ems, + }) + + r := mux.NewRouter() + + r.Handle("/account", kithttp.NewServer( + eps.AccountEndpoint, + decodeAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("GET") + + r.Handle("/account", kithttp.NewServer( + eps.CreateAccountEndpoint, + decodeCreateAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("POST") + + r.Handle("/tenants", kithttp.NewServer( + eps.CreateTenantEndpoint, + decodeCreateTenantRequest, + encode.JsonResponse, + opts..., + )).Methods("POST") + + r.Handle("/account/{id}", kithttp.NewServer( + eps.DeleteAccountEndpoint, + decodeDeleteAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("DELETE") + + r.Handle("/tenant/{id}", kithttp.NewServer( + eps.DeleteTenantEndpoint, + decodeDeleteTenantRequest, + encode.JsonResponse, + opts..., + )).Methods("DELETE") + + r.Handle("/accounts", kithttp.NewServer( + eps.ListAccountEndpoint, + decodeListAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("GET") + + r.Handle("/tenants", kithttp.NewServer( + eps.ListTenantsEndpoint, + decodeListTenantsRequest, + encode.JsonResponse, + opts..., + )).Methods("GET") + + r.Handle("/login", kithttp.NewServer( + eps.LoginEndpoint, + decodeLoginRequest, + encode.JsonResponse, + opts..., + )).Methods("POST") + + r.Handle("/account/{id}", kithttp.NewServer( + eps.UpdateAccountEndpoint, + decodeUpdateAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("PUT") + + r.Handle("/tenant/{id}", kithttp.NewServer( + eps.UpdateTenantEndpoint, + decodeUpdateTenantRequest, + encode.JsonResponse, + opts..., + )).Methods("PUT") + + return r +} + +// Account +// @Summary 获取账号信息 +// @Description 获取账号信息 +// @tags Account +// @Accept json +// @Produce json +// @Success 200 {object} encode.Response{data=AccountResult} +// @Router /account [GET] +func decodeAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := AccountRequest{} + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// CreateAccount +// @Summary 创建账号 +// @Description 创建账号 +// @tags Account +// @Accept json +// @Produce json +// @Param CreateAccountRequest body CreateAccountRequest true "http request body" +// @Success 200 {object} encode.Response{data=Account} +// @Router /account [POST] +func decodeCreateAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := CreateAccountRequest{} + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// CreateTenant +// @Summary 创建租户 +// @Description 创建租户 +// @tags Account +// @Accept json +// @Produce json +// @Param CreateTenantRequest body CreateTenantRequest true "http request body" +// @Success 200 {object} encode.Response{data=TenantDetail} +// @Router /tenants [POST] +func decodeCreateTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := CreateTenantRequest{} + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// DeleteAccount +// @Summary 删除账号 +// @Description 删除账号 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Success 200 {object} encode.Response{} +// @Router /account/{id} [DELETE] +func decodeDeleteAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := DeleteAccountRequest{} + + var _id uint + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// DeleteTenant +// @Summary 删除租户 +// @Description 删除租户 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Success 200 {object} encode.Response{} +// @Router /tenant/{id} [DELETE] +func decodeDeleteTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := DeleteTenantRequest{} + + var _id uint + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// ListAccount +// @Summary 获取账号列表 +// @Description 获取账号列表 +// @tags Account +// @Accept json +// @Produce json +// @Param email query string false " " +// @Param isLdap query string false " " +// @Param nickname query string false " " +// @Param page query string false " " +// @Param pageSize query string false " " +// @Success 200 {object} encode.Response{data.list=[]Account,data.total=int64} +// @Router /accounts [GET] +func decodeListAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := ListAccountRequest{} + + var _email string + + var _isLdap bool + + var _nickname string + + var _page int + + var _pageSize int + + _email = r.URL.Query().Get("email") + + _isLdapStr := r.URL.Query().Get("isLdap") + + if _isLdapStr != "" { + _isLdap, err = cast.ToBoolE(_isLdapStr) + + if err != nil { + return + } + } + + _nickname = r.URL.Query().Get("nickname") + + _pageStr := r.URL.Query().Get("page") + + if _pageStr != "" { + _page, err = cast.ToIntE(_pageStr) + + if err != nil { + return + } + } + + _pageSizeStr := r.URL.Query().Get("pageSize") + + if _pageSizeStr != "" { + _pageSize, err = cast.ToIntE(_pageSizeStr) + + if err != nil { + return + } + } + + req.Email = _email + + if _isLdapStr != "" { + req.IsLdap = &_isLdap + } + + req.Nickname = _nickname + + req.Page = _page + + req.PageSize = _pageSize + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// ListTenants +// @Summary 获取租户列表 +// @Description 获取租户列表 +// @tags Account +// @Accept json +// @Produce json +// @Param name query string false " " +// @Param page query string false " " +// @Param pageSize query string false " " +// @Success 200 {object} encode.Response{data.list=[]TenantDetail,data.total=int64} +// @Router /tenants [GET] +func decodeListTenantsRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := ListTenantRequest{} + + var _name string + + var _page int + + var _pageSize int + + _name = r.URL.Query().Get("name") + + _pageStr := r.URL.Query().Get("page") + + if _pageStr != "" { + _page, err = cast.ToIntE(_pageStr) + + if err != nil { + return + } + } + + _pageSizeStr := r.URL.Query().Get("pageSize") + + if _pageSizeStr != "" { + _pageSize, err = cast.ToIntE(_pageSizeStr) + + if err != nil { + return + } + } + + req.Name = _name + + req.Page = _page + + req.PageSize = _pageSize + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// Login +// @Summary 平台授权登陆 +// @Description 平台授权登陆 +// @tags Account +// @Accept json +// @Produce json +// @Param LoginRequest body LoginRequest true "http request body" +// @Success 200 {object} encode.Response{data=LoginResult} +// @Router /login [POST] +func decodeLoginRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := LoginRequest{} + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// UpdateAccount +// @Summary 更新账号 +// @Description 更新账号 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Param UpdateAccountRequest body UpdateAccountRequest true "http request body" +// @Success 200 {object} encode.Response{} +// @Router /account/{id} [PUT] +func decodeUpdateAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := UpdateAccountRequest{} + + var _id uint + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// UpdateTenant +// @Summary 更新租户 +// @Description 更新租户 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Param UpdateTenantRequest body UpdateTenantRequest true "http request body" +// @Success 200 {object} encode.Response{} +// @Router /tenant/{id} [PUT] +func decodeUpdateTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := UpdateTenantRequest{} + + var _id uint + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} diff --git a/src/pkg/sysauth/logging.go b/src/pkg/sysauth/logging.go new file mode 100644 index 0000000..685a19c --- /dev/null +++ b/src/pkg/sysauth/logging.go @@ -0,0 +1,207 @@ +// Code generated . DO NOT EDIT. +package sysauth + +import ( + "context" + "encoding/json" + "time" + + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" +) + +type logging struct { + logger log.Logger + next Service + traceId string +} + +func (s *logging) CreateAccount(ctx context.Context, req CreateAccountRequest) (res Account, err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CreateAccount", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.CreateAccount(ctx, req) + +} + +func (s *logging) CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CreateTenant", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.CreateTenant(ctx, req) + +} + +func (s *logging) DeleteAccount(ctx context.Context, id uint) (err error) { + + defer func(begin time.Time) { + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "DeleteAccount", + + "id", id, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.DeleteAccount(ctx, id) + +} + +func (s *logging) DeleteTenant(ctx context.Context, id uint) (err error) { + + defer func(begin time.Time) { + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "DeleteTenant", + + "id", id, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.DeleteTenant(ctx, id) + +} + +func (s *logging) ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "ListAccount", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.ListAccount(ctx, req) + +} + +func (s *logging) ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "ListTenants", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.ListTenants(ctx, req) + +} + + +func (s *logging) UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateAccount", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.UpdateAccount(ctx, req) + +} + +func (s *logging) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateTenant", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.UpdateTenant(ctx, req) + +} + +func NewLogging(logger log.Logger, traceId string) Middleware { + logger = log.With(logger, "pkg.auth", "logging") + return func(next Service) Service { + return &logging{ + logger: level.Info(logger), + next: next, + traceId: traceId, + } + } +} diff --git a/src/pkg/sysauth/middleware.go b/src/pkg/sysauth/middleware.go new file mode 100644 index 0000000..de714ea --- /dev/null +++ b/src/pkg/sysauth/middleware.go @@ -0,0 +1,3 @@ +package sysauth + +type Middleware func(Service) Service diff --git a/src/pkg/sysauth/service.go b/src/pkg/sysauth/service.go new file mode 100644 index 0000000..c43f02c --- /dev/null +++ b/src/pkg/sysauth/service.go @@ -0,0 +1,435 @@ +package sysauth + +import ( + "context" + "time" + + "github.com/IceBearAI/aigc/src/encode" + authjwt "github.com/IceBearAI/aigc/src/jwt" + "github.com/IceBearAI/aigc/src/middleware" + "github.com/IceBearAI/aigc/src/repository" + "github.com/IceBearAI/aigc/src/repository/auth" + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/IceBearAI/aigc/src/services" + "github.com/go-kit/log" + "github.com/go-kit/log/level" + jwt2 "github.com/golang-jwt/jwt/v4" + "github.com/google/uuid" + "github.com/pkg/errors" + "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" +) + +// 用户管理 +// @tags Account +type Service interface { + // ListTenants 获取租户列表 + // @kit-http /tenants GET + // @kit-http-request ListTenantRequest + ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) + + // UpdateTenant 更新租户 + // @kit-http /tenant/{id} PUT + // @kit-http-request UpdateTenantRequest true + UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) + // CreateTenant 创建租户 + // @kit-http /tenants POST + // @kit-http-request CreateTenantRequest true + CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) + // DeleteTenant 删除租户 + // @kit-http /tenant/{id} DELETE + // @kit-http-request DeleteTenantRequest + DeleteTenant(ctx context.Context, id uint) (err error) + // CreateAccount 创建账号 + // @kit-http /account POST + // @kit-http-request CreateAccountRequest true + CreateAccount(ctx context.Context, req CreateAccountRequest) (res Account, err error) + // ListAccount 获取账号列表 + // @kit-http /accounts GET + // @kit-http-request ListAccountRequest + ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) + // UpdateAccount 更新账号 + // @kit-http /account/{id} PUT + // @kit-http-request UpdateAccountRequest true + UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) + + // DeleteAccount 删除账号 + // @kit-http /account/{id} DELETE + // @kit-http-request DeleteAccountRequest + DeleteAccount(ctx context.Context, id uint) (err error) +} + +type service struct { + logger log.Logger + traceId string + store repository.Repository + //rdb redis.UniversalClient + apiSvc services.Service +} + +// UpdateTenant implements Service. +func (s *service) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + t, err := s.store.Auth().GetTenantById(ctx, req.Id) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + } + + t.Name = req.Name + t.ContactEmail = req.ContactEmail + t.Models, err = s.store.Model().FindByModelNames(ctx, req.ModelNames) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询模型失败")) + } + + err = s.store.Auth().UpdateTenant(ctx, &t) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "更新租户失败")) + } + + return +} + +// DeleteTenant implements Service. +func (s *service) DeleteTenant(ctx context.Context, id uint) (err error) { + err = s.store.Auth().DeleteTenant(ctx, id) + if err != nil { + err = encode.ErrSystem.Wrap(errors.Wrap(err, "删除租户失败")) + return + } + return +} + +// DeleteAccount implements Service. +func (s *service) DeleteAccount(ctx context.Context, id uint) (err error) { + err = s.store.Auth().DeleteAccount(ctx, id) + if err != nil { + err = encode.ErrSystem.Wrap(errors.Wrap(err, "删除账号失败")) + return + } + return +} + +func (s *service) UpdateAccount(ctx context.Context, request UpdateAccountRequest) (err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "UpdateAccount") + data, err := s.store.Auth().GetAccountById(ctx, request.Id) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + if errors.Is(err, gorm.ErrRecordNotFound) { + return encode.ErrAccountNotFound.Error() + } + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询账号失败")) + } + if request.Email != "" { + res, err := s.store.Auth().GetAccountByEmail(ctx, request.Email) + if err == nil && res.ID != data.ID { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", "邮箱账号已存在") + return encode.InvalidParams.Wrap(errors.Wrap(err, "要更新邮箱账号已存在")) + } + data.Email = request.Email + } + if request.Nickname != "" { + data.Nickname = request.Nickname + } + + if request.Language != "" { + data.Language = request.Language + } + + if request.Status != nil { + data.Status = *request.Status + } + if request.IsLdap != nil { + data.IsLdap = *request.IsLdap + } + + if request.Password != "" { + hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + return encode.ErrSystem.Wrap(errors.Wrap(err, "更新账号失败,请联系管理员")) + } + data.PasswordHash = string(hash) + } + + data.Tenants, err = s.store.Tenants().FindByPublicTenantIdItems(ctx, request.TenantPublicTenantIdItems) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return + } + + err = s.store.Auth().UpdateAccount(ctx, &data) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + return err + } + return nil +} + +func (s *service) ListAccount(ctx context.Context, request ListAccountRequest) (list []Account, total int64, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "ListAccount") + req := auth.ListAccountRequest{ + Page: request.Page, + PageSize: request.PageSize, + Email: request.Email, + IsLdap: request.IsLdap, + } + accounts, total, err := s.store.Auth().ListAccount(ctx, req) + if err != nil { + _ = level.Error(logger).Log("auth", "ListAccount", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询账号失败")) + return + } + for _, a := range accounts { + list = append(list, convertAccount(&a)) + } + return +} + +func (s *service) CreateTenant(ctx context.Context, request CreateTenantRequest) (res TenantDetail, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "CreateTenant") + data := types.Tenants{ + Name: request.Name, + PublicTenantID: uuid.New().String(), + ContactEmail: request.ContactEmail, + } + + models, err := s.store.Model().FindByModelNames(ctx, request.ModelNames) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateTenant", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询模型失败")) + return res, err + } + data.Models = models + err = s.store.Auth().CreateTenant(ctx, &data) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateTenant", "err", err.Error()) + return res, err + } + res = convertTenant(&data) + return res, nil +} + +func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (list []TenantDetail, total int64, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "ListTenants") + req := auth.ListTenantRequest{ + Page: request.Page, + PageSize: request.PageSize, + Name: request.Name, + } + tenants, total, err := s.store.Auth().ListTenants(ctx, req) + if err != nil { + _ = level.Error(logger).Log("auth", "ListTenants", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return + } + for _, t := range tenants { + list = append(list, convertTenant(&t)) + } + return +} + +func (s *service) CreateAccount(ctx context.Context, request CreateAccountRequest) (res Account, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "CreateAccount") + data := types.Accounts{ + Email: request.Email, + Nickname: request.Nickname, + Language: request.Language, + IsLdap: request.IsLdap, + Status: true, + } + if !data.IsLdap { + hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) + return res, encode.ErrSystem.Wrap(errors.Wrap(err, "创建账号失败,请联系管理员")) + } + data.PasswordHash = string(hash) + } + data.Tenants, err = s.store.Tenants().FindByPublicTenantIdItems(ctx, request.TenantPublicTenantIdItems) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return + } + + err = s.store.Auth().CreateAccount(ctx, &data) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) + return res, err + } + res = convertAccount(&data) + return res, nil +} + +func (s *service) Account(ctx context.Context, email string) (res AccountResult, err error) { + email, ok := middleware.GetEmail(ctx) + if !ok { + _ = level.Error(s.logger).Log("auth", "Account, GetEmail error", "email", email) + return res, encode.ErrAccountNotFound.Error() + } + account, err := s.store.Auth().GetAccountByEmail(ctx, email, "Tenants") + if err != nil { + _ = level.Error(s.logger).Log("auth", "account, GetAccountByEmail error", "email", email, "err", err.Error()) + return res, encode.ErrAccountNotFound.Error() + } + res.Email = account.Email + res.Nickname = account.Nickname + res.Language = account.Language + res.Tenants = make([]Tenant, 0) + for _, t := range account.Tenants { + res.Tenants = append(res.Tenants, Tenant{ + Id: t.PublicTenantID, + Name: t.Name, + }) + } + return res, nil +} + +func (s *service) Login(ctx context.Context, req LoginRequest) (res LoginResult, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId)) + username := req.Username + password := req.Password + if username == "" || password == "" { + _ = level.Error(logger).Log("auth", "login, username or password is empty", "username", username, "password", password) + return res, encode.ErrAccountLogin.Error() + } + + //loginKey := fmt.Sprintf("aigc:auth:login:%s", username) + //if s.rdb.Incr(ctx, loginKey).Val() > 1 { + // _ = s.rdb.Expire(ctx, loginKey, time.Minute).Err() + // _ = level.Error(logger).Log("auth", "login", "username", username, "err", encode.ErrLimiter.Error()) + // return res, encode.ErrLimiter.Error() + //} + //defer func() { + // _ = s.rdb.Del(ctx, loginKey).Err() + //}() + // + //errLoginKey := fmt.Sprintf("aigc:auth:login:err:%s", username) + //errNum, err := s.rdb.Get(ctx, errLoginKey).Int() + //if err != nil && !errors.Is(err, redis.Nil) { + // _ = level.Error(logger).Log("auth", "login, redis get errLoginKey error", "username", username, "err", err.Error()) + // return res, encode.ErrSystem.Wrap(errors.Wrap(err,"登录失败,请联系管理员")) + //} + //if errNum >= 5 { + // _ = level.Error(logger).Log("auth", "login too many error times", "username", username, "err", encode.ErrLimiter.Error()) + // return res, encode.ErrAccountLocked.Error() + //} + + // 获取账号信息 + account, err := s.store.Auth().GetAccountByEmail(ctx, req.Username) + if err != nil { + _ = level.Error(logger).Log("auth", "login, GetAccountByEmail error", "username", username, "err", err.Error()) + return res, encode.ErrAccountNotFound.Error() + } + // 账号被锁定 + if !account.Status { + _ = level.Error(logger).Log("auth", "login, account status not active", "username", username) + return res, encode.ErrAccountLocked.Error() + } + + if account.IsLdap { + authenticate, err := s.apiSvc.Ldap().Authenticate(ctx, username, password) + if err != nil { + _ = level.Error(logger).Log("auth", "login", "username", username, "err", err.Error()) + return res, encode.ErrAccountLogin.Error() + } + if !authenticate { + //_ = s.rdb.Incr(ctx, errLoginKey).Err() + //_ = s.rdb.Expire(ctx, errLoginKey, time.Minute*30).Err() + _ = level.Error(logger).Log("auth", "login authenticate false", "username", username) + return res, encode.ErrAccountLogin.Error() + } + } else { + err = bcrypt.CompareHashAndPassword([]byte(account.PasswordHash), []byte(password)) + if err != nil { + //_ = s.rdb.Incr(ctx, errLoginKey).Err() + //_ = s.rdb.Expire(ctx, errLoginKey, time.Minute*30).Err() + _ = level.Error(logger).Log("auth", "login, bcrypt.CompareHashAndPassword error", "username", username, "err", err.Error()) + return res, encode.ErrAccountLogin.Error() + } + } + tk, err := s.jwtToken(ctx, authjwt.TokenSourceNd, time.Duration(168)*time.Hour, username, "", account.ID) + if err != nil { + _ = level.Error(logger).Log("auth", "login, jwtToken error", "username", username, "err", err.Error()) + return res, encode.ErrSystem.Wrap(errors.Wrap(err, "登录失败,请联系管理员")) + } + res.Token = tk + res.Username = username + return res, nil +} + +func (s *service) jwtToken(ctx context.Context, source authjwt.TokenSource, timeout time.Duration, email string, qwUserid string, accountId uint) (tk string, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId)) + expAt := jwt2.NewNumericDate(time.Now().Add(timeout)) + + // 创建声明 + claims := authjwt.ArithmeticCustomClaims{ + Source: source, + RegisteredClaims: jwt2.RegisteredClaims{ + ExpiresAt: expAt, + Issuer: "system", + }, + UserId: accountId, + } + + //不同类型,参数不一样 + claims.Email = email + + //创建token,指定加密算法为HS256 + token := jwt2.NewWithClaims(jwt2.SigningMethodHS256, claims) + //生成token + tk, err = token.SignedString([]byte(authjwt.GetJwtKey())) + if err != nil { + _ = level.Error(logger).Log("auth", "jwtToken, SignedString error", "err", err.Error(), "source", source, "email", email, "qwUserid", qwUserid, "accountId", accountId) + return tk, nil + } + return +} +func convertTenant(data *types.Tenants) TenantDetail { + td := TenantDetail{ + Id: data.ID, + Name: data.Name, + PublicTenantID: data.PublicTenantID, + ContactEmail: data.ContactEmail, + CreatedAt: data.CreatedAt, + UpdatedAt: data.UpdatedAt, + } + + for _, v := range data.Models { + td.ModelNames = append(td.ModelNames, v.ModelName) + } + return td +} + +func convertAccount(data *types.Accounts) Account { + res := Account{ + Id: data.ID, + Email: data.Email, + IsLdap: data.IsLdap, + Nickname: data.Nickname, + Language: data.Language, + Status: data.Status, + CreatedAt: data.CreatedAt, + UpdatedAt: data.UpdatedAt, + } + + for _, v := range data.Tenants { + res.Tenants = append(res.Tenants, convertTenant(&v)) + } + return res + +} + +func New(logger log.Logger, traceId string, + store repository.Repository, + //rdb redis.UniversalClient, + apiSvc services.Service) Service { + return &service{ + logger: logger, + traceId: traceId, + store: store, + //rdb: rdb, + apiSvc: apiSvc, + } +} diff --git a/src/pkg/sysauth/service_test.go b/src/pkg/sysauth/service_test.go new file mode 100644 index 0000000..b9eedaa --- /dev/null +++ b/src/pkg/sysauth/service_test.go @@ -0,0 +1,33 @@ +package sysauth + +import ( + "encoding/json" + + "github.com/IceBearAI/aigc/tests" + "github.com/go-kit/log" +) + +var logger log.Logger + +func initSvc() Service { + apiSvc, err := tests.Init() + if err != nil { + panic(err) + } + + return New(logger, "", tests.Store, apiSvc) +} + +func getCurrentWeather(location string, unit string) (string, error) { + weatherInfo := map[string]interface{}{ + "location": location, + "temperature": "72", + "unit": unit, + "forecast": []string{"sunny", "windy"}, + } + b, err := json.Marshal(weatherInfo) + if err != nil { + return "", err + } + return string(b), nil +} diff --git a/src/pkg/sysauth/tracing.go b/src/pkg/sysauth/tracing.go new file mode 100644 index 0000000..b6b1a7c --- /dev/null +++ b/src/pkg/sysauth/tracing.go @@ -0,0 +1,228 @@ +// Code generated . DO NOT EDIT. +package sysauth + +import ( + "context" + "encoding/json" + + "github.com/opentracing/opentracing-go" + "github.com/opentracing/opentracing-go/ext" +) + +type tracing struct { + next Service + tracer opentracing.Tracer +} + + +func (s *tracing) CreateAccount(ctx context.Context, req CreateAccountRequest) (res Account, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.CreateAccount(ctx, req) + +} + +func (s *tracing) CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateTenant", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.CreateTenant(ctx, req) + +} + +func (s *tracing) DeleteAccount(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteAccount", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + span.LogKV( + "id", id, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.DeleteAccount(ctx, id) + +} + +func (s *tracing) DeleteTenant(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteTenant", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + span.LogKV( + "id", id, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.DeleteTenant(ctx, id) + +} + +func (s *tracing) ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListAccount", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.ListAccount(ctx, req) + +} + +func (s *tracing) ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.ListTenants(ctx, req) + +} + + +func (s *tracing) UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateAccount", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.UpdateAccount(ctx, req) + +} + +func (s *tracing) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateTenant", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.UpdateTenant(ctx, req) + +} + +func NewTracing(otTracer opentracing.Tracer) Middleware { + return func(next Service) Service { + return &tracing{ + next: next, + tracer: otTracer, + } + } +} diff --git a/src/pkg/sysauth/types.go b/src/pkg/sysauth/types.go new file mode 100644 index 0000000..020eeff --- /dev/null +++ b/src/pkg/sysauth/types.go @@ -0,0 +1,115 @@ +package sysauth + +import "time" + +type LoginRequest struct { + // Username 登陆用户的邮箱或邮箱前缀 + Username string `json:"username" validate:"required" param:",username"` + // Username 登陆用户的邮箱密码 + Password string `json:"password" validate:"required" param:",password"` +} + +type LoginResult struct { + // Token jwt token + Token string `json:"token"` + // Username 登陆用户的姓名 + Username string `json:"username"` + // Avatar 登陆用户的头像地址 + Avatar string `json:"avatar,omitempty"` +} +type AccountRequest struct { + Email string `json:"email" param:",email"` +} +type Tenant struct { + // TenantId 租户ID + Id string `json:"id"` + // TenantName 租户名称 + Name string `json:"name"` +} +type AccountResult struct { + // Tenant 租户信息 + Tenants []Tenant `json:"tenants"` + Email string `json:"email"` + Nickname string `json:"nickname"` + Language string `json:"language"` +} + +type TenantDetail struct { + Id uint `json:"id"` + Name string `json:"name"` + PublicTenantID string `json:"publicTenantId"` + ContactEmail string `json:"contactEmail"` + ModelNames []string `json:"modelNames"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type ListTenantRequest struct { + Page int `json:"page" param:"query,page"` + PageSize int `json:"pageSize" param:"query,pageSize"` + Name string `json:"name" param:"query,name"` +} + +type CreateAccountRequest struct { + Nickname string `json:"nickname" validate:"required"` + Email string `json:"email" validate:"required"` + IsLdap bool `json:"isLdap"` + Password string `json:"password"` + Language string `json:"language" validate:"required"` + + TenantPublicTenantIdItems []string `json:"tenantPublicTenantIdItems"` +} + +type Account struct { + Id uint `json:"id"` + Email string `json:"email"` + Nickname string `json:"nickname"` + Status bool `json:"status"` + IsLdap bool `json:"isLdap"` + Language string `json:"language"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + + Tenants []TenantDetail `json:"tenants"` +} + +type ListAccountRequest struct { + Page int `json:"page" param:"query,page"` + PageSize int `json:"pageSize" param:"query,pageSize"` + Email string `json:"email" param:"query,email"` + Nickname string `json:"nickname" param:"query,nickname"` + IsLdap *bool `json:"isLdap,omitempty" param:"query,isLdap"` + Status *bool `json:"status,omitempty"` +} + +type CreateTenantRequest struct { + Name string `json:"name" validate:"required"` + ContactEmail string `json:"contactEmail" validate:"required"` + ModelNames []string `json:"modelNames"` +} + +type UpdateAccountRequest struct { + Id uint `json:"id" param:"path,id" validate:"required"` + Nickname string `json:"nickname"` + Email string `json:"email"` + IsLdap *bool `json:"isLdap"` + Language string `json:"language"` + Status *bool `json:"status,omitempty"` + Password string `json:"password"` + TenantPublicTenantIdItems []string `json:"tenantPublicTenantIdItems"` +} + +type DeleteAccountRequest struct { + Id uint `json:"id" validate:"required" param:"path,id"` +} + +type DeleteTenantRequest struct { + Id uint `json:"publicTenantId" validate:"required" param:"path,id"` +} + +type UpdateTenantRequest struct { + Id uint `json:"id" param:"path,id" validate:"required"` + Name string `json:"name" validate:"required"` + ContactEmail string `json:"contactEmail" validate:"required"` + ModelNames []string `json:"modelNames"` +} diff --git a/src/repository/auth/logging.go b/src/repository/auth/logging.go index 5e98d09..f108e3f 100644 --- a/src/repository/auth/logging.go +++ b/src/repository/auth/logging.go @@ -1,12 +1,14 @@ +// Code generated . DO NOT EDIT. package auth import ( "context" - "fmt" - "github.com/IceBearAI/aigc/src/repository/types" - "github.com/go-kit/log" - "github.com/go-kit/log/level" + "encoding/json" "time" + + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" ) type logging struct { @@ -15,134 +17,277 @@ type logging struct { traceId string } -func (s *logging) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { +func (s *logging) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "UpdateTenant", "data", fmt.Sprintf("%+v", data), + "method", "CreateAccount", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.UpdateTenant(ctx, data) + + return s.next.CreateAccount(ctx, data) + } -func (s *logging) DeleteTenant(ctx context.Context, id uint) (err error) { +func (s *logging) CreateTenant(ctx context.Context, data *types.Tenants) (err error) { + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "DeleteTenant", "id", id, + "method", "CreateTenant", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.DeleteTenant(ctx, id) + + return s.next.CreateTenant(ctx, data) + } -func (s *logging) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { +func (s *logging) DeleteAccount(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "ListAccount", "request", fmt.Sprintf("%+v", request), + "method", "DeleteAccount", + + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.ListAccount(ctx, request) + + return s.next.DeleteAccount(ctx, id) + } -func (s *logging) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { +func (s *logging) DeleteTenant(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "UpdateAccount", "data", fmt.Sprintf("%+v", data), + "method", "DeleteTenant", + + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.UpdateAccount(ctx, data) + + return s.next.DeleteTenant(ctx, id) + +} + +func (s *logging) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { + + defer func(begin time.Time) { + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "GetAccountByEmail", + + "email", email, + + "preload", preloadJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.GetAccountByEmail(ctx, email, preload...) + } func (s *logging) GetAccountById(ctx context.Context, id uint) (res types.Accounts, err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "GetAccountById", "id", id, + "method", "GetAccountById", + + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) + return s.next.GetAccountById(ctx, id) + } -func (s *logging) DeleteAccount(ctx context.Context, id uint) (err error) { +func (s *logging) GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) { + defer func(begin time.Time) { + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + _ = s.logger.Log( - s.traceId, ctx.Value(s.traceId), "method", "DeleteAccount", "id", id, + s.traceId, ctx.Value(s.traceId), + "method", "GetTenantById", + + "id", id, + + "preload", preloadJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.DeleteAccount(ctx, id) + + return s.next.GetTenantById(ctx, id, preload...) + } -func (s *logging) CreateTenant(ctx context.Context, data *types.Tenants) (err error) { +func (s *logging) GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) { + defer func(begin time.Time) { + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "CreateTenant", "data", fmt.Sprintf("%+v", data), + "method", "GetTenantByUuid", + + "uuid", uuid, + + "preload", preloadJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.CreateTenant(ctx, data) + + return s.next.GetTenantByUuid(ctx, uuid, preload...) + } -func (s *logging) ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) { +func (s *logging) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { + defer func(begin time.Time) { + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "ListTenants", "request", fmt.Sprintf("%+v", request), + "method", "ListAccount", + + "request", requestJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.ListTenants(ctx, request) + + return s.next.ListAccount(ctx, request) + } -func (s *logging) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { +func (s *logging) ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) { + defer func(begin time.Time) { + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "CreateAccount", "data", fmt.Sprintf("%+v", data), + "method", "ListTenants", + + "request", requestJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.CreateAccount(ctx, data, tenantId) + + return s.next.ListTenants(ctx, request) + } -func (s *logging) GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) { +func (s *logging) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "GetTenantByUuid", "uuid", uuid, + "method", "UpdateAccount", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.GetTenantByUuid(ctx, uuid, preload...) + + return s.next.UpdateAccount(ctx, data) + } -func (s *logging) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { +func (s *logging) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + _ = s.logger.Log( - s.traceId, ctx.Value(s.traceId), "method", "GetAccountByEmail", "email", email, + s.traceId, ctx.Value(s.traceId), + "method", "UpdateTenant", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.GetAccountByEmail(ctx, email, preload...) + + return s.next.UpdateTenant(ctx, data) + } func NewLogging(logger log.Logger, traceId string) Middleware { diff --git a/src/repository/auth/service.go b/src/repository/auth/service.go index ac21d10..2553898 100644 --- a/src/repository/auth/service.go +++ b/src/repository/auth/service.go @@ -2,14 +2,18 @@ package auth import ( "context" + "github.com/IceBearAI/aigc/src/helpers/page" "github.com/IceBearAI/aigc/src/repository/types" + "github.com/pkg/errors" "gorm.io/gorm" ) type Middleware func(Service) Service type Service interface { + // GetTenantById 根据id获取租户信息 + GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) // GetTenantByUuid 根据uuid获取租户信息 GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) // GetAccountByEmail 根据email获取账号信息 @@ -23,7 +27,7 @@ type Service interface { // ListTenants 租户列表 ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) // CreateAccount 创建账号 - CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) + CreateAccount(ctx context.Context, data *types.Accounts) (err error) // ListAccount 获取账号列表 ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) // UpdateAccount 更新账号 @@ -52,11 +56,27 @@ type service struct { db *gorm.DB } -func (s *service) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { - err = s.db.WithContext(ctx).Save(data).Error +// GetTenantById implements Service. +func (s *service) GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) { + db := s.db.WithContext(ctx).Where("id = ?", id) + for _, v := range preload { + db = db.Preload(v) + } + err = db.First(&res).Error return } +func (s *service) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { + return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + if err = tx.Model(&types.Tenants{Model: data.Model}).Association("Models").Clear(); err != nil { + err = errors.Wrap(err, "取消关联模型失败") + return err + } + return tx.Save(data).Error + }) + +} + func (s *service) DeleteTenant(ctx context.Context, id uint) (err error) { err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { if err = tx.Delete(&types.Tenants{}, id).Error; err != nil { @@ -82,12 +102,28 @@ func (s *service) ListAccount(ctx context.Context, request ListAccountRequest) ( query = query.Where("status = ?", request.Status) } limit, offset := page.Limit(request.Page, request.PageSize) - err = query.Count(&total).Order("id DESC").Limit(limit).Offset(offset).Find(&res).Error + err = query.Count(&total).Order("id DESC").Limit(limit).Offset(offset).Preload("Tenants").Find(&res).Error return } func (s *service) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { - err = s.db.WithContext(ctx).Save(data).Error + db := s.db.WithContext(ctx) + + err = db.Transaction(func(tx *gorm.DB) (err error) { + err = tx.Model(&types.Accounts{Model: data.Model}).Association("Tenants").Clear() + if err != nil { + err = errors.Wrap(err, "取消关联租户失败") + return + } + + err = tx.Save(data).Error + if err != nil { + err = errors.Wrap(err, "更新账号信息失败") + return + } + + return nil + }) return } @@ -117,21 +153,12 @@ func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (r query = query.Where("name LIKE ?", "%"+request.Name+"%") } limit, offset := page.Limit(request.Page, request.PageSize) - err = query.Count(&total).Order("id DESC").Limit(limit).Offset(offset).Find(&res).Error + err = query.Count(&total).Order("id DESC").Limit(limit).Offset(offset).Preload("Models").Find(&res).Error return } -func (s *service) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { - err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { - if err = tx.Create(data).Error; err != nil { - return err - } - return tx.Create(&types.TenantAccountAssociations{ - TenantID: tenantId, - AccountID: data.ID, - }).Error - }) - return +func (s *service) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { + return s.db.WithContext(ctx).Save(data).Error } func (s *service) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { diff --git a/src/repository/auth/tracing.go b/src/repository/auth/tracing.go index f8d214a..1770829 100644 --- a/src/repository/auth/tracing.go +++ b/src/repository/auth/tracing.go @@ -1,8 +1,10 @@ +// Code generated . DO NOT EDIT. package auth import ( "context" - "fmt" + "encoding/json" + "github.com/IceBearAI/aigc/src/repository/types" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" @@ -13,147 +15,307 @@ type tracing struct { tracer opentracing.Tracer } -func (s *tracing) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateTenant", opentracing.Tag{ +func (s *tracing) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.UpdateTenant(ctx, data) + + return s.next.CreateAccount(ctx, data) + } -func (s *tracing) DeleteTenant(ctx context.Context, id uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteTenant", opentracing.Tag{ +func (s *tracing) CreateTenant(ctx context.Context, data *types.Tenants) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateTenant", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("id", id, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.DeleteTenant(ctx, id) + + return s.next.CreateTenant(ctx, data) + } -func (s *tracing) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListAccount", opentracing.Tag{ +func (s *tracing) DeleteAccount(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteAccount", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "res", res, "total", total, "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.ListAccount(ctx, request) + + return s.next.DeleteAccount(ctx, id) + } -func (s *tracing) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateAccount", opentracing.Tag{ +func (s *tracing) DeleteTenant(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteTenant", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.UpdateAccount(ctx, data) + + return s.next.DeleteTenant(ctx, id) + +} + +func (s *tracing) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetAccountByEmail", opentracing.Tag{ + Key: string(ext.Component), + Value: "repository.auth", + }) + defer func() { + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + span.LogKV( + "email", email, "preload", preloadJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.GetAccountByEmail(ctx, email, preload...) + } func (s *tracing) GetAccountById(ctx context.Context, id uint) (res types.Accounts, err error) { + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetAccountById", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("id", id, "res", res, "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() + return s.next.GetAccountById(ctx, id) + } -func (s *tracing) DeleteAccount(ctx context.Context, id uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteAccount", opentracing.Tag{ +func (s *tracing) GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetTenantById", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("id", id, "err", err) + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + span.LogKV( + "id", id, "preload", preloadJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.DeleteAccount(ctx, id) + + return s.next.GetTenantById(ctx, id, preload...) + } -func (s *tracing) CreateTenant(ctx context.Context, data *types.Tenants) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateTenant", opentracing.Tag{ +func (s *tracing) GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetTenantByUuid", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + span.LogKV( + "uuid", uuid, "preload", preloadJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.CreateTenant(ctx, data) + + return s.next.GetTenantByUuid(ctx, uuid, preload...) + } -func (s *tracing) ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ +func (s *tracing) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListAccount", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + span.LogKV( + "request", requestJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.ListTenants(ctx, request) + + return s.next.ListAccount(ctx, request) + } -func (s *tracing) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ +func (s *tracing) ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + span.LogKV( + "request", requestJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.CreateAccount(ctx, data, tenantId) + + return s.next.ListTenants(ctx, request) + } -func (s *tracing) GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetTenantByUuid", opentracing.Tag{ +func (s *tracing) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateAccount", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("uuid", uuid, "res", res, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.GetTenantByUuid(ctx, uuid, preload...) + + return s.next.UpdateAccount(ctx, data) + } -func (s *tracing) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetAccountByEmail", opentracing.Tag{ +func (s *tracing) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateTenant", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("email", email, "res", res, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.GetAccountByEmail(ctx, email, preload...) + + return s.next.UpdateTenant(ctx, data) + } func NewTracing(otTracer opentracing.Tracer) Middleware { diff --git a/src/repository/model/logging.go b/src/repository/model/logging.go index 2f073cd..8078f45 100644 --- a/src/repository/model/logging.go +++ b/src/repository/model/logging.go @@ -1,11 +1,14 @@ +// Code generated . DO NOT EDIT. package model import ( "context" - "fmt" - "github.com/IceBearAI/aigc/src/repository/types" - "github.com/go-kit/log" + "encoding/json" "time" + + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" ) type logging struct { @@ -14,265 +17,478 @@ type logging struct { traceId string } -func (l *logging) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { +func (s *logging) CancelModelDeploy(ctx context.Context, modelId uint) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CancelModelDeploy", + "modelId", modelId, - "method", "FindByModelId", + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.FindByModelId(ctx, modelId, preloads...) + + return s.next.CancelModelDeploy(ctx, modelId) + } -func (l *logging) FindDeployPendingModels(ctx context.Context) (models []types.Models, err error) { +func (s *logging) CreateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "FindDeployPendingModels", + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CreateEval", + + "data", dataJson, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.FindDeployPendingModels(ctx) + + return s.next.CreateEval(ctx, data) + } -func (l *logging) UpdateDeployStatus(ctx context.Context, modelId uint, status types.ModelDeployStatus) (err error) { +func (s *logging) CreateModel(ctx context.Context, data *types.Models) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "UpdateDeployStatus", - "modelId", modelId, - "status", status, + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CreateModel", + + "data", dataJson, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.UpdateDeployStatus(ctx, modelId, status) + + return s.next.CreateModel(ctx, data) + } -func (l *logging) SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) { +func (s *logging) DeleteEval(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "SetModelEnabled", - "modelId", modelId, - "enabled", enabled, + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "DeleteEval", + + "id", id, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.SetModelEnabled(ctx, modelId, enabled) + + return s.next.DeleteEval(ctx, id) + } -func (l *logging) FindModelDeployByModeId(ctx context.Context, modelId uint) (res types.ModelDeploy, err error) { +func (s *logging) DeleteModel(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "FindModelDeployByModeId", - "modelId", modelId, + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "DeleteModel", + + "id", id, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.FindModelDeployByModeId(ctx, modelId) + + return s.next.DeleteModel(ctx, id) + } -func (l *logging) SaveModel(ctx context.Context, model *types.Models) (err error) { +func (s *logging) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "SaveModel", - "model", model, + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindByModelId", + + "modelId", modelId, + + "preloads", preloadsJson, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.SaveModel(ctx, model) + + return s.next.FindByModelId(ctx, modelId, preloads...) + } -func (l *logging) CancelModelDeploy(ctx context.Context, modelId uint) (err error) { +func (s *logging) FindByModelNames(ctx context.Context, modelNames []string) (models []types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "", "modelId", modelId, + + modelNamesByte, _ := json.Marshal(modelNames) + modelNamesJson := string(modelNamesByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindByModelNames", + + "modelNames", modelNamesJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.CancelModelDeploy(ctx, modelId) + + return s.next.FindByModelNames(ctx, modelNames) + } -func (l *logging) SaveModelDeploy(ctx context.Context, data *types.ModelDeploy) (err error) { +func (s *logging) FindDeployPendingModels(ctx context.Context) (models []types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "", "data", data, + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindDeployPendingModels", + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.SaveModelDeploy(ctx, data) + + return s.next.FindDeployPendingModels(ctx) + } -func (l *logging) DeleteEval(ctx context.Context, id uint) (err error) { +func (s *logging) FindModelDeployByModeId(ctx context.Context, modelId uint) (res types.ModelDeploy, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "DeleteEval", - "id", id, + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindModelDeployByModeId", + + "modelId", modelId, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.DeleteEval(ctx, id) + + return s.next.FindModelDeployByModeId(ctx, modelId) + } -func (l *logging) UpdateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { +func (s *logging) FindModelsByTenantId(ctx context.Context, tenantId uint) (res []types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "UpdateEval", - "data", fmt.Sprintf("%+v", data), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindModelsByTenantId", + + "tenantId", tenantId, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.UpdateEval(ctx, data) + + return s.next.FindModelsByTenantId(ctx, tenantId) + } -func (l *logging) GetEval(ctx context.Context, id uint) (res types.LLMEvalResults, err error) { +func (s *logging) GetEval(ctx context.Context, id uint) (res types.LLMEvalResults, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), "method", "GetEval", + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.GetEval(ctx, id) + + return s.next.GetEval(ctx, id) + } -func (l *logging) CreateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { +func (s *logging) GetModel(ctx context.Context, id uint, preload ...string) (res types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "CreateEval", - "data", fmt.Sprintf("%+v", data), + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "GetModel", + + "id", id, + + "preload", preloadJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.CreateEval(ctx, data) + + return s.next.GetModel(ctx, id, preload...) + } -func (l *logging) ListEval(ctx context.Context, request ListEvalRequest) (res []types.LLMEvalResults, total int64, err error) { +func (s *logging) GetModelByModelName(ctx context.Context, modelName string) (res types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "GetModelByModelName", + + "modelName", modelName, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.GetModelByModelName(ctx, modelName) + +} + +func (s *logging) ListEval(ctx context.Context, request ListEvalRequest) (res []types.LLMEvalResults, total int64, err error) { + + defer func(begin time.Time) { + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), "method", "ListEval", - "request", fmt.Sprintf("%+v", request), - "total", total, + + "request", requestJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.ListEval(ctx, request) + + return s.next.ListEval(ctx, request) + } -func (l *logging) ListModels(ctx context.Context, request ListModelRequest, preloads ...string) (res []types.Models, total int64, err error) { +func (s *logging) ListModels(ctx context.Context, request ListModelRequest, preloads ...string) (res []types.Models, total int64, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), "method", "ListModels", - "request", fmt.Sprintf("%+v", request), - "preloads", fmt.Sprintf("%+v", preloads), + + "request", requestJson, + + "preloads", preloadsJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.ListModels(ctx, request, preloads...) + + return s.next.ListModels(ctx, request, preloads...) + } -func (l *logging) CreateModel(ctx context.Context, data *types.Models) (err error) { +func (s *logging) SaveModel(ctx context.Context, model *types.Models) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "CreateModel", - "data", fmt.Sprintf("%+v", data), + + modelByte, _ := json.Marshal(model) + modelJson := string(modelByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "SaveModel", + + "model", modelJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.CreateModel(ctx, data) + + return s.next.SaveModel(ctx, model) + } -func (l *logging) GetModel(ctx context.Context, id uint, preload ...string) (res types.Models, err error) { +func (s *logging) SaveModelDeploy(ctx context.Context, data *types.ModelDeploy) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "GetModel", - "id", id, + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "SaveModelDeploy", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.GetModel(ctx, id, preload...) + + return s.next.SaveModelDeploy(ctx, data) + } -func (l *logging) UpdateModel(ctx context.Context, request UpdateModelRequest) (err error) { +func (s *logging) SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "UpdateModel", - "request", fmt.Sprintf("%+v", request), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "SetModelEnabled", + + "modelId", modelId, + + "enabled", enabled, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.UpdateModel(ctx, request) + + return s.next.SetModelEnabled(ctx, modelId, enabled) + } -func (l *logging) DeleteModel(ctx context.Context, id uint) (err error) { +func (s *logging) UpdateDeployStatus(ctx context.Context, modelId uint, status types.ModelDeployStatus) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "DeleteModel", - "id", id, + + statusByte, _ := json.Marshal(status) + statusJson := string(statusByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateDeployStatus", + + "modelId", modelId, + + "status", statusJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.DeleteModel(ctx, id) + + return s.next.UpdateDeployStatus(ctx, modelId, status) + } -func (l *logging) FindModelsByTenantId(ctx context.Context, tenantId uint) (res []types.Models, err error) { +func (s *logging) UpdateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "FindModelsByTenantId", - "tenantId", tenantId, + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateEval", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.FindModelsByTenantId(ctx, tenantId) + + return s.next.UpdateEval(ctx, data) + } -func (l *logging) GetModelByModelName(ctx context.Context, modelName string) (res types.Models, err error) { +func (s *logging) UpdateModel(ctx context.Context, request UpdateModelRequest) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "GetModelByModelName", - "modelName", modelName, + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateModel", + + "request", requestJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.GetModelByModelName(ctx, modelName) + + return s.next.UpdateModel(ctx, request) + } func NewLogging(logger log.Logger, traceId string) Middleware { + logger = log.With(logger, "repository.model", "logging") return func(next Service) Service { return &logging{ - logger: logger, + logger: level.Info(logger), next: next, traceId: traceId, } diff --git a/src/repository/model/service.go b/src/repository/model/service.go index 1edb29e..9e84e23 100644 --- a/src/repository/model/service.go +++ b/src/repository/model/service.go @@ -2,10 +2,11 @@ package model import ( "context" + "time" + "github.com/IceBearAI/aigc/src/helpers/page" "github.com/IceBearAI/aigc/src/repository/types" "gorm.io/gorm" - "time" ) type Middleware func(Service) Service @@ -72,12 +73,20 @@ type Service interface { SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) // FindByModelId 根据id查询模型 FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) + // 根据模型名字列表查模型 + FindByModelNames(ctx context.Context, modelNames []string) (models []types.Models, err error) } type service struct { db *gorm.DB } +// FindByModelNames implements Service. +func (s *service) FindByModelNames(ctx context.Context, modelNames []string) (models []types.Models, err error) { + err = s.db.WithContext(ctx).Where("model_name IN ?", modelNames).Find(&models).Error + return +} + func (s *service) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { db := s.db.WithContext(ctx) for _, preload := range preloads { diff --git a/src/repository/model/tracing.go b/src/repository/model/tracing.go index e87c5ef..a506c92 100644 --- a/src/repository/model/tracing.go +++ b/src/repository/model/tracing.go @@ -1,8 +1,10 @@ +// Code generated . DO NOT EDIT. package model import ( "context" - "fmt" + "encoding/json" + "github.com/IceBearAI/aigc/src/repository/types" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" @@ -13,264 +15,525 @@ type tracing struct { tracer opentracing.Tracer } -func (t *tracing) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "FindByModelId", opentracing.Tag{ +func (s *tracing) CancelModelDeploy(ctx context.Context, modelId uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CancelModelDeploy", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "err", err) + + span.LogKV( + "modelId", modelId, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.FindByModelId(ctx, modelId, preloads...) + + return s.next.CancelModelDeploy(ctx, modelId) + } -func (t *tracing) FindDeployPendingModels(ctx context.Context) (models []types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "FindDeployPendingModels", opentracing.Tag{ +func (s *tracing) CreateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.FindDeployPendingModels(ctx) + + return s.next.CreateEval(ctx, data) + } -func (t *tracing) UpdateDeployStatus(ctx context.Context, modelId uint, status types.ModelDeployStatus) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "UpdateDeployStatus", opentracing.Tag{ +func (s *tracing) CreateModel(ctx context.Context, data *types.Models) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "status", status, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.UpdateDeployStatus(ctx, modelId, status) + + return s.next.CreateModel(ctx, data) + } -func (t *tracing) SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "SetModelEnabled", opentracing.Tag{ +func (s *tracing) DeleteEval(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "enabled", enabled, "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.SetModelEnabled(ctx, modelId, enabled) + + return s.next.DeleteEval(ctx, id) + } -func (t *tracing) FindModelDeployByModeId(ctx context.Context, modelId uint) (res types.ModelDeploy, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "FindModelDeployByModeId", opentracing.Tag{ +func (s *tracing) DeleteModel(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.FindModelDeployByModeId(ctx, modelId) + + return s.next.DeleteModel(ctx, id) + } -func (t *tracing) SaveModel(ctx context.Context, model *types.Models) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "SaveModel", opentracing.Tag{ +func (s *tracing) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindByModelId", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("model", model, "err", err) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "modelId", modelId, "preloads", preloadsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.SaveModel(ctx, model) + + return s.next.FindByModelId(ctx, modelId, preloads...) + } -func (t *tracing) CancelModelDeploy(ctx context.Context, modelId uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "CancelModelDeploy", opentracing.Tag{ +func (s *tracing) FindByModelNames(ctx context.Context, modelNames []string) (models []types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindByModelNames", opentracing.Tag{ + Key: string(ext.Component), + Value: "repository.model", + }) + defer func() { + + modelNamesByte, _ := json.Marshal(modelNames) + modelNamesJson := string(modelNamesByte) + + span.LogKV( + "modelNames", modelNamesJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.FindByModelNames(ctx, modelNames) + +} + +func (s *tracing) FindDeployPendingModels(ctx context.Context) (models []types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindDeployPendingModels", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "err", err) + + span.LogKV( + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.CancelModelDeploy(ctx, modelId) + + return s.next.FindDeployPendingModels(ctx) + } -func (t *tracing) SaveModelDeploy(ctx context.Context, data *types.ModelDeploy) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "SaveModelDeploy", opentracing.Tag{ +func (s *tracing) FindModelDeployByModeId(ctx context.Context, modelId uint) (res types.ModelDeploy, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindModelDeployByModeId", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("data", data, "err", err) + + span.LogKV( + "modelId", modelId, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.SaveModelDeploy(ctx, data) + + return s.next.FindModelDeployByModeId(ctx, modelId) + } -func (t *tracing) DeleteEval(ctx context.Context, id uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "DeleteEval", opentracing.Tag{ +func (s *tracing) FindModelsByTenantId(ctx context.Context, tenantId uint) (res []types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindModelsByTenantId", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("id", id, "err", err) + + span.LogKV( + "tenantId", tenantId, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.DeleteEval(ctx, id) + + return s.next.FindModelsByTenantId(ctx, tenantId) + } -func (t *tracing) CreateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "CreateEval", opentracing.Tag{ +func (s *tracing) GetEval(ctx context.Context, id uint) (res types.LLMEvalResults, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.CreateEval(ctx, data) + + return s.next.GetEval(ctx, id) + } -func (t *tracing) ListEval(ctx context.Context, request ListEvalRequest) (res []types.LLMEvalResults, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "ListEval", opentracing.Tag{ +func (s *tracing) GetModel(ctx context.Context, id uint, preload ...string) (res types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + span.LogKV( + "id", id, "preload", preloadJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.ListEval(ctx, request) + + return s.next.GetModel(ctx, id, preload...) + } -func (t *tracing) UpdateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "UpdateEval", opentracing.Tag{ +func (s *tracing) GetModelByModelName(ctx context.Context, modelName string) (res types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetModelByModelName", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + span.LogKV( + "modelName", modelName, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.UpdateEval(ctx, data) + + return s.next.GetModelByModelName(ctx, modelName) + } -func (t *tracing) GetEval(ctx context.Context, id uint) (res types.LLMEvalResults, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "GetEval", opentracing.Tag{ +func (s *tracing) ListEval(ctx context.Context, request ListEvalRequest) (res []types.LLMEvalResults, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("id", id, "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + span.LogKV( + "request", requestJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.GetEval(ctx, id) + + return s.next.ListEval(ctx, request) + } -func (t *tracing) ListModels(ctx context.Context, request ListModelRequest, preloads ...string) (res []types.Models, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "ListModels", opentracing.Tag{ +func (s *tracing) ListModels(ctx context.Context, request ListModelRequest, preloads ...string) (res []types.Models, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListModels", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "preloads", preloads, "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "request", requestJson, "preloads", preloadsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.ListModels(ctx, request, preloads...) + + return s.next.ListModels(ctx, request, preloads...) + } -func (t *tracing) CreateModel(ctx context.Context, data *types.Models) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "CreateModel", opentracing.Tag{ +func (s *tracing) SaveModel(ctx context.Context, model *types.Models) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "SaveModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("data", data, "err", err) + + modelByte, _ := json.Marshal(model) + modelJson := string(modelByte) + + span.LogKV( + "model", modelJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.CreateModel(ctx, data) + + return s.next.SaveModel(ctx, model) + } -func (t *tracing) GetModel(ctx context.Context, id uint, preload ...string) (res types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "GetModel", opentracing.Tag{ +func (s *tracing) SaveModelDeploy(ctx context.Context, data *types.ModelDeploy) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "SaveModelDeploy", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("id", id, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.GetModel(ctx, id, preload...) + + return s.next.SaveModelDeploy(ctx, data) + } -func (t *tracing) UpdateModel(ctx context.Context, request UpdateModelRequest) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "UpdateModel", opentracing.Tag{ +func (s *tracing) SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "SetModelEnabled", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + span.LogKV( + "modelId", modelId, "enabled", enabled, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.UpdateModel(ctx, request) + + return s.next.SetModelEnabled(ctx, modelId, enabled) + } -func (t *tracing) DeleteModel(ctx context.Context, id uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "DeleteModel", opentracing.Tag{ +func (s *tracing) UpdateDeployStatus(ctx context.Context, modelId uint, status types.ModelDeployStatus) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateDeployStatus", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("id", id, "err", err) + + statusByte, _ := json.Marshal(status) + statusJson := string(statusByte) + + span.LogKV( + "modelId", modelId, "status", statusJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.DeleteModel(ctx, id) + + return s.next.UpdateDeployStatus(ctx, modelId, status) + } -func (t *tracing) FindModelsByTenantId(ctx context.Context, tenantId uint) (res []types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "FindModelsByTenantId", opentracing.Tag{ +func (s *tracing) UpdateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("tenantId", tenantId, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.FindModelsByTenantId(ctx, tenantId) + + return s.next.UpdateEval(ctx, data) + } -func (t *tracing) GetModelByModelName(ctx context.Context, modelName string) (res types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "GetModelByModelName", opentracing.Tag{ +func (s *tracing) UpdateModel(ctx context.Context, request UpdateModelRequest) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelName", modelName, "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + span.LogKV( + "request", requestJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.GetModelByModelName(ctx, modelName) + + return s.next.UpdateModel(ctx, request) + } func NewTracing(otTracer opentracing.Tracer) Middleware { diff --git a/src/repository/tenant/logging.go b/src/repository/tenant/logging.go index fcc174c..3800af9 100644 --- a/src/repository/tenant/logging.go +++ b/src/repository/tenant/logging.go @@ -1,10 +1,14 @@ +// Code generated . DO NOT EDIT. package tenant import ( "context" - "github.com/IceBearAI/aigc/src/repository/types" - "github.com/go-kit/log" + "encoding/json" "time" + + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" ) type logging struct { @@ -13,50 +17,114 @@ type logging struct { traceId string } -func (s *logging) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { +func (s *logging) AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) { + defer func(begin time.Time) { + + modelsByte, _ := json.Marshal(models) + modelsJson := string(modelsByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "FindTenantByTenantId", - "tenantId", tenantId, + "method", "AddModel", + + "id", id, + + "models", modelsJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.FindTenantByTenantId(ctx, tenantId, preloads...) + + return s.next.AddModel(ctx, id, models...) + } -func (s *logging) AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) { +func (s *logging) FindByPublicTenantIdItems(ctx context.Context, publicTenantIdItems []string, preloads ...string) (res []types.Tenants, err error) { + defer func(begin time.Time) { + + publicTenantIdItemsByte, _ := json.Marshal(publicTenantIdItems) + publicTenantIdItemsJson := string(publicTenantIdItemsByte) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "AddModel", - "id", id, + "method", "FindByPublicTenantIdItems", + + "publicTenantIdItems", publicTenantIdItemsJson, + + "preloads", preloadsJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.AddModel(ctx, id, models...) + + return s.next.FindByPublicTenantIdItems(ctx, publicTenantIdItems, preloads...) + } func (s *logging) FindTenant(ctx context.Context, id uint, preloads ...string) (res types.Tenants, err error) { + defer func(begin time.Time) { + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), "method", "FindTenant", + "id", id, + + "preloads", preloadsJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) + return s.next.FindTenant(ctx, id, preloads...) + +} + +func (s *logging) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { + + defer func(begin time.Time) { + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindTenantByTenantId", + + "tenantId", tenantId, + + "preloads", preloadsJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.FindTenantByTenantId(ctx, tenantId, preloads...) + } func NewLogging(logger log.Logger, traceId string) Middleware { logger = log.With(logger, "repository.tenant", "logging") return func(next Service) Service { return &logging{ - logger: logger, + logger: level.Info(logger), next: next, traceId: traceId, } diff --git a/src/repository/tenant/service.go b/src/repository/tenant/service.go index 794c55e..8595f92 100644 --- a/src/repository/tenant/service.go +++ b/src/repository/tenant/service.go @@ -2,6 +2,7 @@ package tenant import ( "context" + "github.com/IceBearAI/aigc/src/repository/types" "github.com/pkg/errors" "gorm.io/gorm" @@ -16,12 +17,20 @@ type Service interface { AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) // FindTenantByTenantId 通过租户ID获取租户信息 FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) + // FindByPublicTenantIdItems 通过公共租户ID获取租户信息 + FindByPublicTenantIdItems(ctx context.Context, publicTenantIdItems []string, preloads ...string) (res []types.Tenants, err error) } type service struct { db *gorm.DB } +// FindByPublicTenantIdItems implements Service. +func (s *service) FindByPublicTenantIdItems(ctx context.Context, publicTenantIdItems []string, preloads ...string) (res []types.Tenants, err error) { + err = s.db.WithContext(ctx).Where("public_tenant_id IN ?", publicTenantIdItems).Find(&res).Error + return +} + func (s service) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { db := s.db.WithContext(ctx) for _, preload := range preloads { diff --git a/src/repository/tenant/tracing.go b/src/repository/tenant/tracing.go index 32f0a86..1f1d647 100644 --- a/src/repository/tenant/tracing.go +++ b/src/repository/tenant/tracing.go @@ -1,7 +1,10 @@ +// Code generated . DO NOT EDIT. package tenant import ( "context" + "encoding/json" + "github.com/IceBearAI/aigc/src/repository/types" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" @@ -12,43 +15,111 @@ type tracing struct { tracer opentracing.Tracer } -func (s *tracing) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindTenantByTenantId", opentracing.Tag{ +func (s *tracing) AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "AddModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.tenant", }) defer func() { - span.LogKV("tenantId", tenantId, "err", err) + + modelsByte, _ := json.Marshal(models) + modelsJson := string(modelsByte) + + span.LogKV( + "id", id, "models", modelsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.FindTenantByTenantId(ctx, tenantId, preloads...) + + return s.next.AddModel(ctx, id, models...) + } -func (s *tracing) AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "AddModel", opentracing.Tag{ +func (s *tracing) FindByPublicTenantIdItems(ctx context.Context, publicTenantIdItems []string, preloads ...string) (res []types.Tenants, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindByPublicTenantIdItems", opentracing.Tag{ Key: string(ext.Component), Value: "repository.tenant", }) defer func() { - span.LogKV("id", id, "err", err) + + publicTenantIdItemsByte, _ := json.Marshal(publicTenantIdItems) + publicTenantIdItemsJson := string(publicTenantIdItemsByte) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "publicTenantIdItems", publicTenantIdItemsJson, "preloads", preloadsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.AddModel(ctx, id, models...) + + return s.next.FindByPublicTenantIdItems(ctx, publicTenantIdItems, preloads...) + } func (s *tracing) FindTenant(ctx context.Context, id uint, preloads ...string) (res types.Tenants, err error) { + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindTenant", opentracing.Tag{ Key: string(ext.Component), Value: "repository.tenant", }) defer func() { - span.LogKV("id", id, "err", err) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "id", id, "preloads", preloadsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() + return s.next.FindTenant(ctx, id, preloads...) + +} + +func (s *tracing) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindTenantByTenantId", opentracing.Tag{ + Key: string(ext.Component), + Value: "repository.tenant", + }) + defer func() { + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "tenantId", tenantId, "preloads", preloadsJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.FindTenantByTenantId(ctx, tenantId, preloads...) + } func NewTracing(otTracer opentracing.Tracer) Middleware { From c5f5a0719dc78ea57cb864f00b7eac79a2961031 Mon Sep 17 00:00:00 2001 From: "boweian@creditease.cn" Date: Thu, 6 Jun 2024 10:40:02 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pkg/sysauth/service.go | 2 +- src/repository/auth/logging.go | 29 +++++++++++++++++++++++++++-- src/repository/auth/service.go | 20 ++++++++++++++++++-- src/repository/auth/tracing.go | 30 ++++++++++++++++++++++++++++-- 4 files changed, 74 insertions(+), 7 deletions(-) diff --git a/src/pkg/sysauth/service.go b/src/pkg/sysauth/service.go index c43f02c..8972c64 100644 --- a/src/pkg/sysauth/service.go +++ b/src/pkg/sysauth/service.go @@ -253,7 +253,7 @@ func (s *service) CreateAccount(ctx context.Context, request CreateAccountReques return } - err = s.store.Auth().CreateAccount(ctx, &data) + err = s.store.Auth().CreateAccountV2(ctx, &data) if err != nil { _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) return res, err diff --git a/src/repository/auth/logging.go b/src/repository/auth/logging.go index f108e3f..3c335df 100644 --- a/src/repository/auth/logging.go +++ b/src/repository/auth/logging.go @@ -17,7 +17,7 @@ type logging struct { traceId string } -func (s *logging) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { +func (s *logging) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { defer func(begin time.Time) { @@ -30,13 +30,38 @@ func (s *logging) CreateAccount(ctx context.Context, data *types.Accounts) (err "data", dataJson, + "tenantId", tenantId, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.CreateAccount(ctx, data, tenantId) + +} + +func (s *logging) CreateAccountV2(ctx context.Context, data *types.Accounts) (err error) { + + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CreateAccountV2", + + "data", dataJson, + "took", time.Since(begin), "err", err, ) }(time.Now()) - return s.next.CreateAccount(ctx, data) + return s.next.CreateAccountV2(ctx, data) } diff --git a/src/repository/auth/service.go b/src/repository/auth/service.go index 2553898..1aebf4b 100644 --- a/src/repository/auth/service.go +++ b/src/repository/auth/service.go @@ -11,6 +11,7 @@ import ( type Middleware func(Service) Service +//go:generate gowrap.exe gen -g -p ./ -i Service -bt "ce_log:logging.go ce_trace:tracing.go" type Service interface { // GetTenantById 根据id获取租户信息 GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) @@ -27,7 +28,7 @@ type Service interface { // ListTenants 租户列表 ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) // CreateAccount 创建账号 - CreateAccount(ctx context.Context, data *types.Accounts) (err error) + CreateAccountV2(ctx context.Context, data *types.Accounts) (err error) // ListAccount 获取账号列表 ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) // UpdateAccount 更新账号 @@ -36,6 +37,8 @@ type Service interface { GetAccountById(ctx context.Context, id uint) (res types.Accounts, err error) // DeleteAccount 删除账号 DeleteAccount(ctx context.Context, id uint) (err error) + // CreateAccount 创建账号 + CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) } type ListTenantRequest struct { @@ -87,6 +90,19 @@ func (s *service) DeleteTenant(ctx context.Context, id uint) (err error) { return } +func (s *service) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { + err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + if err = tx.Create(data).Error; err != nil { + return err + } + return tx.Create(&types.TenantAccountAssociations{ + TenantID: tenantId, + AccountID: data.ID, + }).Error + }) + return +} + func (s *service) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { query := s.db.WithContext(ctx).Model(&types.Accounts{}) if request.Email != "" { @@ -157,7 +173,7 @@ func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (r return } -func (s *service) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { +func (s *service) CreateAccountV2(ctx context.Context, data *types.Accounts) (err error) { return s.db.WithContext(ctx).Save(data).Error } diff --git a/src/repository/auth/tracing.go b/src/repository/auth/tracing.go index 1770829..5f42158 100644 --- a/src/repository/auth/tracing.go +++ b/src/repository/auth/tracing.go @@ -15,7 +15,7 @@ type tracing struct { tracer opentracing.Tracer } -func (s *tracing) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { +func (s *tracing) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ Key: string(ext.Component), @@ -26,6 +26,32 @@ func (s *tracing) CreateAccount(ctx context.Context, data *types.Accounts) (err dataByte, _ := json.Marshal(data) dataJson := string(dataByte) + span.LogKV( + "data", dataJson, "tenantId", tenantId, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.CreateAccount(ctx, data, tenantId) + +} + +func (s *tracing) CreateAccountV2(ctx context.Context, data *types.Accounts) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccountV2", opentracing.Tag{ + Key: string(ext.Component), + Value: "repository.auth", + }) + defer func() { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + span.LogKV( "data", dataJson, @@ -37,7 +63,7 @@ func (s *tracing) CreateAccount(ctx context.Context, data *types.Accounts) (err span.Finish() }() - return s.next.CreateAccount(ctx, data) + return s.next.CreateAccountV2(ctx, data) } From 89dd9cc4451c2463ec484f5a45b81c1a3ba2de3e Mon Sep 17 00:00:00 2001 From: "boweian@creditease.cn" Date: Fri, 7 Jun 2024 10:02:20 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E6=8B=86=E5=88=86=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/service/service_start.go | 21 +- src/pkg/{sysauth => account}/endpoint.go | 109 +---- src/pkg/account/http.go | 271 +++++++++++ src/pkg/{sysauth => account}/logging.go | 87 +--- src/pkg/{sysauth => account}/middleware.go | 2 +- src/pkg/account/service.go | 238 ++++++++++ src/pkg/{sysauth => account}/tracing.go | 105 +---- src/pkg/{sysauth => account}/types.go | 40 +- src/pkg/auth/service.go | 3 +- src/pkg/sysauth/http.go | 504 --------------------- src/pkg/sysauth/service.go | 435 ------------------ src/pkg/sysauth/service_test.go | 33 -- src/pkg/tenant/endpoint.go | 172 +++++++ src/pkg/tenant/http.go | 248 ++++++++++ src/pkg/tenant/logging.go | 125 +++++ src/pkg/tenant/middleware.go | 3 + src/pkg/tenant/service.go | 149 ++++++ src/pkg/tenant/tracing.go | 134 ++++++ src/pkg/tenant/types.go | 43 ++ 19 files changed, 1409 insertions(+), 1313 deletions(-) rename src/pkg/{sysauth => account}/endpoint.go (54%) create mode 100644 src/pkg/account/http.go rename src/pkg/{sysauth => account}/logging.go (56%) rename src/pkg/{sysauth => account}/middleware.go (70%) create mode 100644 src/pkg/account/service.go rename src/pkg/{sysauth => account}/tracing.go (52%) rename src/pkg/{sysauth => account}/types.go (65%) delete mode 100644 src/pkg/sysauth/http.go delete mode 100644 src/pkg/sysauth/service.go delete mode 100644 src/pkg/sysauth/service_test.go create mode 100644 src/pkg/tenant/endpoint.go create mode 100644 src/pkg/tenant/http.go create mode 100644 src/pkg/tenant/logging.go create mode 100644 src/pkg/tenant/middleware.go create mode 100644 src/pkg/tenant/service.go create mode 100644 src/pkg/tenant/tracing.go create mode 100644 src/pkg/tenant/types.go diff --git a/cmd/service/service_start.go b/cmd/service/service_start.go index ff5a29c..8cdf607 100644 --- a/cmd/service/service_start.go +++ b/cmd/service/service_start.go @@ -16,6 +16,7 @@ import ( "time" tiktoken2 "github.com/IceBearAI/aigc/src/helpers/tiktoken" + "github.com/IceBearAI/aigc/src/pkg/account" "github.com/IceBearAI/aigc/src/pkg/assistants" "github.com/IceBearAI/aigc/src/pkg/auth" "github.com/IceBearAI/aigc/src/pkg/channels" @@ -27,7 +28,7 @@ import ( "github.com/IceBearAI/aigc/src/pkg/modelevaluate" "github.com/IceBearAI/aigc/src/pkg/models" "github.com/IceBearAI/aigc/src/pkg/sys" - "github.com/IceBearAI/aigc/src/pkg/sysauth" + "github.com/IceBearAI/aigc/src/pkg/tenant" "github.com/IceBearAI/aigc/src/pkg/terminal" "github.com/IceBearAI/aigc/src/pkg/tools" "github.com/IceBearAI/aigc/src/repository/types" @@ -109,7 +110,8 @@ aigc-server start -p :8080 assistantsSvc assistants.Service modelEvaluateSvc modelevaluate.Service terminalSvc terminal.Service - sysauthSvc sysauth.Service + accountSvc account.Service + tenantSvc tenant.Service ) func start(ctx context.Context) (err error) { @@ -130,6 +132,8 @@ func start(ctx context.Context) (err error) { tiktoken.SetBpeLoader(tiktoken2.NewBpeLoader(DataFs)) authSvc = auth.New(logger, traceId, store, apiSvc) + accountSvc = account.New(logger, traceId, store, apiSvc) + tenantSvc = tenant.New(logger, traceId, store, apiSvc) fileSvc = files.NewService(logger, traceId, store, apiSvc, []files.CreationOption{ files.WithLocalDataPath(serverStoragePath), files.WithServerUrl(fmt.Sprintf("%s/storage", serverDomain)), @@ -186,8 +190,8 @@ func start(ctx context.Context) (err error) { datasetTaskSvc = datasettask.NewLogging(logger, logging.TraceId)(datasetTaskSvc) modelEvaluateSvc = modelevaluate.NewLogging(logger, logging.TraceId)(modelEvaluateSvc) terminalSvc = terminal.NewLogging(logger, logging.TraceId)(terminalSvc) - sysauthSvc = sysauth.NewLogging(logger, logging.TraceId)(sysauthSvc) - + accountSvc = account.NewLogging(logger, logging.TraceId)(accountSvc) + tenantSvc = tenant.NewLogging(logger, logging.TraceId)(tenantSvc) } if tracer != nil { @@ -203,7 +207,8 @@ func start(ctx context.Context) (err error) { datasetTaskSvc = datasettask.NewTracing(tracer)(datasetTaskSvc) modelEvaluateSvc = modelevaluate.NewTracing(tracer)(modelEvaluateSvc) terminalSvc = terminal.NewTracing(tracer)(terminalSvc) - sysauthSvc = sysauth.NewTracing(tracer)(sysauthSvc) + accountSvc = account.NewTracing(tracer)(accountSvc) + tenantSvc = tenant.NewTracing(tracer)(tenantSvc) } g := &group.Group{} @@ -308,8 +313,10 @@ func initHttpHandler(ctx context.Context, g *group.Group) { r := mux.NewRouter() // auth模块 r.PathPrefix("/api/auth").Handler(http.StripPrefix("/api/auth", auth.MakeHTTPHandler(authSvc, authEms, opts))) - // sysauth模块 - r.PathPrefix("/api/sysauth").Handler(http.StripPrefix("/api/sysauth", sysauth.MakeHTTPHandler(sysauthSvc, authEms, opts))) + // account模块 + r.PathPrefix("/api/accounts").Handler(http.StripPrefix("/api", account.MakeHTTPHandler(accountSvc, authEms, opts))) + // tenant模块 + r.PathPrefix("/api/tenants").Handler(http.StripPrefix("/api", tenant.MakeHTTPHandler(tenantSvc, authEms, opts))) // file模块 r.PathPrefix("/api/files").Handler(http.StripPrefix("/api", files.MakeHTTPHandler(fileSvc, authEms, opts))) // channel模块 diff --git a/src/pkg/sysauth/endpoint.go b/src/pkg/account/endpoint.go similarity index 54% rename from src/pkg/sysauth/endpoint.go rename to src/pkg/account/endpoint.go index 99ff881..84fd45f 100644 --- a/src/pkg/sysauth/endpoint.go +++ b/src/pkg/account/endpoint.go @@ -1,5 +1,5 @@ // Code generated . DO NOT EDIT. -package sysauth +package account import ( "context" @@ -9,25 +9,18 @@ import ( ) const ( - AccountMethodName = "Account" CreateAccountMethodName = "CreateAccount" - CreateTenantMethodName = "CreateTenant" DeleteAccountMethodName = "DeleteAccount" - DeleteTenantMethodName = "DeleteTenant" ListAccountMethodName = "ListAccount" - ListTenantsMethodName = "ListTenants" - - LoginMethodName = "Login" UpdateAccountMethodName = "UpdateAccount" - UpdateTenantMethodName = "UpdateTenant" ) type Endpoints struct { @@ -57,60 +50,39 @@ func NewEndpoint(s Service, dmw map[string][]endpoint.Middleware) Endpoints { CreateAccountEndpoint: makeCreateAccountEndpoint(s), - CreateTenantEndpoint: makeCreateTenantEndpoint(s), DeleteAccountEndpoint: makeDeleteAccountEndpoint(s), - DeleteTenantEndpoint: makeDeleteTenantEndpoint(s), ListAccountEndpoint: makeListAccountEndpoint(s), - ListTenantsEndpoint: makeListTenantsEndpoint(s), UpdateAccountEndpoint: makeUpdateAccountEndpoint(s), - UpdateTenantEndpoint: makeUpdateTenantEndpoint(s), } - for _, m := range dmw[AccountMethodName] { - eps.AccountEndpoint = m(eps.AccountEndpoint) - } + for _, m := range dmw[CreateAccountMethodName] { eps.CreateAccountEndpoint = m(eps.CreateAccountEndpoint) } - for _, m := range dmw[CreateTenantMethodName] { - eps.CreateTenantEndpoint = m(eps.CreateTenantEndpoint) - } for _, m := range dmw[DeleteAccountMethodName] { eps.DeleteAccountEndpoint = m(eps.DeleteAccountEndpoint) } - for _, m := range dmw[DeleteTenantMethodName] { - eps.DeleteTenantEndpoint = m(eps.DeleteTenantEndpoint) - } for _, m := range dmw[ListAccountMethodName] { eps.ListAccountEndpoint = m(eps.ListAccountEndpoint) } - for _, m := range dmw[ListTenantsMethodName] { - eps.ListTenantsEndpoint = m(eps.ListTenantsEndpoint) - } - for _, m := range dmw[LoginMethodName] { - eps.LoginEndpoint = m(eps.LoginEndpoint) - } for _, m := range dmw[UpdateAccountMethodName] { eps.UpdateAccountEndpoint = m(eps.UpdateAccountEndpoint) } - for _, m := range dmw[UpdateTenantMethodName] { - eps.UpdateTenantEndpoint = m(eps.UpdateTenantEndpoint) - } return eps } @@ -136,26 +108,7 @@ func makeCreateAccountEndpoint(s Service) endpoint.Endpoint { } } -func makeCreateTenantEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - - req := request.(CreateTenantRequest) - - var res TenantDetail - - res, err = s.CreateTenant( - ctx, - - req, - ) - - return encode.Response{ - Data: res, - Error: err, - }, nil - } -} func makeDeleteAccountEndpoint(s Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { @@ -176,24 +129,7 @@ func makeDeleteAccountEndpoint(s Service) endpoint.Endpoint { } } -func makeDeleteTenantEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - - req := request.(DeleteTenantRequest) - - err = s.DeleteTenant( - ctx, - - req.Id, - ) - return encode.Response{ - Data: map[string]interface{}{}, - Error: err, - }, nil - - } -} func makeListAccountEndpoint(s Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { @@ -220,30 +156,7 @@ func makeListAccountEndpoint(s Service) endpoint.Endpoint { } } -func makeListTenantsEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - - req := request.(ListTenantRequest) - var list []TenantDetail - - var total int64 - - list, total, err = s.ListTenants( - ctx, - - req, - ) - - return encode.Response{ - Data: map[string]interface{}{ - "list": list, - "total": total}, - Error: err, - }, nil - - } -} @@ -266,21 +179,3 @@ func makeUpdateAccountEndpoint(s Service) endpoint.Endpoint { } } -func makeUpdateTenantEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - - req := request.(UpdateTenantRequest) - - err = s.UpdateTenant( - ctx, - - req, - ) - - return encode.Response{ - Data: map[string]interface{}{}, - Error: err, - }, nil - - } -} diff --git a/src/pkg/account/http.go b/src/pkg/account/http.go new file mode 100644 index 0000000..766bbe3 --- /dev/null +++ b/src/pkg/account/http.go @@ -0,0 +1,271 @@ +// Code generated . DO NOT EDIT. +package account + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/IceBearAI/aigc/src/encode" + endpoint "github.com/go-kit/kit/endpoint" + kithttp "github.com/go-kit/kit/transport/http" + "github.com/go-playground/validator/v10" + "github.com/gorilla/mux" + "github.com/pkg/errors" + "github.com/spf13/cast" +) + +var validate = validator.New() +func MakeHTTPHandler(s Service, dmw []endpoint.Middleware, opts []kithttp.ServerOption) http.Handler { + var ems []endpoint.Middleware + + opts = append(opts, kithttp.ServerBefore(func(ctx context.Context, request *http.Request) context.Context { + return ctx + })) + + ems = append(ems, dmw...) + + eps := NewEndpoint(s, map[string][]endpoint.Middleware{ + + + CreateAccountMethodName: ems, + + + DeleteAccountMethodName: ems, + + + ListAccountMethodName: ems, + + + UpdateAccountMethodName: ems, + + }) + + r := mux.NewRouter() + + + r.Handle("/accounts", kithttp.NewServer( + eps.CreateAccountEndpoint, + decodeCreateAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("POST") + + + r.Handle("/accounts/{id}", kithttp.NewServer( + eps.DeleteAccountEndpoint, + decodeDeleteAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("DELETE") + + + + r.Handle("/accounts", kithttp.NewServer( + eps.ListAccountEndpoint, + decodeListAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("GET") + + + + r.Handle("/accounts/{id}", kithttp.NewServer( + eps.UpdateAccountEndpoint, + decodeUpdateAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("PUT") + + return r +} + + + +// CreateAccount +// @Summary 创建账号 +// @Description 创建账号 +// @tags Account +// @Accept json +// @Produce json +// @Param CreateAccountRequest body CreateAccountRequest true "http request body" +// @Success 200 {object} encode.Response{data=Account} +// @Router /account [POST] +func decodeCreateAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := CreateAccountRequest{} + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + + +// DeleteAccount +// @Summary 删除账号 +// @Description 删除账号 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Success 200 {object} encode.Response{} +// @Router /account/{id} [DELETE] +func decodeDeleteAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := DeleteAccountRequest{} + + var _id uint + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + + + +// ListAccount +// @Summary 获取账号列表 +// @Description 获取账号列表 +// @tags Account +// @Accept json +// @Produce json +// @Param email query string false " " +// @Param isLdap query string false " " +// @Param nickname query string false " " +// @Param page query string false " " +// @Param pageSize query string false " " +// @Success 200 {object} encode.Response{data.list=[]Account,data.total=int64} +// @Router /accounts [GET] +func decodeListAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := ListAccountRequest{} + + var _email string + + var _isLdap bool + + var _nickname string + + var _page int + + var _pageSize int + + _email = r.URL.Query().Get("email") + + _isLdapStr := r.URL.Query().Get("isLdap") + + if _isLdapStr != "" { + _isLdap, err = cast.ToBoolE(_isLdapStr) + + if err != nil { + return + } + } + + _nickname = r.URL.Query().Get("nickname") + + _pageStr := r.URL.Query().Get("page") + + if _pageStr != "" { + _page, err = cast.ToIntE(_pageStr) + + if err != nil { + return + } + } + + _pageSizeStr := r.URL.Query().Get("pageSize") + + if _pageSizeStr != "" { + _pageSize, err = cast.ToIntE(_pageSizeStr) + + if err != nil { + return + } + } + + req.Email = _email + + if _isLdapStr != "" { + req.IsLdap = &_isLdap + } + + req.Nickname = _nickname + + req.Page = _page + + req.PageSize = _pageSize + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + + + + + +// UpdateAccount +// @Summary 更新账号 +// @Description 更新账号 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Param UpdateAccountRequest body UpdateAccountRequest true "http request body" +// @Success 200 {object} encode.Response{} +// @Router /account/{id} [PUT] +func decodeUpdateAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := UpdateAccountRequest{} + + var _id uint + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + + diff --git a/src/pkg/sysauth/logging.go b/src/pkg/account/logging.go similarity index 56% rename from src/pkg/sysauth/logging.go rename to src/pkg/account/logging.go index 685a19c..40656bd 100644 --- a/src/pkg/sysauth/logging.go +++ b/src/pkg/account/logging.go @@ -1,5 +1,5 @@ // Code generated . DO NOT EDIT. -package sysauth +package account import ( "context" @@ -39,28 +39,6 @@ func (s *logging) CreateAccount(ctx context.Context, req CreateAccountRequest) ( } -func (s *logging) CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) { - - defer func(begin time.Time) { - - reqByte, _ := json.Marshal(req) - reqJson := string(reqByte) - - _ = s.logger.Log( - s.traceId, ctx.Value(s.traceId), - "method", "CreateTenant", - - "req", reqJson, - - "took", time.Since(begin), - - "err", err, - ) - }(time.Now()) - - return s.next.CreateTenant(ctx, req) - -} func (s *logging) DeleteAccount(ctx context.Context, id uint) (err error) { @@ -82,25 +60,7 @@ func (s *logging) DeleteAccount(ctx context.Context, id uint) (err error) { } -func (s *logging) DeleteTenant(ctx context.Context, id uint) (err error) { - defer func(begin time.Time) { - - _ = s.logger.Log( - s.traceId, ctx.Value(s.traceId), - "method", "DeleteTenant", - - "id", id, - - "took", time.Since(begin), - - "err", err, - ) - }(time.Now()) - - return s.next.DeleteTenant(ctx, id) - -} func (s *logging) ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) { @@ -125,29 +85,6 @@ func (s *logging) ListAccount(ctx context.Context, req ListAccountRequest) (list } -func (s *logging) ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) { - - defer func(begin time.Time) { - - reqByte, _ := json.Marshal(req) - reqJson := string(reqByte) - - _ = s.logger.Log( - s.traceId, ctx.Value(s.traceId), - "method", "ListTenants", - - "req", reqJson, - - "took", time.Since(begin), - - "err", err, - ) - }(time.Now()) - - return s.next.ListTenants(ctx, req) - -} - func (s *logging) UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) { @@ -172,28 +109,6 @@ func (s *logging) UpdateAccount(ctx context.Context, req UpdateAccountRequest) ( } -func (s *logging) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { - - defer func(begin time.Time) { - - reqByte, _ := json.Marshal(req) - reqJson := string(reqByte) - - _ = s.logger.Log( - s.traceId, ctx.Value(s.traceId), - "method", "UpdateTenant", - - "req", reqJson, - - "took", time.Since(begin), - - "err", err, - ) - }(time.Now()) - - return s.next.UpdateTenant(ctx, req) - -} func NewLogging(logger log.Logger, traceId string) Middleware { logger = log.With(logger, "pkg.auth", "logging") diff --git a/src/pkg/sysauth/middleware.go b/src/pkg/account/middleware.go similarity index 70% rename from src/pkg/sysauth/middleware.go rename to src/pkg/account/middleware.go index de714ea..5d61c91 100644 --- a/src/pkg/sysauth/middleware.go +++ b/src/pkg/account/middleware.go @@ -1,3 +1,3 @@ -package sysauth +package account type Middleware func(Service) Service diff --git a/src/pkg/account/service.go b/src/pkg/account/service.go new file mode 100644 index 0000000..1b85172 --- /dev/null +++ b/src/pkg/account/service.go @@ -0,0 +1,238 @@ +package account + +import ( + "context" + + "github.com/IceBearAI/aigc/src/encode" + "github.com/IceBearAI/aigc/src/middleware" + "github.com/IceBearAI/aigc/src/repository" + "github.com/IceBearAI/aigc/src/repository/auth" + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/IceBearAI/aigc/src/services" + "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/pkg/errors" + "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" +) + +// 用户管理 +type Service interface { + // CreateAccount 创建账号 + // @kit-http /account POST + // @kit-http-request CreateAccountRequest true + CreateAccount(ctx context.Context, req CreateAccountRequest) (res Account, err error) + // ListAccount 获取账号列表 + // @kit-http /accounts GET + // @kit-http-request ListAccountRequest + ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) + // UpdateAccount 更新账号 + // @kit-http /account/{id} PUT + // @kit-http-request UpdateAccountRequest true + UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) + + // DeleteAccount 删除账号 + // @kit-http /account/{id} DELETE + // @kit-http-request DeleteAccountRequest + DeleteAccount(ctx context.Context, id uint) (err error) +} + +type service struct { + logger log.Logger + traceId string + store repository.Repository + //rdb redis.UniversalClient + apiSvc services.Service +} + +// DeleteAccount implements Service. +func (s *service) DeleteAccount(ctx context.Context, id uint) (err error) { + err = s.store.Auth().DeleteAccount(ctx, id) + if err != nil { + err = encode.ErrSystem.Wrap(errors.Wrap(err, "删除账号失败")) + return + } + return +} + +func (s *service) UpdateAccount(ctx context.Context, request UpdateAccountRequest) (err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "UpdateAccount") + data, err := s.store.Auth().GetAccountById(ctx, request.Id) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + if errors.Is(err, gorm.ErrRecordNotFound) { + return encode.ErrAccountNotFound.Error() + } + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询账号失败")) + } + if request.Email != "" { + res, err := s.store.Auth().GetAccountByEmail(ctx, request.Email) + if err == nil && res.ID != data.ID { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", "邮箱账号已存在") + return encode.InvalidParams.Wrap(errors.Wrap(err, "要更新邮箱账号已存在")) + } + data.Email = request.Email + } + if request.Nickname != "" { + data.Nickname = request.Nickname + } + + if request.Language != "" { + data.Language = request.Language + } + + if request.Status != nil { + data.Status = *request.Status + } + if request.IsLdap != nil { + data.IsLdap = *request.IsLdap + } + + if request.Password != "" { + hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + return encode.ErrSystem.Wrap(errors.Wrap(err, "更新账号失败,请联系管理员")) + } + data.PasswordHash = string(hash) + } + + data.Tenants, err = s.store.Tenants().FindByPublicTenantIdItems(ctx, request.TenantPublicTenantIdItems) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return + } + + err = s.store.Auth().UpdateAccount(ctx, &data) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + return err + } + return nil +} + +func (s *service) ListAccount(ctx context.Context, request ListAccountRequest) (list []Account, total int64, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "ListAccount") + req := auth.ListAccountRequest{ + Page: request.Page, + PageSize: request.PageSize, + Email: request.Email, + IsLdap: request.IsLdap, + } + accounts, total, err := s.store.Auth().ListAccount(ctx, req) + if err != nil { + _ = level.Error(logger).Log("auth", "ListAccount", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询账号失败")) + return + } + for _, a := range accounts { + list = append(list, convertAccount(&a)) + } + return +} + +func (s *service) CreateAccount(ctx context.Context, request CreateAccountRequest) (res Account, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "CreateAccount") + data := types.Accounts{ + Email: request.Email, + Nickname: request.Nickname, + Language: request.Language, + IsLdap: request.IsLdap, + Status: true, + } + if !data.IsLdap { + hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) + return res, encode.ErrSystem.Wrap(errors.Wrap(err, "创建账号失败,请联系管理员")) + } + data.PasswordHash = string(hash) + } + data.Tenants, err = s.store.Tenants().FindByPublicTenantIdItems(ctx, request.TenantPublicTenantIdItems) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return + } + + err = s.store.Auth().CreateAccountV2(ctx, &data) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) + return res, err + } + res = convertAccount(&data) + return res, nil +} + +func (s *service) Account(ctx context.Context, email string) (res AccountResult, err error) { + email, ok := middleware.GetEmail(ctx) + if !ok { + _ = level.Error(s.logger).Log("auth", "Account, GetEmail error", "email", email) + return res, encode.ErrAccountNotFound.Error() + } + account, err := s.store.Auth().GetAccountByEmail(ctx, email, "Tenants") + if err != nil { + _ = level.Error(s.logger).Log("auth", "account, GetAccountByEmail error", "email", email, "err", err.Error()) + return res, encode.ErrAccountNotFound.Error() + } + res.Email = account.Email + res.Nickname = account.Nickname + res.Language = account.Language + res.Tenants = make([]Tenant, 0) + for _, t := range account.Tenants { + res.Tenants = append(res.Tenants, Tenant{ + Id: t.PublicTenantID, + Name: t.Name, + }) + } + return res, nil +} + +func convertTenant(data *types.Tenants) TenantDetail { + td := TenantDetail{ + Id: data.ID, + Name: data.Name, + PublicTenantID: data.PublicTenantID, + ContactEmail: data.ContactEmail, + CreatedAt: data.CreatedAt, + UpdatedAt: data.UpdatedAt, + } + + for _, v := range data.Models { + td.ModelNames = append(td.ModelNames, v.ModelName) + } + return td +} + +func convertAccount(data *types.Accounts) Account { + res := Account{ + Id: data.ID, + Email: data.Email, + IsLdap: data.IsLdap, + Nickname: data.Nickname, + Language: data.Language, + Status: data.Status, + CreatedAt: data.CreatedAt, + UpdatedAt: data.UpdatedAt, + } + + for _, v := range data.Tenants { + res.Tenants = append(res.Tenants, convertTenant(&v)) + } + return res + +} + +func New(logger log.Logger, traceId string, + store repository.Repository, + //rdb redis.UniversalClient, + apiSvc services.Service) Service { + return &service{ + logger: logger, + traceId: traceId, + store: store, + //rdb: rdb, + apiSvc: apiSvc, + } +} diff --git a/src/pkg/sysauth/tracing.go b/src/pkg/account/tracing.go similarity index 52% rename from src/pkg/sysauth/tracing.go rename to src/pkg/account/tracing.go index b6b1a7c..3aed9b8 100644 --- a/src/pkg/sysauth/tracing.go +++ b/src/pkg/account/tracing.go @@ -1,5 +1,5 @@ // Code generated . DO NOT EDIT. -package sysauth +package account import ( "context" @@ -19,7 +19,7 @@ func (s *tracing) CreateAccount(ctx context.Context, req CreateAccountRequest) ( span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ Key: string(ext.Component), - Value: "pkg.auth", + Value: "pkg.account", }) defer func() { @@ -41,37 +41,11 @@ func (s *tracing) CreateAccount(ctx context.Context, req CreateAccountRequest) ( } -func (s *tracing) CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) { - - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateTenant", opentracing.Tag{ - Key: string(ext.Component), - Value: "pkg.auth", - }) - defer func() { - - reqByte, _ := json.Marshal(req) - reqJson := string(reqByte) - - span.LogKV( - "req", reqJson, - - "err", err, - ) - - span.SetTag(string(ext.Error), err != nil) - - span.Finish() - }() - - return s.next.CreateTenant(ctx, req) - -} - func (s *tracing) DeleteAccount(ctx context.Context, id uint) (err error) { span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteAccount", opentracing.Tag{ Key: string(ext.Component), - Value: "pkg.auth", + Value: "pkg.account", }) defer func() { @@ -90,34 +64,13 @@ func (s *tracing) DeleteAccount(ctx context.Context, id uint) (err error) { } -func (s *tracing) DeleteTenant(ctx context.Context, id uint) (err error) { - - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteTenant", opentracing.Tag{ - Key: string(ext.Component), - Value: "pkg.auth", - }) - defer func() { - - span.LogKV( - "id", id, - - "err", err, - ) - - span.SetTag(string(ext.Error), err != nil) - - span.Finish() - }() - return s.next.DeleteTenant(ctx, id) - -} func (s *tracing) ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) { span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListAccount", opentracing.Tag{ Key: string(ext.Component), - Value: "pkg.auth", + Value: "pkg.account", }) defer func() { @@ -139,38 +92,14 @@ func (s *tracing) ListAccount(ctx context.Context, req ListAccountRequest) (list } -func (s *tracing) ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ - Key: string(ext.Component), - Value: "pkg.auth", - }) - defer func() { - - reqByte, _ := json.Marshal(req) - reqJson := string(reqByte) - - span.LogKV( - "req", reqJson, - - "err", err, - ) - - span.SetTag(string(ext.Error), err != nil) - - span.Finish() - }() - - return s.next.ListTenants(ctx, req) - -} func (s *tracing) UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) { span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateAccount", opentracing.Tag{ Key: string(ext.Component), - Value: "pkg.auth", + Value: "pkg.account", }) defer func() { @@ -192,31 +121,7 @@ func (s *tracing) UpdateAccount(ctx context.Context, req UpdateAccountRequest) ( } -func (s *tracing) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateTenant", opentracing.Tag{ - Key: string(ext.Component), - Value: "pkg.auth", - }) - defer func() { - - reqByte, _ := json.Marshal(req) - reqJson := string(reqByte) - - span.LogKV( - "req", reqJson, - - "err", err, - ) - - span.SetTag(string(ext.Error), err != nil) - - span.Finish() - }() - - return s.next.UpdateTenant(ctx, req) - -} func NewTracing(otTracer opentracing.Tracer) Middleware { return func(next Service) Service { diff --git a/src/pkg/sysauth/types.go b/src/pkg/account/types.go similarity index 65% rename from src/pkg/sysauth/types.go rename to src/pkg/account/types.go index 020eeff..9f291ea 100644 --- a/src/pkg/sysauth/types.go +++ b/src/pkg/account/types.go @@ -1,22 +1,7 @@ -package sysauth +package account import "time" -type LoginRequest struct { - // Username 登陆用户的邮箱或邮箱前缀 - Username string `json:"username" validate:"required" param:",username"` - // Username 登陆用户的邮箱密码 - Password string `json:"password" validate:"required" param:",password"` -} - -type LoginResult struct { - // Token jwt token - Token string `json:"token"` - // Username 登陆用户的姓名 - Username string `json:"username"` - // Avatar 登陆用户的头像地址 - Avatar string `json:"avatar,omitempty"` -} type AccountRequest struct { Email string `json:"email" param:",email"` } @@ -44,12 +29,6 @@ type TenantDetail struct { UpdatedAt time.Time `json:"updatedAt"` } -type ListTenantRequest struct { - Page int `json:"page" param:"query,page"` - PageSize int `json:"pageSize" param:"query,pageSize"` - Name string `json:"name" param:"query,name"` -} - type CreateAccountRequest struct { Nickname string `json:"nickname" validate:"required"` Email string `json:"email" validate:"required"` @@ -82,12 +61,6 @@ type ListAccountRequest struct { Status *bool `json:"status,omitempty"` } -type CreateTenantRequest struct { - Name string `json:"name" validate:"required"` - ContactEmail string `json:"contactEmail" validate:"required"` - ModelNames []string `json:"modelNames"` -} - type UpdateAccountRequest struct { Id uint `json:"id" param:"path,id" validate:"required"` Nickname string `json:"nickname"` @@ -102,14 +75,3 @@ type UpdateAccountRequest struct { type DeleteAccountRequest struct { Id uint `json:"id" validate:"required" param:"path,id"` } - -type DeleteTenantRequest struct { - Id uint `json:"publicTenantId" validate:"required" param:"path,id"` -} - -type UpdateTenantRequest struct { - Id uint `json:"id" param:"path,id" validate:"required"` - Name string `json:"name" validate:"required"` - ContactEmail string `json:"contactEmail" validate:"required"` - ModelNames []string `json:"modelNames"` -} diff --git a/src/pkg/auth/service.go b/src/pkg/auth/service.go index 543516e..2351102 100644 --- a/src/pkg/auth/service.go +++ b/src/pkg/auth/service.go @@ -2,6 +2,8 @@ package auth import ( "context" + "time" + "github.com/IceBearAI/aigc/src/encode" authjwt "github.com/IceBearAI/aigc/src/jwt" "github.com/IceBearAI/aigc/src/repository" @@ -15,7 +17,6 @@ import ( "github.com/pkg/errors" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" - "time" ) type Service interface { diff --git a/src/pkg/sysauth/http.go b/src/pkg/sysauth/http.go deleted file mode 100644 index 51c3d49..0000000 --- a/src/pkg/sysauth/http.go +++ /dev/null @@ -1,504 +0,0 @@ -// Code generated . DO NOT EDIT. -package sysauth - -import ( - "context" - "encoding/json" - "net/http" - - "github.com/IceBearAI/aigc/src/encode" - endpoint "github.com/go-kit/kit/endpoint" - kithttp "github.com/go-kit/kit/transport/http" - "github.com/go-playground/validator/v10" - "github.com/gorilla/mux" - "github.com/pkg/errors" - "github.com/spf13/cast" -) - -var validate = validator.New() -func MakeHTTPHandler(s Service, dmw []endpoint.Middleware, opts []kithttp.ServerOption) http.Handler { - var ems []endpoint.Middleware - - opts = append(opts, kithttp.ServerBefore(func(ctx context.Context, request *http.Request) context.Context { - return ctx - })) - - ems = append(ems, dmw...) - - eps := NewEndpoint(s, map[string][]endpoint.Middleware{ - - AccountMethodName: ems, - - CreateAccountMethodName: ems, - - CreateTenantMethodName: ems, - - DeleteAccountMethodName: ems, - - DeleteTenantMethodName: ems, - - ListAccountMethodName: ems, - - ListTenantsMethodName: ems, - - LoginMethodName: ems, - - UpdateAccountMethodName: ems, - - UpdateTenantMethodName: ems, - }) - - r := mux.NewRouter() - - r.Handle("/account", kithttp.NewServer( - eps.AccountEndpoint, - decodeAccountRequest, - encode.JsonResponse, - opts..., - )).Methods("GET") - - r.Handle("/account", kithttp.NewServer( - eps.CreateAccountEndpoint, - decodeCreateAccountRequest, - encode.JsonResponse, - opts..., - )).Methods("POST") - - r.Handle("/tenants", kithttp.NewServer( - eps.CreateTenantEndpoint, - decodeCreateTenantRequest, - encode.JsonResponse, - opts..., - )).Methods("POST") - - r.Handle("/account/{id}", kithttp.NewServer( - eps.DeleteAccountEndpoint, - decodeDeleteAccountRequest, - encode.JsonResponse, - opts..., - )).Methods("DELETE") - - r.Handle("/tenant/{id}", kithttp.NewServer( - eps.DeleteTenantEndpoint, - decodeDeleteTenantRequest, - encode.JsonResponse, - opts..., - )).Methods("DELETE") - - r.Handle("/accounts", kithttp.NewServer( - eps.ListAccountEndpoint, - decodeListAccountRequest, - encode.JsonResponse, - opts..., - )).Methods("GET") - - r.Handle("/tenants", kithttp.NewServer( - eps.ListTenantsEndpoint, - decodeListTenantsRequest, - encode.JsonResponse, - opts..., - )).Methods("GET") - - r.Handle("/login", kithttp.NewServer( - eps.LoginEndpoint, - decodeLoginRequest, - encode.JsonResponse, - opts..., - )).Methods("POST") - - r.Handle("/account/{id}", kithttp.NewServer( - eps.UpdateAccountEndpoint, - decodeUpdateAccountRequest, - encode.JsonResponse, - opts..., - )).Methods("PUT") - - r.Handle("/tenant/{id}", kithttp.NewServer( - eps.UpdateTenantEndpoint, - decodeUpdateTenantRequest, - encode.JsonResponse, - opts..., - )).Methods("PUT") - - return r -} - -// Account -// @Summary 获取账号信息 -// @Description 获取账号信息 -// @tags Account -// @Accept json -// @Produce json -// @Success 200 {object} encode.Response{data=AccountResult} -// @Router /account [GET] -func decodeAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := AccountRequest{} - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// CreateAccount -// @Summary 创建账号 -// @Description 创建账号 -// @tags Account -// @Accept json -// @Produce json -// @Param CreateAccountRequest body CreateAccountRequest true "http request body" -// @Success 200 {object} encode.Response{data=Account} -// @Router /account [POST] -func decodeCreateAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := CreateAccountRequest{} - - err = json.NewDecoder(r.Body).Decode(&req) - - if err != nil { - err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) - return - } - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// CreateTenant -// @Summary 创建租户 -// @Description 创建租户 -// @tags Account -// @Accept json -// @Produce json -// @Param CreateTenantRequest body CreateTenantRequest true "http request body" -// @Success 200 {object} encode.Response{data=TenantDetail} -// @Router /tenants [POST] -func decodeCreateTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := CreateTenantRequest{} - - err = json.NewDecoder(r.Body).Decode(&req) - - if err != nil { - err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) - return - } - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// DeleteAccount -// @Summary 删除账号 -// @Description 删除账号 -// @tags Account -// @Accept json -// @Produce json -// @Param id path string true " " -// @Success 200 {object} encode.Response{} -// @Router /account/{id} [DELETE] -func decodeDeleteAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := DeleteAccountRequest{} - - var _id uint - - vars := mux.Vars(r) - - _id, err = cast.ToUintE(vars["id"]) - - if err != nil { - return - } - - req.Id = _id - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// DeleteTenant -// @Summary 删除租户 -// @Description 删除租户 -// @tags Account -// @Accept json -// @Produce json -// @Param id path string true " " -// @Success 200 {object} encode.Response{} -// @Router /tenant/{id} [DELETE] -func decodeDeleteTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := DeleteTenantRequest{} - - var _id uint - - vars := mux.Vars(r) - - _id, err = cast.ToUintE(vars["id"]) - - if err != nil { - return - } - - req.Id = _id - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// ListAccount -// @Summary 获取账号列表 -// @Description 获取账号列表 -// @tags Account -// @Accept json -// @Produce json -// @Param email query string false " " -// @Param isLdap query string false " " -// @Param nickname query string false " " -// @Param page query string false " " -// @Param pageSize query string false " " -// @Success 200 {object} encode.Response{data.list=[]Account,data.total=int64} -// @Router /accounts [GET] -func decodeListAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := ListAccountRequest{} - - var _email string - - var _isLdap bool - - var _nickname string - - var _page int - - var _pageSize int - - _email = r.URL.Query().Get("email") - - _isLdapStr := r.URL.Query().Get("isLdap") - - if _isLdapStr != "" { - _isLdap, err = cast.ToBoolE(_isLdapStr) - - if err != nil { - return - } - } - - _nickname = r.URL.Query().Get("nickname") - - _pageStr := r.URL.Query().Get("page") - - if _pageStr != "" { - _page, err = cast.ToIntE(_pageStr) - - if err != nil { - return - } - } - - _pageSizeStr := r.URL.Query().Get("pageSize") - - if _pageSizeStr != "" { - _pageSize, err = cast.ToIntE(_pageSizeStr) - - if err != nil { - return - } - } - - req.Email = _email - - if _isLdapStr != "" { - req.IsLdap = &_isLdap - } - - req.Nickname = _nickname - - req.Page = _page - - req.PageSize = _pageSize - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// ListTenants -// @Summary 获取租户列表 -// @Description 获取租户列表 -// @tags Account -// @Accept json -// @Produce json -// @Param name query string false " " -// @Param page query string false " " -// @Param pageSize query string false " " -// @Success 200 {object} encode.Response{data.list=[]TenantDetail,data.total=int64} -// @Router /tenants [GET] -func decodeListTenantsRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := ListTenantRequest{} - - var _name string - - var _page int - - var _pageSize int - - _name = r.URL.Query().Get("name") - - _pageStr := r.URL.Query().Get("page") - - if _pageStr != "" { - _page, err = cast.ToIntE(_pageStr) - - if err != nil { - return - } - } - - _pageSizeStr := r.URL.Query().Get("pageSize") - - if _pageSizeStr != "" { - _pageSize, err = cast.ToIntE(_pageSizeStr) - - if err != nil { - return - } - } - - req.Name = _name - - req.Page = _page - - req.PageSize = _pageSize - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// Login -// @Summary 平台授权登陆 -// @Description 平台授权登陆 -// @tags Account -// @Accept json -// @Produce json -// @Param LoginRequest body LoginRequest true "http request body" -// @Success 200 {object} encode.Response{data=LoginResult} -// @Router /login [POST] -func decodeLoginRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := LoginRequest{} - - err = json.NewDecoder(r.Body).Decode(&req) - - if err != nil { - err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) - return - } - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// UpdateAccount -// @Summary 更新账号 -// @Description 更新账号 -// @tags Account -// @Accept json -// @Produce json -// @Param id path string true " " -// @Param UpdateAccountRequest body UpdateAccountRequest true "http request body" -// @Success 200 {object} encode.Response{} -// @Router /account/{id} [PUT] -func decodeUpdateAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := UpdateAccountRequest{} - - var _id uint - - err = json.NewDecoder(r.Body).Decode(&req) - - if err != nil { - err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) - return - } - - vars := mux.Vars(r) - - _id, err = cast.ToUintE(vars["id"]) - - if err != nil { - return - } - - req.Id = _id - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} - -// UpdateTenant -// @Summary 更新租户 -// @Description 更新租户 -// @tags Account -// @Accept json -// @Produce json -// @Param id path string true " " -// @Param UpdateTenantRequest body UpdateTenantRequest true "http request body" -// @Success 200 {object} encode.Response{} -// @Router /tenant/{id} [PUT] -func decodeUpdateTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { - - req := UpdateTenantRequest{} - - var _id uint - - err = json.NewDecoder(r.Body).Decode(&req) - - if err != nil { - err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) - return - } - - vars := mux.Vars(r) - - _id, err = cast.ToUintE(vars["id"]) - - if err != nil { - return - } - - req.Id = _id - -err = validate.Struct(req) - if err != nil { - return nil, encode.InvalidParams.Wrap(err) - } - return req, err -} diff --git a/src/pkg/sysauth/service.go b/src/pkg/sysauth/service.go deleted file mode 100644 index 8972c64..0000000 --- a/src/pkg/sysauth/service.go +++ /dev/null @@ -1,435 +0,0 @@ -package sysauth - -import ( - "context" - "time" - - "github.com/IceBearAI/aigc/src/encode" - authjwt "github.com/IceBearAI/aigc/src/jwt" - "github.com/IceBearAI/aigc/src/middleware" - "github.com/IceBearAI/aigc/src/repository" - "github.com/IceBearAI/aigc/src/repository/auth" - "github.com/IceBearAI/aigc/src/repository/types" - "github.com/IceBearAI/aigc/src/services" - "github.com/go-kit/log" - "github.com/go-kit/log/level" - jwt2 "github.com/golang-jwt/jwt/v4" - "github.com/google/uuid" - "github.com/pkg/errors" - "golang.org/x/crypto/bcrypt" - "gorm.io/gorm" -) - -// 用户管理 -// @tags Account -type Service interface { - // ListTenants 获取租户列表 - // @kit-http /tenants GET - // @kit-http-request ListTenantRequest - ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) - - // UpdateTenant 更新租户 - // @kit-http /tenant/{id} PUT - // @kit-http-request UpdateTenantRequest true - UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) - // CreateTenant 创建租户 - // @kit-http /tenants POST - // @kit-http-request CreateTenantRequest true - CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) - // DeleteTenant 删除租户 - // @kit-http /tenant/{id} DELETE - // @kit-http-request DeleteTenantRequest - DeleteTenant(ctx context.Context, id uint) (err error) - // CreateAccount 创建账号 - // @kit-http /account POST - // @kit-http-request CreateAccountRequest true - CreateAccount(ctx context.Context, req CreateAccountRequest) (res Account, err error) - // ListAccount 获取账号列表 - // @kit-http /accounts GET - // @kit-http-request ListAccountRequest - ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) - // UpdateAccount 更新账号 - // @kit-http /account/{id} PUT - // @kit-http-request UpdateAccountRequest true - UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) - - // DeleteAccount 删除账号 - // @kit-http /account/{id} DELETE - // @kit-http-request DeleteAccountRequest - DeleteAccount(ctx context.Context, id uint) (err error) -} - -type service struct { - logger log.Logger - traceId string - store repository.Repository - //rdb redis.UniversalClient - apiSvc services.Service -} - -// UpdateTenant implements Service. -func (s *service) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { - t, err := s.store.Auth().GetTenantById(ctx, req.Id) - if err != nil { - return encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) - } - - t.Name = req.Name - t.ContactEmail = req.ContactEmail - t.Models, err = s.store.Model().FindByModelNames(ctx, req.ModelNames) - if err != nil { - return encode.ErrSystem.Wrap(errors.Wrap(err, "查询模型失败")) - } - - err = s.store.Auth().UpdateTenant(ctx, &t) - if err != nil { - return encode.ErrSystem.Wrap(errors.Wrap(err, "更新租户失败")) - } - - return -} - -// DeleteTenant implements Service. -func (s *service) DeleteTenant(ctx context.Context, id uint) (err error) { - err = s.store.Auth().DeleteTenant(ctx, id) - if err != nil { - err = encode.ErrSystem.Wrap(errors.Wrap(err, "删除租户失败")) - return - } - return -} - -// DeleteAccount implements Service. -func (s *service) DeleteAccount(ctx context.Context, id uint) (err error) { - err = s.store.Auth().DeleteAccount(ctx, id) - if err != nil { - err = encode.ErrSystem.Wrap(errors.Wrap(err, "删除账号失败")) - return - } - return -} - -func (s *service) UpdateAccount(ctx context.Context, request UpdateAccountRequest) (err error) { - logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "UpdateAccount") - data, err := s.store.Auth().GetAccountById(ctx, request.Id) - if err != nil { - _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) - if errors.Is(err, gorm.ErrRecordNotFound) { - return encode.ErrAccountNotFound.Error() - } - return encode.ErrSystem.Wrap(errors.Wrap(err, "查询账号失败")) - } - if request.Email != "" { - res, err := s.store.Auth().GetAccountByEmail(ctx, request.Email) - if err == nil && res.ID != data.ID { - _ = level.Error(logger).Log("auth", "UpdateAccount", "err", "邮箱账号已存在") - return encode.InvalidParams.Wrap(errors.Wrap(err, "要更新邮箱账号已存在")) - } - data.Email = request.Email - } - if request.Nickname != "" { - data.Nickname = request.Nickname - } - - if request.Language != "" { - data.Language = request.Language - } - - if request.Status != nil { - data.Status = *request.Status - } - if request.IsLdap != nil { - data.IsLdap = *request.IsLdap - } - - if request.Password != "" { - hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost) - if err != nil { - _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) - return encode.ErrSystem.Wrap(errors.Wrap(err, "更新账号失败,请联系管理员")) - } - data.PasswordHash = string(hash) - } - - data.Tenants, err = s.store.Tenants().FindByPublicTenantIdItems(ctx, request.TenantPublicTenantIdItems) - if err != nil { - _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) - err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) - return - } - - err = s.store.Auth().UpdateAccount(ctx, &data) - if err != nil { - _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) - return err - } - return nil -} - -func (s *service) ListAccount(ctx context.Context, request ListAccountRequest) (list []Account, total int64, err error) { - logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "ListAccount") - req := auth.ListAccountRequest{ - Page: request.Page, - PageSize: request.PageSize, - Email: request.Email, - IsLdap: request.IsLdap, - } - accounts, total, err := s.store.Auth().ListAccount(ctx, req) - if err != nil { - _ = level.Error(logger).Log("auth", "ListAccount", "err", err.Error()) - err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询账号失败")) - return - } - for _, a := range accounts { - list = append(list, convertAccount(&a)) - } - return -} - -func (s *service) CreateTenant(ctx context.Context, request CreateTenantRequest) (res TenantDetail, err error) { - logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "CreateTenant") - data := types.Tenants{ - Name: request.Name, - PublicTenantID: uuid.New().String(), - ContactEmail: request.ContactEmail, - } - - models, err := s.store.Model().FindByModelNames(ctx, request.ModelNames) - if err != nil { - _ = level.Error(logger).Log("auth", "CreateTenant", "err", err.Error()) - err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询模型失败")) - return res, err - } - data.Models = models - err = s.store.Auth().CreateTenant(ctx, &data) - if err != nil { - _ = level.Error(logger).Log("auth", "CreateTenant", "err", err.Error()) - return res, err - } - res = convertTenant(&data) - return res, nil -} - -func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (list []TenantDetail, total int64, err error) { - logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "ListTenants") - req := auth.ListTenantRequest{ - Page: request.Page, - PageSize: request.PageSize, - Name: request.Name, - } - tenants, total, err := s.store.Auth().ListTenants(ctx, req) - if err != nil { - _ = level.Error(logger).Log("auth", "ListTenants", "err", err.Error()) - err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) - return - } - for _, t := range tenants { - list = append(list, convertTenant(&t)) - } - return -} - -func (s *service) CreateAccount(ctx context.Context, request CreateAccountRequest) (res Account, err error) { - logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "CreateAccount") - data := types.Accounts{ - Email: request.Email, - Nickname: request.Nickname, - Language: request.Language, - IsLdap: request.IsLdap, - Status: true, - } - if !data.IsLdap { - hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost) - if err != nil { - _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) - return res, encode.ErrSystem.Wrap(errors.Wrap(err, "创建账号失败,请联系管理员")) - } - data.PasswordHash = string(hash) - } - data.Tenants, err = s.store.Tenants().FindByPublicTenantIdItems(ctx, request.TenantPublicTenantIdItems) - if err != nil { - _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) - err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) - return - } - - err = s.store.Auth().CreateAccountV2(ctx, &data) - if err != nil { - _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) - return res, err - } - res = convertAccount(&data) - return res, nil -} - -func (s *service) Account(ctx context.Context, email string) (res AccountResult, err error) { - email, ok := middleware.GetEmail(ctx) - if !ok { - _ = level.Error(s.logger).Log("auth", "Account, GetEmail error", "email", email) - return res, encode.ErrAccountNotFound.Error() - } - account, err := s.store.Auth().GetAccountByEmail(ctx, email, "Tenants") - if err != nil { - _ = level.Error(s.logger).Log("auth", "account, GetAccountByEmail error", "email", email, "err", err.Error()) - return res, encode.ErrAccountNotFound.Error() - } - res.Email = account.Email - res.Nickname = account.Nickname - res.Language = account.Language - res.Tenants = make([]Tenant, 0) - for _, t := range account.Tenants { - res.Tenants = append(res.Tenants, Tenant{ - Id: t.PublicTenantID, - Name: t.Name, - }) - } - return res, nil -} - -func (s *service) Login(ctx context.Context, req LoginRequest) (res LoginResult, err error) { - logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId)) - username := req.Username - password := req.Password - if username == "" || password == "" { - _ = level.Error(logger).Log("auth", "login, username or password is empty", "username", username, "password", password) - return res, encode.ErrAccountLogin.Error() - } - - //loginKey := fmt.Sprintf("aigc:auth:login:%s", username) - //if s.rdb.Incr(ctx, loginKey).Val() > 1 { - // _ = s.rdb.Expire(ctx, loginKey, time.Minute).Err() - // _ = level.Error(logger).Log("auth", "login", "username", username, "err", encode.ErrLimiter.Error()) - // return res, encode.ErrLimiter.Error() - //} - //defer func() { - // _ = s.rdb.Del(ctx, loginKey).Err() - //}() - // - //errLoginKey := fmt.Sprintf("aigc:auth:login:err:%s", username) - //errNum, err := s.rdb.Get(ctx, errLoginKey).Int() - //if err != nil && !errors.Is(err, redis.Nil) { - // _ = level.Error(logger).Log("auth", "login, redis get errLoginKey error", "username", username, "err", err.Error()) - // return res, encode.ErrSystem.Wrap(errors.Wrap(err,"登录失败,请联系管理员")) - //} - //if errNum >= 5 { - // _ = level.Error(logger).Log("auth", "login too many error times", "username", username, "err", encode.ErrLimiter.Error()) - // return res, encode.ErrAccountLocked.Error() - //} - - // 获取账号信息 - account, err := s.store.Auth().GetAccountByEmail(ctx, req.Username) - if err != nil { - _ = level.Error(logger).Log("auth", "login, GetAccountByEmail error", "username", username, "err", err.Error()) - return res, encode.ErrAccountNotFound.Error() - } - // 账号被锁定 - if !account.Status { - _ = level.Error(logger).Log("auth", "login, account status not active", "username", username) - return res, encode.ErrAccountLocked.Error() - } - - if account.IsLdap { - authenticate, err := s.apiSvc.Ldap().Authenticate(ctx, username, password) - if err != nil { - _ = level.Error(logger).Log("auth", "login", "username", username, "err", err.Error()) - return res, encode.ErrAccountLogin.Error() - } - if !authenticate { - //_ = s.rdb.Incr(ctx, errLoginKey).Err() - //_ = s.rdb.Expire(ctx, errLoginKey, time.Minute*30).Err() - _ = level.Error(logger).Log("auth", "login authenticate false", "username", username) - return res, encode.ErrAccountLogin.Error() - } - } else { - err = bcrypt.CompareHashAndPassword([]byte(account.PasswordHash), []byte(password)) - if err != nil { - //_ = s.rdb.Incr(ctx, errLoginKey).Err() - //_ = s.rdb.Expire(ctx, errLoginKey, time.Minute*30).Err() - _ = level.Error(logger).Log("auth", "login, bcrypt.CompareHashAndPassword error", "username", username, "err", err.Error()) - return res, encode.ErrAccountLogin.Error() - } - } - tk, err := s.jwtToken(ctx, authjwt.TokenSourceNd, time.Duration(168)*time.Hour, username, "", account.ID) - if err != nil { - _ = level.Error(logger).Log("auth", "login, jwtToken error", "username", username, "err", err.Error()) - return res, encode.ErrSystem.Wrap(errors.Wrap(err, "登录失败,请联系管理员")) - } - res.Token = tk - res.Username = username - return res, nil -} - -func (s *service) jwtToken(ctx context.Context, source authjwt.TokenSource, timeout time.Duration, email string, qwUserid string, accountId uint) (tk string, err error) { - logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId)) - expAt := jwt2.NewNumericDate(time.Now().Add(timeout)) - - // 创建声明 - claims := authjwt.ArithmeticCustomClaims{ - Source: source, - RegisteredClaims: jwt2.RegisteredClaims{ - ExpiresAt: expAt, - Issuer: "system", - }, - UserId: accountId, - } - - //不同类型,参数不一样 - claims.Email = email - - //创建token,指定加密算法为HS256 - token := jwt2.NewWithClaims(jwt2.SigningMethodHS256, claims) - //生成token - tk, err = token.SignedString([]byte(authjwt.GetJwtKey())) - if err != nil { - _ = level.Error(logger).Log("auth", "jwtToken, SignedString error", "err", err.Error(), "source", source, "email", email, "qwUserid", qwUserid, "accountId", accountId) - return tk, nil - } - return -} -func convertTenant(data *types.Tenants) TenantDetail { - td := TenantDetail{ - Id: data.ID, - Name: data.Name, - PublicTenantID: data.PublicTenantID, - ContactEmail: data.ContactEmail, - CreatedAt: data.CreatedAt, - UpdatedAt: data.UpdatedAt, - } - - for _, v := range data.Models { - td.ModelNames = append(td.ModelNames, v.ModelName) - } - return td -} - -func convertAccount(data *types.Accounts) Account { - res := Account{ - Id: data.ID, - Email: data.Email, - IsLdap: data.IsLdap, - Nickname: data.Nickname, - Language: data.Language, - Status: data.Status, - CreatedAt: data.CreatedAt, - UpdatedAt: data.UpdatedAt, - } - - for _, v := range data.Tenants { - res.Tenants = append(res.Tenants, convertTenant(&v)) - } - return res - -} - -func New(logger log.Logger, traceId string, - store repository.Repository, - //rdb redis.UniversalClient, - apiSvc services.Service) Service { - return &service{ - logger: logger, - traceId: traceId, - store: store, - //rdb: rdb, - apiSvc: apiSvc, - } -} diff --git a/src/pkg/sysauth/service_test.go b/src/pkg/sysauth/service_test.go deleted file mode 100644 index b9eedaa..0000000 --- a/src/pkg/sysauth/service_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package sysauth - -import ( - "encoding/json" - - "github.com/IceBearAI/aigc/tests" - "github.com/go-kit/log" -) - -var logger log.Logger - -func initSvc() Service { - apiSvc, err := tests.Init() - if err != nil { - panic(err) - } - - return New(logger, "", tests.Store, apiSvc) -} - -func getCurrentWeather(location string, unit string) (string, error) { - weatherInfo := map[string]interface{}{ - "location": location, - "temperature": "72", - "unit": unit, - "forecast": []string{"sunny", "windy"}, - } - b, err := json.Marshal(weatherInfo) - if err != nil { - return "", err - } - return string(b), nil -} diff --git a/src/pkg/tenant/endpoint.go b/src/pkg/tenant/endpoint.go new file mode 100644 index 0000000..48b55ff --- /dev/null +++ b/src/pkg/tenant/endpoint.go @@ -0,0 +1,172 @@ +// Code generated . DO NOT EDIT. +package tenant + +import ( + "context" + + "github.com/IceBearAI/aigc/src/encode" + endpoint "github.com/go-kit/kit/endpoint" +) + +const ( + + + CreateTenantMethodName = "CreateTenant" + + + DeleteTenantMethodName = "DeleteTenant" + + + ListTenantsMethodName = "ListTenants" + + + UpdateTenantMethodName = "UpdateTenant" +) + +type Endpoints struct { + + + CreateTenantEndpoint endpoint.Endpoint + + + DeleteTenantEndpoint endpoint.Endpoint + + + ListTenantsEndpoint endpoint.Endpoint + + + UpdateTenantEndpoint endpoint.Endpoint +} + +func NewEndpoint(s Service, dmw map[string][]endpoint.Middleware) Endpoints { + eps := Endpoints{ + + + CreateTenantEndpoint: makeCreateTenantEndpoint(s), + + + DeleteTenantEndpoint: makeDeleteTenantEndpoint(s), + + + ListTenantsEndpoint: makeListTenantsEndpoint(s), + + + UpdateTenantEndpoint: makeUpdateTenantEndpoint(s), + } + + + for _, m := range dmw[CreateTenantMethodName] { + eps.CreateTenantEndpoint = m(eps.CreateTenantEndpoint) + } + + + for _, m := range dmw[DeleteTenantMethodName] { + eps.DeleteTenantEndpoint = m(eps.DeleteTenantEndpoint) + } + + + for _, m := range dmw[ListTenantsMethodName] { + eps.ListTenantsEndpoint = m(eps.ListTenantsEndpoint) + } + + + + for _, m := range dmw[UpdateTenantMethodName] { + eps.UpdateTenantEndpoint = m(eps.UpdateTenantEndpoint) + } + + return eps +} + + + +func makeCreateTenantEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(CreateTenantRequest) + + var res TenantDetail + + res, err = s.CreateTenant( + ctx, + + req, + ) + + return encode.Response{ + Data: res, + Error: err, + }, nil + + } +} + + + +func makeDeleteTenantEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(DeleteTenantRequest) + + err = s.DeleteTenant( + ctx, + + req.Id, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + + } +} + + + +func makeListTenantsEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(ListTenantRequest) + + var list []TenantDetail + + var total int64 + + list, total, err = s.ListTenants( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{ + "list": list, + "total": total}, + Error: err, + }, nil + + } +} + + + + +func makeUpdateTenantEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(UpdateTenantRequest) + + err = s.UpdateTenant( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + + } +} diff --git a/src/pkg/tenant/http.go b/src/pkg/tenant/http.go new file mode 100644 index 0000000..e8fd086 --- /dev/null +++ b/src/pkg/tenant/http.go @@ -0,0 +1,248 @@ +// Code generated . DO NOT EDIT. +package tenant + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/IceBearAI/aigc/src/encode" + endpoint "github.com/go-kit/kit/endpoint" + kithttp "github.com/go-kit/kit/transport/http" + "github.com/go-playground/validator/v10" + "github.com/gorilla/mux" + "github.com/pkg/errors" + "github.com/spf13/cast" +) + +var validate = validator.New() +func MakeHTTPHandler(s Service, dmw []endpoint.Middleware, opts []kithttp.ServerOption) http.Handler { + var ems []endpoint.Middleware + + opts = append(opts, kithttp.ServerBefore(func(ctx context.Context, request *http.Request) context.Context { + return ctx + })) + + ems = append(ems, dmw...) + + eps := NewEndpoint(s, map[string][]endpoint.Middleware{ + + + CreateTenantMethodName: ems, + + + DeleteTenantMethodName: ems, + + + ListTenantsMethodName: ems, + + UpdateTenantMethodName: ems, + }) + + r := mux.NewRouter() + + + + + r.Handle("/tenants", kithttp.NewServer( + eps.CreateTenantEndpoint, + decodeCreateTenantRequest, + encode.JsonResponse, + opts..., + )).Methods("POST") + + + + r.Handle("/tenants/{id}", kithttp.NewServer( + eps.DeleteTenantEndpoint, + decodeDeleteTenantRequest, + encode.JsonResponse, + opts..., + )).Methods("DELETE") + + + + r.Handle("/tenants", kithttp.NewServer( + eps.ListTenantsEndpoint, + decodeListTenantsRequest, + encode.JsonResponse, + opts..., + )).Methods("GET") + + + + r.Handle("/tenants/{id}", kithttp.NewServer( + eps.UpdateTenantEndpoint, + decodeUpdateTenantRequest, + encode.JsonResponse, + opts..., + )).Methods("PUT") + + return r +} + + + + + +// CreateTenant +// @Summary 创建租户 +// @Description 创建租户 +// @tags Account +// @Accept json +// @Produce json +// @Param CreateTenantRequest body CreateTenantRequest true "http request body" +// @Success 200 {object} encode.Response{data=TenantDetail} +// @Router /tenants [POST] +func decodeCreateTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := CreateTenantRequest{} + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + + + +// DeleteTenant +// @Summary 删除租户 +// @Description 删除租户 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Success 200 {object} encode.Response{} +// @Router /tenant/{id} [DELETE] +func decodeDeleteTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := DeleteTenantRequest{} + + var _id uint + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + + + +// ListTenants +// @Summary 获取租户列表 +// @Description 获取租户列表 +// @tags Account +// @Accept json +// @Produce json +// @Param name query string false " " +// @Param page query string false " " +// @Param pageSize query string false " " +// @Success 200 {object} encode.Response{data.list=[]TenantDetail,data.total=int64} +// @Router /tenants [GET] +func decodeListTenantsRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := ListTenantRequest{} + + var _name string + + var _page int + + var _pageSize int + + _name = r.URL.Query().Get("name") + + _pageStr := r.URL.Query().Get("page") + + if _pageStr != "" { + _page, err = cast.ToIntE(_pageStr) + + if err != nil { + return + } + } + + _pageSizeStr := r.URL.Query().Get("pageSize") + + if _pageSizeStr != "" { + _pageSize, err = cast.ToIntE(_pageSizeStr) + + if err != nil { + return + } + } + + req.Name = _name + + req.Page = _page + + req.PageSize = _pageSize + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + + + + +// UpdateTenant +// @Summary 更新租户 +// @Description 更新租户 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Param UpdateTenantRequest body UpdateTenantRequest true "http request body" +// @Success 200 {object} encode.Response{} +// @Router /tenant/{id} [PUT] +func decodeUpdateTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := UpdateTenantRequest{} + + var _id uint + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} diff --git a/src/pkg/tenant/logging.go b/src/pkg/tenant/logging.go new file mode 100644 index 0000000..7bd6d52 --- /dev/null +++ b/src/pkg/tenant/logging.go @@ -0,0 +1,125 @@ +// Code generated . DO NOT EDIT. +package tenant + +import ( + "context" + "encoding/json" + "time" + + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" +) + +type logging struct { + logger log.Logger + next Service + traceId string +} + + + +func (s *logging) CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CreateTenant", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.CreateTenant(ctx, req) + +} + + + +func (s *logging) DeleteTenant(ctx context.Context, id uint) (err error) { + + defer func(begin time.Time) { + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "DeleteTenant", + + "id", id, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.DeleteTenant(ctx, id) + +} + + + +func (s *logging) ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "ListTenants", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.ListTenants(ctx, req) + +} + + + +func (s *logging) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateTenant", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.UpdateTenant(ctx, req) + +} + +func NewLogging(logger log.Logger, traceId string) Middleware { + logger = log.With(logger, "pkg.tenant", "logging") + return func(next Service) Service { + return &logging{ + logger: level.Info(logger), + next: next, + traceId: traceId, + } + } +} diff --git a/src/pkg/tenant/middleware.go b/src/pkg/tenant/middleware.go new file mode 100644 index 0000000..83e3055 --- /dev/null +++ b/src/pkg/tenant/middleware.go @@ -0,0 +1,3 @@ +package tenant + +type Middleware func(Service) Service diff --git a/src/pkg/tenant/service.go b/src/pkg/tenant/service.go new file mode 100644 index 0000000..d4323e9 --- /dev/null +++ b/src/pkg/tenant/service.go @@ -0,0 +1,149 @@ +package tenant + +import ( + "context" + + "github.com/IceBearAI/aigc/src/encode" + "github.com/IceBearAI/aigc/src/repository" + "github.com/IceBearAI/aigc/src/repository/auth" + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/IceBearAI/aigc/src/services" + "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/google/uuid" + "github.com/pkg/errors" +) + +// 用户管理 +// @tags Account +type Service interface { + // ListTenants 获取租户列表 + // @kit-http /tenants GET + // @kit-http-request ListTenantRequest + ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) + + // UpdateTenant 更新租户 + // @kit-http /tenant/{id} PUT + // @kit-http-request UpdateTenantRequest true + UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) + // CreateTenant 创建租户 + // @kit-http /tenants POST + // @kit-http-request CreateTenantRequest true + CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) + // DeleteTenant 删除租户 + // @kit-http /tenant/{id} DELETE + // @kit-http-request DeleteTenantRequest + DeleteTenant(ctx context.Context, id uint) (err error) +} + +type service struct { + logger log.Logger + traceId string + store repository.Repository + //rdb redis.UniversalClient + apiSvc services.Service +} + +// UpdateTenant implements Service. +func (s *service) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + t, err := s.store.Auth().GetTenantById(ctx, req.Id) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + } + + t.Name = req.Name + t.ContactEmail = req.ContactEmail + t.Models, err = s.store.Model().FindByModelNames(ctx, req.ModelNames) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询模型失败")) + } + + err = s.store.Auth().UpdateTenant(ctx, &t) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "更新租户失败")) + } + + return +} + +// DeleteTenant implements Service. +func (s *service) DeleteTenant(ctx context.Context, id uint) (err error) { + err = s.store.Auth().DeleteTenant(ctx, id) + if err != nil { + err = encode.ErrSystem.Wrap(errors.Wrap(err, "删除租户失败")) + return + } + return +} + +func (s *service) CreateTenant(ctx context.Context, request CreateTenantRequest) (res TenantDetail, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "CreateTenant") + data := types.Tenants{ + Name: request.Name, + PublicTenantID: uuid.New().String(), + ContactEmail: request.ContactEmail, + } + + models, err := s.store.Model().FindByModelNames(ctx, request.ModelNames) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateTenant", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询模型失败")) + return res, err + } + data.Models = models + err = s.store.Auth().CreateTenant(ctx, &data) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateTenant", "err", err.Error()) + return res, err + } + res = convertTenant(&data) + return res, nil +} + +func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (list []TenantDetail, total int64, err error) { + logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "ListTenants") + req := auth.ListTenantRequest{ + Page: request.Page, + PageSize: request.PageSize, + Name: request.Name, + } + tenants, total, err := s.store.Auth().ListTenants(ctx, req) + if err != nil { + _ = level.Error(logger).Log("auth", "ListTenants", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return + } + for _, t := range tenants { + list = append(list, convertTenant(&t)) + } + return +} + +func convertTenant(data *types.Tenants) TenantDetail { + td := TenantDetail{ + Id: data.ID, + Name: data.Name, + PublicTenantID: data.PublicTenantID, + ContactEmail: data.ContactEmail, + CreatedAt: data.CreatedAt, + UpdatedAt: data.UpdatedAt, + } + + for _, v := range data.Models { + td.ModelNames = append(td.ModelNames, v.ModelName) + } + return td +} + +func New(logger log.Logger, traceId string, + store repository.Repository, + //rdb redis.UniversalClient, + apiSvc services.Service) Service { + return &service{ + logger: logger, + traceId: traceId, + store: store, + //rdb: rdb, + apiSvc: apiSvc, + } +} diff --git a/src/pkg/tenant/tracing.go b/src/pkg/tenant/tracing.go new file mode 100644 index 0000000..547e07b --- /dev/null +++ b/src/pkg/tenant/tracing.go @@ -0,0 +1,134 @@ +// Code generated . DO NOT EDIT. +package tenant + +import ( + "context" + "encoding/json" + + "github.com/opentracing/opentracing-go" + "github.com/opentracing/opentracing-go/ext" +) + +type tracing struct { + next Service + tracer opentracing.Tracer +} + + + + +func (s *tracing) CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateTenant", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.tenant", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.CreateTenant(ctx, req) + +} + + + +func (s *tracing) DeleteTenant(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteTenant", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.tenant", + }) + defer func() { + + span.LogKV( + "id", id, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.DeleteTenant(ctx, id) + +} + + + +func (s *tracing) ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.tenant", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.ListTenants(ctx, req) + +} + + + +func (s *tracing) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateTenant", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.tenant", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.UpdateTenant(ctx, req) + +} + +func NewTracing(otTracer opentracing.Tracer) Middleware { + return func(next Service) Service { + return &tracing{ + next: next, + tracer: otTracer, + } + } +} diff --git a/src/pkg/tenant/types.go b/src/pkg/tenant/types.go new file mode 100644 index 0000000..67d78d4 --- /dev/null +++ b/src/pkg/tenant/types.go @@ -0,0 +1,43 @@ +package tenant + +import "time" + +type Tenant struct { + // TenantId 租户ID + Id string `json:"id"` + // TenantName 租户名称 + Name string `json:"name"` +} + +type TenantDetail struct { + Id uint `json:"id"` + Name string `json:"name"` + PublicTenantID string `json:"publicTenantId"` + ContactEmail string `json:"contactEmail"` + ModelNames []string `json:"modelNames"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type ListTenantRequest struct { + Page int `json:"page" param:"query,page"` + PageSize int `json:"pageSize" param:"query,pageSize"` + Name string `json:"name" param:"query,name"` +} + +type CreateTenantRequest struct { + Name string `json:"name" validate:"required"` + ContactEmail string `json:"contactEmail" validate:"required"` + ModelNames []string `json:"modelNames"` +} + +type DeleteTenantRequest struct { + Id uint `json:"publicTenantId" validate:"required" param:"path,id"` +} + +type UpdateTenantRequest struct { + Id uint `json:"id" param:"path,id" validate:"required"` + Name string `json:"name" validate:"required"` + ContactEmail string `json:"contactEmail" validate:"required"` + ModelNames []string `json:"modelNames"` +}