neon.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. // NeonIntegrationRepository is a repository that manages neon integrations
  11. type NeonIntegrationRepository struct {
  12. db *gorm.DB
  13. key *[32]byte
  14. }
  15. // NewNeonIntegrationRepository returns a NeonIntegrationRepository
  16. func NewNeonIntegrationRepository(db *gorm.DB, key *[32]byte) repository.NeonIntegrationRepository {
  17. return &NeonIntegrationRepository{db, key}
  18. }
  19. // Insert creates a new neon integration
  20. func (repo *NeonIntegrationRepository) Insert(
  21. ctx context.Context, neonInt ints.NeonIntegration,
  22. ) (ints.NeonIntegration, error) {
  23. ctx, span := telemetry.NewSpan(ctx, "gorm-create-neon-integration")
  24. defer span.End()
  25. var created ints.NeonIntegration
  26. encrypted, err := repo.EncryptNeonIntegration(neonInt, 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 neon integration")
  32. }
  33. return created, nil
  34. }
  35. // EncryptNeonIntegration will encrypt the neon integration data before
  36. // writing to the DB
  37. func (repo *NeonIntegrationRepository) EncryptNeonIntegration(
  38. neonInt ints.NeonIntegration,
  39. key *[32]byte,
  40. ) (ints.NeonIntegration, error) {
  41. encrypted := neonInt
  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. return encrypted, nil
  64. }