create_api_key_logic.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package api_key
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/base64"
  6. "fmt"
  7. "wechat-api/internal/svc"
  8. "wechat-api/internal/types"
  9. "wechat-api/internal/utils/dberrorhandler"
  10. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  11. "github.com/zeromicro/go-zero/core/errorx"
  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. l.svcCtx.Rds.HSet(l.ctx, "api_key", apiKey, req)
  40. return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
  41. }
  42. // GenerateAPIKey generates a random API key with a specified prefix.
  43. func GenerateAPIKey(prefix string, length int) (string, error) {
  44. randomBytes := make([]byte, length)
  45. _, err := rand.Read(randomBytes)
  46. if err != nil {
  47. return "", err
  48. }
  49. // Use base64 to encode the random bytes to a string
  50. encoded := base64.URLEncoding.EncodeToString(randomBytes)
  51. // Trim the encoded string to the desired length and prepend the prefix
  52. apiKey := fmt.Sprintf("%s%s", prefix, encoded[:length])
  53. return apiKey, nil
  54. }