upstash.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package gorm
  2. import (
  3. "context"
  4. "github.com/porter-dev/porter/internal/encryption"
  5. ints "github.com/porter-dev/porter/internal/models/integrations"
  6. "github.com/porter-dev/porter/internal/repository"
  7. "github.com/porter-dev/porter/internal/telemetry"
  8. "gorm.io/gorm"
  9. )
  10. // UpstashIntegrationRepository is a repository that manages upstash integrations
  11. type UpstashIntegrationRepository struct {
  12. db *gorm.DB
  13. key *[32]byte
  14. }
  15. // NewUpstashIntegrationRepository returns a UpstashIntegrationRepository
  16. func NewUpstashIntegrationRepository(db *gorm.DB, key *[32]byte) repository.UpstashIntegrationRepository {
  17. return &UpstashIntegrationRepository{db, key}
  18. }
  19. // Insert creates a new upstash integration
  20. func (repo *UpstashIntegrationRepository) Insert(
  21. ctx context.Context, upstashInt ints.UpstashIntegration,
  22. ) (ints.UpstashIntegration, error) {
  23. ctx, span := telemetry.NewSpan(ctx, "gorm-create-upstash-integration")
  24. defer span.End()
  25. var created ints.UpstashIntegration
  26. encrypted, err := repo.EncryptUpstashIntegration(upstashInt, repo.key)
  27. if err != nil {
  28. return created, telemetry.Error(ctx, span, err, "failed to encrypt")
  29. }
  30. if err := repo.db.Create(&encrypted).Error; err != nil {
  31. return created, telemetry.Error(ctx, span, err, "failed to create upstash integration")
  32. }
  33. return created, nil
  34. }
  35. // EncryptUpstashIntegration will encrypt the upstash integration data before
  36. // writing to the DB
  37. func (repo *UpstashIntegrationRepository) EncryptUpstashIntegration(
  38. upstashInt ints.UpstashIntegration,
  39. key *[32]byte,
  40. ) (ints.UpstashIntegration, error) {
  41. encrypted := upstashInt
  42. if len(encrypted.ClientID) > 0 {
  43. cipherData, err := encryption.Encrypt(encrypted.ClientID, key)
  44. if err != nil {
  45. return encrypted, err
  46. }
  47. encrypted.ClientID = cipherData
  48. }
  49. if len(encrypted.AccessToken) > 0 {
  50. cipherData, err := encryption.Encrypt(encrypted.AccessToken, key)
  51. if err != nil {
  52. return encrypted, err
  53. }
  54. encrypted.AccessToken = cipherData
  55. }
  56. if len(encrypted.RefreshToken) > 0 {
  57. cipherData, err := encryption.Encrypt(encrypted.RefreshToken, key)
  58. if err != nil {
  59. return encrypted, err
  60. }
  61. encrypted.RefreshToken = cipherData
  62. }
  63. if len(encrypted.DeveloperApiKey) > 0 {
  64. cipherData, err := encryption.Encrypt(encrypted.DeveloperApiKey, key)
  65. if err != nil {
  66. return encrypted, err
  67. }
  68. encrypted.DeveloperApiKey = cipherData
  69. }
  70. return encrypted, nil
  71. }