addapplicationlogic.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Code scaffolded by goctl. Safe to edit.
  2. // goctl 1.10.2
  3. package application
  4. import (
  5. "context"
  6. "database/sql"
  7. "strings"
  8. "udeServer/internal/apierr"
  9. "udeServer/internal/audit"
  10. "udeServer/internal/log"
  11. "udeServer/internal/model"
  12. "udeServer/internal/svc"
  13. "udeServer/internal/types"
  14. "github.com/zeromicro/go-zero/core/logx"
  15. )
  16. type AddApplicationLogic struct {
  17. logx.Logger
  18. ctx context.Context
  19. svcCtx *svc.ServiceContext
  20. }
  21. // 添加应用凭证
  22. func NewAddApplicationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddApplicationLogic {
  23. return &AddApplicationLogic{
  24. Logger: logx.WithContext(ctx),
  25. ctx: ctx,
  26. svcCtx: svcCtx,
  27. }
  28. }
  29. func (l *AddApplicationLogic) AddApplication(req *types.ApplicationCredentialsAddReq) (*types.ApplicationCredentialsAddResp, error) {
  30. if strings.TrimSpace(req.Name) == "" {
  31. return nil, apierr.BadRequest("应用名称不能为空")
  32. }
  33. // 状态缺省启用;只接受 1(启用)/2(禁用)
  34. if req.Status == 0 {
  35. req.Status = 1
  36. }
  37. if req.Status != 1 && req.Status != 2 {
  38. return nil, apierr.BadRequest("应用状态只允许 1(启用) 或 2(禁用)")
  39. }
  40. exists, err := l.svcCtx.ApplicationCredModel.ExistsByName(l.ctx, req.Name)
  41. if err != nil {
  42. log.RecordError(l.ctx, err)
  43. return nil, apierr.New(500, "添加应用凭证失败")
  44. }
  45. if exists {
  46. return nil, apierr.BadRequest("已存在同名[%s]的应用凭证", req.Name)
  47. }
  48. credIden := audit.NewUUID()
  49. data := &model.TApplicationCredentials{
  50. CredIden: credIden,
  51. Name: req.Name,
  52. ApiKey: GenerateApiKey(),
  53. ApiSecret: GenerateApiSecret(),
  54. HmacAlgo: HmacAlgo,
  55. Status: int64(req.Status),
  56. Description: sql.NullString{
  57. String: req.Description,
  58. Valid: req.Description != "",
  59. },
  60. CreatedBy: operatorName,
  61. UpdatedBy: operatorName,
  62. }
  63. if _, err := l.svcCtx.ApplicationCredModel.Insert(l.ctx, data); err != nil {
  64. log.RecordError(l.ctx, err)
  65. return nil, apierr.New(500, "添加应用凭证失败")
  66. }
  67. return &types.ApplicationCredentialsAddResp{Iden: credIden}, nil
  68. }