create_api_key_logic.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package api_key
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/base64"
  6. "fmt"
  7. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  8. "github.com/zeromicro/go-zero/core/errorx"
  9. "wechat-api/internal/svc"
  10. "wechat-api/internal/types"
  11. "wechat-api/internal/utils/dberrorhandler"
  12. "github.com/zeromicro/go-zero/core/logx"
  13. )
  14. type CreateApiKeyLogic struct {
  15. logx.Logger
  16. ctx context.Context
  17. svcCtx *svc.ServiceContext
  18. }
  19. func NewCreateApiKeyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateApiKeyLogic {
  20. return &CreateApiKeyLogic{
  21. Logger: logx.WithContext(ctx),
  22. ctx: ctx,
  23. svcCtx: svcCtx}
  24. }
  25. func (l *CreateApiKeyLogic) CreateApiKey(req *types.ApiKeyInfo) (resp *types.BaseMsgResp, err error) {
  26. organizationId := l.ctx.Value("organizationId").(uint64)
  27. apiKey, err := GenerateAPIKey("sk-", 32)
  28. if err != nil {
  29. return nil, errorx.NewCodeInternalError("Failed to generate API key")
  30. }
  31. _, err = l.svcCtx.DB.ApiKey.Create().
  32. SetTitle(*req.Title).
  33. SetKey(apiKey).
  34. SetOrganizationID(organizationId).
  35. Save(l.ctx)
  36. if err != nil {
  37. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  38. }
  39. return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
  40. }
  41. // GenerateAPIKey generates a random API key with a specified prefix.
  42. func GenerateAPIKey(prefix string, length int) (string, error) {
  43. randomBytes := make([]byte, length)
  44. _, err := rand.Read(randomBytes)
  45. if err != nil {
  46. return "", err
  47. }
  48. // Use base64 to encode the random bytes to a string
  49. encoded := base64.URLEncoding.EncodeToString(randomBytes)
  50. // Trim the encoded string to the desired length and prepend the prefix
  51. apiKey := fmt.Sprintf("%s%s", prefix, encoded[:length])
  52. return apiKey, nil
  53. }