create_api_key_logic.go 1.9 KB

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