Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (storages): Add Google Drive

Rostislav Dugin1b2acbc118ad
diff --git a/README.md b/README.md
index a4199d08..0f0b30ec 100644
--- a/README.md
+++ b/README.md
@@ -147,3 +147,5 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
## 🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
+
+To see diagrams it is recommended to install "Markdown Preview Enhanced" plugin
\ No newline at end of file
diff --git a/backend/go.mod b/backend/go.mod
index 14adca6b..34948165 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -25,6 +25,17 @@ require (
gorm.io/gorm v1.26.1
)
+require (
+ cloud.google.com/go/auth v0.16.2 // indirect
+ cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
+ cloud.google.com/go/compute/metadata v0.7.0 // indirect
+ github.com/google/s2a-go v0.1.9 // indirect
+ github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect
+ github.com/googleapis/gax-go/v2 v2.14.2 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
+ google.golang.org/grpc v1.73.0 // indirect
+)
+
require (
dario.cat/mergo v1.0.2 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
@@ -117,11 +128,13 @@ require (
go.opentelemetry.io/otel/trace v1.36.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
golang.org/x/arch v0.17.0 // indirect
- golang.org/x/net v0.40.0 // indirect
+ golang.org/x/net v0.41.0 // indirect
+ golang.org/x/oauth2 v0.30.0
golang.org/x/sync v0.15.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
golang.org/x/tools v0.33.0 // indirect
+ google.golang.org/api v0.239.0
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 679d4e54..a6fb4c6f 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -1,3 +1,11 @@
+cloud.google.com/go/auth v0.16.2 h1:QvBAGFPLrDeoiNjyfVunhQ10HKNYuOwZ5noee0M5df4=
+cloud.google.com/go/auth v0.16.2/go.mod h1:sRBas2Y1fB1vZTdurouM0AzuYQBMZinrUYL8EufhtEA=
+cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
+cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
+cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=
+cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
+cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU=
+cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
@@ -107,8 +115,14 @@ github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
+github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4=
+github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA=
+github.com/googleapis/gax-go/v2 v2.14.2 h1:eBLnkZ9635krYIPD+ag1USrOAI0Nr0QYF3+/3GqO0k0=
+github.com/googleapis/gax-go/v2 v2.14.2/go.mod h1:ON64QhlJkhVtSqp4v1uaK92VyZ2gmvDQsweuyLV+8+w=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI=
github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4=
@@ -296,6 +310,10 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
+golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
+golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
+golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
+golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -344,12 +362,18 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/api v0.239.0 h1:2hZKUnFZEy81eugPs4e2XzIJ5SOwQg0G82bpXD65Puo=
+google.golang.org/api v0.239.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50=
google.golang.org/genproto/googleapis/api v0.0.0-20250528174236-200df99c418a h1:SGktgSolFCo75dnHJF2yMvnns6jCmHFJ0vE4Vn2JKvQ=
google.golang.org/genproto/googleapis/api v0.0.0-20250528174236-200df99c418a/go.mod h1:a77HrdMjoeKbnd2jmgcWdaS++ZLZAEq3orIOAEIKiVw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a h1:v2PbRU4K3llS09c7zodFpNePeamkAwG3mPrAery9VeE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 h1:fc6jSaCT0vBduLYZHYrBBNY4dsWuvgyff9noRNDdBeE=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
google.golang.org/grpc v1.72.2 h1:TdbGzwb82ty4OusHWepvFWGLgIbNo1/SUynEN0ssqv8=
google.golang.org/grpc v1.72.2/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM=
+google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok=
+google.golang.org/grpc v1.73.0/go.mod h1:50sbHOUqWoCQGI8V2HQLJM0B+LMlIUjNSZmow7EVBQc=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 53461de4..6d69971c 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -28,6 +28,10 @@ type EnvVariables struct {
DataFolder string
TempFolder string
+
+ TestGoogleDriveClientID string `env:"TEST_GOOGLE_DRIVE_CLIENT_ID" required:"true"`
+ TestGoogleDriveClientSecret string `env:"TEST_GOOGLE_DRIVE_CLIENT_SECRET" required:"true"`
+ TestGoogleDriveTokenJSON string `env:"TEST_GOOGLE_DRIVE_TOKEN_JSON" required:"true"`
}
var (
diff --git a/backend/internal/features/backups/background_service.go b/backend/internal/features/backups/background_service.go
index 79f6670d..3e1c8f04 100644
--- a/backend/internal/features/backups/background_service.go
+++ b/backend/internal/features/backups/background_service.go
@@ -127,7 +127,6 @@ func (s *BackupBackgroundService) cleanOldBackups() error {
err = storage.DeleteFile(backup.ID)
if err != nil {
s.logger.Error("Failed to delete backup file", "backupId", backup.ID, "error", err)
- continue
}
if err := s.backupRepository.DeleteByID(backup.ID); err != nil {
diff --git a/backend/internal/features/backups/usecases/postgresql/create_backup_uc.go b/backend/internal/features/backups/usecases/postgresql/create_backup_uc.go
index e823020e..470e6701 100644
--- a/backend/internal/features/backups/usecases/postgresql/create_backup_uc.go
+++ b/backend/internal/features/backups/usecases/postgresql/create_backup_uc.go
@@ -44,6 +44,11 @@ func (uc *CreatePostgresqlBackupUsecase) Execute(
)
pg := db.Postgresql
+
+ if pg == nil {
+ return fmt.Errorf("postgresql database configuration is required for pg_dump backups")
+ }
+
if pg.Database == nil || *pg.Database == "" {
return fmt.Errorf("database name is required for pg_dump backups")
}
diff --git a/backend/internal/features/storages/enums.go b/backend/internal/features/storages/enums.go
index 93787c94..869704e9 100644
--- a/backend/internal/features/storages/enums.go
+++ b/backend/internal/features/storages/enums.go
@@ -3,6 +3,7 @@ package storages
type StorageType string
const (
- StorageTypeLocal StorageType = "LOCAL"
- StorageTypeS3 StorageType = "S3"
+ StorageTypeLocal StorageType = "LOCAL"
+ StorageTypeS3 StorageType = "S3"
+ StorageTypeGoogleDrive StorageType = "GOOGLE_DRIVE"
)
diff --git a/backend/internal/features/storages/model.go b/backend/internal/features/storages/model.go
index 17c207ff..5cd3483c 100644
--- a/backend/internal/features/storages/model.go
+++ b/backend/internal/features/storages/model.go
@@ -4,6 +4,7 @@ import (
"errors"
"io"
"log/slog"
+ google_drive_storage "postgresus-backend/internal/features/storages/models/google_drive"
local_storage "postgresus-backend/internal/features/storages/models/local"
s3_storage "postgresus-backend/internal/features/storages/models/s3"
@@ -18,8 +19,9 @@ type Storage struct {
LastSaveError *string `json:"lastSaveError" gorm:"column:last_save_error;type:text"`
// specific storage
- LocalStorage *local_storage.LocalStorage `json:"localStorage" gorm:"foreignKey:StorageID"`
- S3Storage *s3_storage.S3Storage `json:"s3Storage" gorm:"foreignKey:StorageID"`
+ LocalStorage *local_storage.LocalStorage `json:"localStorage" gorm:"foreignKey:StorageID"`
+ S3Storage *s3_storage.S3Storage `json:"s3Storage" gorm:"foreignKey:StorageID"`
+ GoogleDriveStorage *google_drive_storage.GoogleDriveStorage `json:"googleDriveStorage" gorm:"foreignKey:StorageID"`
}
func (s *Storage) SaveFile(logger *slog.Logger, fileID uuid.UUID, file io.Reader) error {
@@ -65,6 +67,8 @@ func (s *Storage) getSpecificStorage() StorageFileSaver {
return s.LocalStorage
case StorageTypeS3:
return s.S3Storage
+ case StorageTypeGoogleDrive:
+ return s.GoogleDriveStorage
default:
panic("invalid storage type: " + string(s.Type))
}
diff --git a/backend/internal/features/storages/model_test.go b/backend/internal/features/storages/model_test.go
index 50b4afed..372eeb5e 100644
--- a/backend/internal/features/storages/model_test.go
+++ b/backend/internal/features/storages/model_test.go
@@ -7,6 +7,8 @@ import (
"io"
"os"
"path/filepath"
+ "postgresus-backend/internal/config"
+ google_drive_storage "postgresus-backend/internal/features/storages/models/google_drive"
local_storage "postgresus-backend/internal/features/storages/models/local"
s3_storage "postgresus-backend/internal/features/storages/models/s3"
"postgresus-backend/internal/util/logger"
@@ -34,6 +36,8 @@ type S3Container struct {
func Test_Storage_BasicOperations(t *testing.T) {
ctx := context.Background()
+ validateEnvVariables(t)
+
// Setup S3 container
s3Container, err := setupS3Container(ctx)
require.NoError(t, err, "Failed to setup S3 container")
@@ -68,6 +72,15 @@ func Test_Storage_BasicOperations(t *testing.T) {
S3Endpoint: "http://" + s3Container.endpoint, // Use http:// explicitly for testing
},
},
+ {
+ name: "GoogleDriveStorage",
+ storage: &google_drive_storage.GoogleDriveStorage{
+ StorageID: uuid.New(),
+ ClientID: config.GetEnv().TestGoogleDriveClientID,
+ ClientSecret: config.GetEnv().TestGoogleDriveClientSecret,
+ TokenJSON: config.GetEnv().TestGoogleDriveTokenJSON,
+ },
+ },
}
for _, tc := range testCases {
@@ -222,3 +235,10 @@ func setupS3Container(ctx context.Context) (*S3Container, error) {
region: region,
}, nil
}
+
+func validateEnvVariables(t *testing.T) {
+ env := config.GetEnv()
+ assert.NotEmpty(t, env.TestGoogleDriveClientID, "TEST_GOOGLE_DRIVE_CLIENT_ID is empty")
+ assert.NotEmpty(t, env.TestGoogleDriveClientSecret, "TEST_GOOGLE_DRIVE_CLIENT_SECRET is empty")
+ assert.NotEmpty(t, env.TestGoogleDriveTokenJSON, "TEST_GOOGLE_DRIVE_TOKEN_JSON is empty")
+}
diff --git a/backend/internal/features/storages/models/google_drive/model.go b/backend/internal/features/storages/models/google_drive/model.go
new file mode 100644
index 00000000..df9c1716
--- /dev/null
+++ b/backend/internal/features/storages/models/google_drive/model.go
@@ -0,0 +1,246 @@
+package google_drive_storage
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "strings"
+
+ "github.com/google/uuid"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/google"
+
+ drive "google.golang.org/api/drive/v3"
+ "google.golang.org/api/option"
+)
+
+type GoogleDriveStorage struct {
+ StorageID uuid.UUID `json:"storageId" gorm:"primaryKey;type:uuid;column:storage_id"`
+ ClientID string `json:"clientId" gorm:"not null;type:text;column:client_id"`
+ ClientSecret string `json:"clientSecret" gorm:"not null;type:text;column:client_secret"`
+ TokenJSON string `json:"tokenJson" gorm:"not null;type:text;column:token_json"`
+}
+
+func (s *GoogleDriveStorage) TableName() string {
+ return "google_drive_storages"
+}
+
+func (s *GoogleDriveStorage) SaveFile(
+ logger *slog.Logger,
+ fileID uuid.UUID,
+ file io.Reader,
+) error {
+ driveService, err := s.getDriveService()
+ if err != nil {
+ return err
+ }
+
+ ctx := context.Background()
+ filename := fileID.String()
+
+ // Delete any previous copy so we keep at most one object per logical file.
+ _ = s.deleteByName(ctx, driveService, filename) // ignore "not found"
+
+ fileMeta := &drive.File{Name: filename}
+
+ _, err = driveService.Files.Create(fileMeta).Media(file).Context(ctx).Do()
+ if err != nil {
+ return fmt.Errorf("failed to upload file to Google Drive: %w", err)
+ }
+
+ logger.Info("file uploaded to Google Drive", "name", filename)
+
+ return nil
+}
+
+func (s *GoogleDriveStorage) GetFile(fileID uuid.UUID) (io.ReadCloser, error) {
+ driveService, err := s.getDriveService()
+ if err != nil {
+ return nil, err
+ }
+
+ fileIDGoogle, err := s.lookupFileID(driveService, fileID.String())
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := driveService.Files.Get(fileIDGoogle).Download()
+ if err != nil {
+ return nil, fmt.Errorf("failed to download file from Google Drive: %w", err)
+ }
+
+ return resp.Body, nil
+}
+
+func (s *GoogleDriveStorage) DeleteFile(fileID uuid.UUID) error {
+ driveService, err := s.getDriveService()
+ if err != nil {
+ return err
+ }
+
+ ctx := context.Background()
+ return s.deleteByName(ctx, driveService, fileID.String())
+}
+
+func (s *GoogleDriveStorage) Validate() error {
+ switch {
+ case s.ClientID == "":
+ return errors.New("client ID is required")
+ case s.ClientSecret == "":
+ return errors.New("client secret is required")
+ case s.TokenJSON == "":
+ return errors.New("token JSON is required")
+ }
+
+ return nil
+}
+
+func (s *GoogleDriveStorage) TestConnection() error {
+ driveService, err := s.getDriveService()
+ if err != nil {
+ return err
+ }
+
+ ctx := context.Background()
+ testFilename := "test-connection-" + uuid.New().String()
+ testData := []byte("test")
+
+ // Test write operation
+ fileMeta := &drive.File{Name: testFilename}
+ file, err := driveService.Files.Create(fileMeta).
+ Media(strings.NewReader(string(testData))).
+ Context(ctx).
+ Do()
+ if err != nil {
+ return fmt.Errorf("failed to write test file to Google Drive: %w", err)
+ }
+
+ // Test read operation
+ resp, err := driveService.Files.Get(file.Id).Download()
+ if err != nil {
+ // Clean up test file before returning error
+ _ = driveService.Files.Delete(file.Id).Context(ctx).Do()
+ return fmt.Errorf("failed to read test file from Google Drive: %w", err)
+ }
+ defer func() {
+ if err := resp.Body.Close(); err != nil {
+ fmt.Printf("failed to close response body: %v\n", err)
+ }
+ }()
+
+ readData, err := io.ReadAll(resp.Body)
+ if err != nil {
+ // Clean up test file before returning error
+ _ = driveService.Files.Delete(file.Id).Context(ctx).Do()
+ return fmt.Errorf("failed to read test file data: %w", err)
+ }
+
+ // Clean up test file
+ if err := driveService.Files.Delete(file.Id).Context(ctx).Do(); err != nil {
+ return fmt.Errorf("failed to clean up test file: %w", err)
+ }
+
+ // Verify data matches
+ if string(readData) != string(testData) {
+ return fmt.Errorf(
+ "test file data mismatch: expected %q, got %q",
+ string(testData),
+ string(readData),
+ )
+ }
+
+ return nil
+}
+
+func (s *GoogleDriveStorage) getDriveService() (*drive.Service, error) {
+ if err := s.Validate(); err != nil {
+ return nil, err
+ }
+
+ var token oauth2.Token
+ if err := json.Unmarshal([]byte(s.TokenJSON), &token); err != nil {
+ return nil, fmt.Errorf("invalid token JSON: %w", err)
+ }
+
+ ctx := context.Background()
+
+ cfg := &oauth2.Config{
+ ClientID: s.ClientID,
+ ClientSecret: s.ClientSecret,
+ Endpoint: google.Endpoint,
+ Scopes: []string{"https://www.googleapis.com/auth/drive.file"},
+ }
+
+ tokenSource := cfg.TokenSource(ctx, &token)
+
+ // Try to get a fresh token
+ _, err := tokenSource.Token()
+ if err != nil {
+ return nil, fmt.Errorf("failed to get fresh token: %w", err)
+ }
+
+ driveService, err := drive.NewService(ctx, option.WithTokenSource(tokenSource))
+ if err != nil {
+ return nil, fmt.Errorf("unable to create Drive client: %w", err)
+ }
+
+ return driveService, nil
+}
+
+func (s *GoogleDriveStorage) lookupFileID(
+ driveService *drive.Service,
+ name string,
+) (string, error) {
+ query := fmt.Sprintf("name = '%s' and trashed = false", escapeForQuery(name))
+
+ results, err := driveService.Files.List().
+ Q(query).
+ Fields("files(id)").
+ PageSize(1).
+ Do()
+ if err != nil {
+ return "", fmt.Errorf("file lookup failed: %w", err)
+ }
+
+ if len(results.Files) == 0 {
+ return "", fmt.Errorf("file %q not found in Google Drive", name)
+ }
+
+ return results.Files[0].Id, nil
+}
+
+func (s *GoogleDriveStorage) deleteByName(
+ ctx context.Context,
+ driveService *drive.Service,
+ name string,
+) error {
+ query := fmt.Sprintf("name = '%s' and trashed = false", escapeForQuery(name))
+
+ err := driveService.
+ Files.
+ List().
+ Q(query).
+ Fields("files(id)").
+ Pages(ctx, func(p *drive.FileList) error {
+ for _, file := range p.Files {
+ if err := driveService.Files.Delete(file.Id).Context(ctx).Do(); err != nil {
+ return err
+ }
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return fmt.Errorf("failed to delete %q: %w", name, err)
+ }
+
+ return nil
+}
+
+func escapeForQuery(s string) string {
+ return strings.ReplaceAll(s, `'`, `\'`)
+}
diff --git a/backend/internal/features/storages/models/s3/model.go b/backend/internal/features/storages/models/s3/model.go
index 0c92a636..f94e4beb 100644
--- a/backend/internal/features/storages/models/s3/model.go
+++ b/backend/internal/features/storages/models/s3/model.go
@@ -44,7 +44,7 @@ func (s *S3Storage) SaveFile(logger *slog.Logger, fileID uuid.UUID, file io.Read
_, err = client.PutObject(
context.TODO(),
s.S3Bucket,
- fileID.String()+".zip",
+ fileID.String(),
bytes.NewReader(data),
int64(len(data)),
minio.PutObjectOptions{},
@@ -65,7 +65,7 @@ func (s *S3Storage) GetFile(fileID uuid.UUID) (io.ReadCloser, error) {
object, err := client.GetObject(
context.TODO(),
s.S3Bucket,
- fileID.String()+".zip",
+ fileID.String(),
minio.GetObjectOptions{},
)
if err != nil {
@@ -100,7 +100,7 @@ func (s *S3Storage) DeleteFile(fileID uuid.UUID) error {
err = client.RemoveObject(
context.TODO(),
s.S3Bucket,
- fileID.String()+".zip",
+ fileID.String(),
minio.RemoveObjectOptions{},
)
if err != nil {
diff --git a/backend/internal/features/storages/repository.go b/backend/internal/features/storages/repository.go
index 218cbfe7..bc3e122d 100644
--- a/backend/internal/features/storages/repository.go
+++ b/backend/internal/features/storages/repository.go
@@ -22,17 +22,21 @@ func (r *StorageRepository) Save(storage *Storage) (*Storage, error) {
if storage.S3Storage != nil {
storage.S3Storage.StorageID = storage.ID
}
+ case StorageTypeGoogleDrive:
+ if storage.GoogleDriveStorage != nil {
+ storage.GoogleDriveStorage.StorageID = storage.ID
+ }
}
if storage.ID == uuid.Nil {
if err := tx.Create(storage).
- Omit("LocalStorage", "S3Storage").
+ Omit("LocalStorage", "S3Storage", "GoogleDriveStorage").
Error; err != nil {
return err
}
} else {
if err := tx.Save(storage).
- Omit("LocalStorage", "S3Storage").
+ Omit("LocalStorage", "S3Storage", "GoogleDriveStorage").
Error; err != nil {
return err
}
@@ -53,6 +57,13 @@ func (r *StorageRepository) Save(storage *Storage) (*Storage, error) {
return err
}
}
+ case StorageTypeGoogleDrive:
+ if storage.GoogleDriveStorage != nil {
+ storage.GoogleDriveStorage.StorageID = storage.ID // Ensure ID is set
+ if err := tx.Save(storage.GoogleDriveStorage).Error; err != nil {
+ return err
+ }
+ }
}
return nil
@@ -72,6 +83,7 @@ func (r *StorageRepository) FindByID(id uuid.UUID) (*Storage, error) {
GetDb().
Preload("LocalStorage").
Preload("S3Storage").
+ Preload("GoogleDriveStorage").
Where("id = ?", id).
First(&s).Error; err != nil {
return nil, err
@@ -87,6 +99,7 @@ func (r *StorageRepository) FindByUserID(userID uuid.UUID) ([]*Storage, error) {
GetDb().
Preload("LocalStorage").
Preload("S3Storage").
+ Preload("GoogleDriveStorage").
Where("user_id = ?", userID).
Order("name ASC").
Find(&storages).Error; err != nil {
@@ -112,6 +125,12 @@ func (r *StorageRepository) Delete(s *Storage) error {
return err
}
}
+ case StorageTypeGoogleDrive:
+ if s.GoogleDriveStorage != nil {
+ if err := tx.Delete(s.GoogleDriveStorage).Error; err != nil {
+ return err
+ }
+ }
}
// Delete the main storage
diff --git a/backend/migrations/20250629143714_add_google_drive_storage.sql b/backend/migrations/20250629143714_add_google_drive_storage.sql
new file mode 100644
index 00000000..b82a965b
--- /dev/null
+++ b/backend/migrations/20250629143714_add_google_drive_storage.sql
@@ -0,0 +1,25 @@
+-- +goose Up
+-- +goose StatementBegin
+
+-- Create google drive storages table
+CREATE TABLE google_drive_storages (
+ storage_id UUID PRIMARY KEY,
+ client_id TEXT NOT NULL,
+ client_secret TEXT NOT NULL,
+ token_json TEXT NOT NULL
+);
+
+ALTER TABLE google_drive_storages
+ ADD CONSTRAINT fk_google_drive_storages_storage
+ FOREIGN KEY (storage_id)
+ REFERENCES storages (id)
+ ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED;
+
+-- +goose StatementEnd
+
+-- +goose Down
+-- +goose StatementBegin
+
+DROP TABLE IF EXISTS google_drive_storages;
+
+-- +goose StatementEnd
diff --git a/backend/tools/download_windows.bat b/backend/tools/download_windows.bat
index 61f522fb..49bee42a 100644
--- a/backend/tools/download_windows.bat
+++ b/backend/tools/download_windows.bat
@@ -90,12 +90,4 @@ echo Installation process completed!
echo PostgreSQL versions are installed in: %POSTGRES_DIR%
echo.
-:: List installed versions
-echo Installed PostgreSQL versions:
-if exist "postgresql" (
- dir /b "postgresql\postgresql-*" 2>nul
-) else (
- echo No PostgreSQL installations found
-)
-
pause
diff --git a/docs/how-extrnal-oauth-works.md b/docs/how-extrnal-oauth-works.md
new file mode 100644
index 00000000..5ec03ec6
--- /dev/null
+++ b/docs/how-extrnal-oauth-works.md
@@ -0,0 +1,26 @@
+Cloud storages usually require OAuth (Google Drive, Dropbox, OneDrive)
+
+OAuth services usually need HTTPS domain for authorization. Self hosted Postgresus can be hosted via HTTP or even without static IP so this way does not work. To make OAuth works even on localhost, we proxy requests via postgresus.com domain
+
+As permanent URL for authorization we use main Postgresus domain. It forward responses to the self hosted domain so it can get access to the cloud
+
+This is the sequence of requests (example for Google Drive):
+
+```mermaid
+sequenceDiagram
+ participant SelfHosted as http://localhost:4005<br/>Self-hosted Postgresus
+ participant Proxy as https://postgresus.com<br/>Proxy website
+ participant Google as Google OAuth
+
+ SelfHosted->>Google: Send auth request with DTO
+
+ Google->>Proxy: Redirect with auth code<br/>to postgresus.com/oauth
+
+ Proxy->>SelfHosted: Redirect to self-hosted instance<br/>with DTO + auth code
+
+ SelfHosted->>Google: Exchange auth code for tokens<br/>POST /oauth2/token
+ Google->>SelfHosted: Return access & refresh tokens
+
+ SelfHosted->>SelfHosted: Store Google Drive config for files exchange
+```
+
diff --git a/frontend/public/icons/storages/google-drive.svg b/frontend/public/icons/storages/google-drive.svg
new file mode 100644
index 00000000..94921e11
--- /dev/null
+++ b/frontend/public/icons/storages/google-drive.svg
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
+<svg width="800px" height="800px" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M2 11.9556C2 8.47078 2 6.7284 2.67818 5.39739C3.27473 4.22661 4.22661 3.27473 5.39739 2.67818C6.7284 2 8.47078 2 11.9556 2H20.0444C23.5292 2 25.2716 2 26.6026 2.67818C27.7734 3.27473 28.7253 4.22661 29.3218 5.39739C30 6.7284 30 8.47078 30 11.9556V20.0444C30 23.5292 30 25.2716 29.3218 26.6026C28.7253 27.7734 27.7734 28.7253 26.6026 29.3218C25.2716 30 23.5292 30 20.0444 30H11.9556C8.47078 30 6.7284 30 5.39739 29.3218C4.22661 28.7253 3.27473 27.7734 2.67818 26.6026C2 25.2716 2 23.5292 2 20.0444V11.9556Z" fill="white"/>
+<path d="M16.0019 12.4507L12.541 6.34297C12.6559 6.22598 12.7881 6.14924 12.9203 6.09766C11.8998 6.43355 11.4315 7.57961 11.4315 7.57961L5.10895 18.7345C5.01999 19.0843 4.99528 19.4 5.0064 19.6781H11.9072L16.0019 12.4507Z" fill="#34A853"/>
+<path d="M16.002 12.4507L20.0967 19.6781H26.9975C27.0086 19.4 26.9839 19.0843 26.8949 18.7345L20.5724 7.57961C20.5724 7.57961 20.1029 6.43355 19.0835 6.09766C19.2145 6.14924 19.3479 6.22598 19.4628 6.34297L16.002 12.4507Z" fill="#FBBC05"/>
+<path d="M16.0019 12.4514L19.4628 6.34371C19.3479 6.22671 19.2144 6.14997 19.0835 6.09839C18.9327 6.04933 18.7709 6.01662 18.5954 6.00781H18.4125H13.5913H13.4084C13.2342 6.01536 13.0711 6.04807 12.9203 6.09839C12.7894 6.14997 12.6559 6.22671 12.541 6.34371L16.0019 12.4514Z" fill="#188038"/>
+<path d="M11.9082 19.6782L8.48687 25.7168C8.48687 25.7168 8.3732 25.6614 8.21875 25.5469C8.70434 25.9206 9.17633 25.9998 9.17633 25.9998H22.6134C23.3547 25.9998 23.5092 25.7168 23.5092 25.7168C23.5116 25.7155 23.5129 25.7142 23.5153 25.713L20.0965 19.6782H11.9082Z" fill="#4285F4"/>
+<path d="M11.9086 19.6782H5.00781C5.04241 20.4985 5.39826 20.9778 5.39826 20.9778L5.65773 21.4281C5.67627 21.4546 5.68739 21.4697 5.68739 21.4697L6.25205 22.461L7.51976 24.6676C7.55683 24.7569 7.60008 24.8386 7.6458 24.9166C7.66309 24.9431 7.67915 24.972 7.69769 24.9972C7.70263 25.0047 7.70757 25.0123 7.71252 25.0198C7.86944 25.2412 8.04489 25.4123 8.22034 25.5469C8.37479 25.6627 8.48847 25.7168 8.48847 25.7168L11.9086 19.6782Z" fill="#1967D2"/>
+<path d="M20.0967 19.6782H26.9974C26.9628 20.4985 26.607 20.9778 26.607 20.9778L26.3475 21.4281C26.329 21.4546 26.3179 21.4697 26.3179 21.4697L25.7532 22.461L24.4855 24.6676C24.4484 24.7569 24.4052 24.8386 24.3595 24.9166C24.3422 24.9431 24.3261 24.972 24.3076 24.9972C24.3026 25.0047 24.2977 25.0123 24.2927 25.0198C24.1358 25.2412 23.9604 25.4123 23.7849 25.5469C23.6305 25.6627 23.5168 25.7168 23.5168 25.7168L20.0967 19.6782Z" fill="#EA4335"/>
+</svg>
\ No newline at end of file
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 1fb2cc81..9c82c9b0 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -3,6 +3,7 @@ import { BrowserRouter, Route } from 'react-router';
import { Routes } from 'react-router';
import { userApi } from './entity/users';
+import { OauthStorageComponent } from './features/storages/OauthStorageComponent';
import { AuthPageComponent } from './pages/AuthPageComponent';
import { MainScreenComponent } from './widgets/main/MainScreenComponent';
@@ -22,6 +23,10 @@ function App() {
<BrowserRouter>
<Routes>
<Route path="/" element={!isAuthorized ? <AuthPageComponent /> : <MainScreenComponent />} />
+ <Route
+ path="/storages/google-oauth"
+ element={!isAuthorized ? <AuthPageComponent /> : <OauthStorageComponent />}
+ />
</Routes>
</BrowserRouter>
);
diff --git a/frontend/src/constants.ts b/frontend/src/constants.ts
index 7abd24c7..7c5b9110 100644
--- a/frontend/src/constants.ts
+++ b/frontend/src/constants.ts
@@ -10,3 +10,5 @@ export function getApplicationServer() {
return `${url.protocol}//${url.hostname}:${url.port || (url.protocol === 'https:' ? '443' : '80')}`;
}
}
+
+export const GOOGLE_DRIVE_OAUTH_REDIRECT_URL = 'https://postgresus.com/storages/google-oauth';
\ No newline at end of file
diff --git a/frontend/src/entity/storages/index.ts b/frontend/src/entity/storages/index.ts
index 15d7f0ea..d0fe113e 100644
--- a/frontend/src/entity/storages/index.ts
+++ b/frontend/src/entity/storages/index.ts
@@ -5,3 +5,4 @@ export { type LocalStorage } from './models/LocalStorage';
export { type S3Storage } from './models/S3Storage';
export { getStorageLogoFromType } from './models/getStorageLogoFromType';
export { getStorageNameFromType } from './models/getStorageNameFromType';
+export { type GoogleDriveStorage } from './models/GoogleDriveStorage';
diff --git a/frontend/src/entity/storages/models/GoogleDriveStorage.ts b/frontend/src/entity/storages/models/GoogleDriveStorage.ts
new file mode 100644
index 00000000..992aa7d5
--- /dev/null
+++ b/frontend/src/entity/storages/models/GoogleDriveStorage.ts
@@ -0,0 +1,5 @@
+export interface GoogleDriveStorage {
+ clientId: string;
+ clientSecret: string;
+ tokenJson?: string;
+}
diff --git a/frontend/src/entity/storages/models/Storage.ts b/frontend/src/entity/storages/models/Storage.ts
index 69781254..b8e928ae 100644
--- a/frontend/src/entity/storages/models/Storage.ts
+++ b/frontend/src/entity/storages/models/Storage.ts
@@ -1,3 +1,4 @@
+import type { GoogleDriveStorage } from './GoogleDriveStorage';
import type { LocalStorage } from './LocalStorage';
import type { S3Storage } from './S3Storage';
import type { StorageType } from './StorageType';
@@ -11,4 +12,5 @@ export interface Storage {
// specific storage types
localStorage?: LocalStorage;
s3Storage?: S3Storage;
+ googleDriveStorage?: GoogleDriveStorage;
}
diff --git a/frontend/src/entity/storages/models/StorageOauthDto.ts b/frontend/src/entity/storages/models/StorageOauthDto.ts
new file mode 100644
index 00000000..c5c120e3
--- /dev/null
+++ b/frontend/src/entity/storages/models/StorageOauthDto.ts
@@ -0,0 +1,7 @@
+import type { Storage } from './Storage';
+
+export interface StorageOauthDto {
+ redirectUrl: string;
+ storage: Storage;
+ authCode: string;
+}
diff --git a/frontend/src/entity/storages/models/StorageType.ts b/frontend/src/entity/storages/models/StorageType.ts
index 875a533f..86f2eaa4 100644
--- a/frontend/src/entity/storages/models/StorageType.ts
+++ b/frontend/src/entity/storages/models/StorageType.ts
@@ -1,4 +1,5 @@
export enum StorageType {
LOCAL = 'LOCAL',
S3 = 'S3',
+ GOOGLE_DRIVE = 'GOOGLE_DRIVE',
}
diff --git a/frontend/src/entity/storages/models/getStorageLogoFromType.ts b/frontend/src/entity/storages/models/getStorageLogoFromType.ts
index bc11a46e..65a7d189 100644
--- a/frontend/src/entity/storages/models/getStorageLogoFromType.ts
+++ b/frontend/src/entity/storages/models/getStorageLogoFromType.ts
@@ -6,6 +6,8 @@ export const getStorageLogoFromType = (type: StorageType) => {
return '/icons/storages/local.svg';
case StorageType.S3:
return '/icons/storages/s3.svg';
+ case StorageType.GOOGLE_DRIVE:
+ return '/icons/storages/google-drive.svg';
default:
return '';
}
diff --git a/frontend/src/entity/storages/models/getStorageNameFromType.ts b/frontend/src/entity/storages/models/getStorageNameFromType.ts
index 2eb42d3f..32e9998a 100644
--- a/frontend/src/entity/storages/models/getStorageNameFromType.ts
+++ b/frontend/src/entity/storages/models/getStorageNameFromType.ts
@@ -6,6 +6,8 @@ export const getStorageNameFromType = (type: StorageType) => {
return 'local storage';
case StorageType.S3:
return 'S3';
+ case StorageType.GOOGLE_DRIVE:
+ return 'Google Drive';
default:
return '';
}
diff --git a/frontend/src/features/databases/ui/DatabasesComponent.tsx b/frontend/src/features/databases/ui/DatabasesComponent.tsx
index f8b20214..28319d98 100644
--- a/frontend/src/features/databases/ui/DatabasesComponent.tsx
+++ b/frontend/src/features/databases/ui/DatabasesComponent.tsx
@@ -52,6 +52,12 @@ export const DatabasesComponent = ({ contentHeight }: Props) => {
);
}
+ const addDatabaseButton = (
+ <Button type="primary" className="mb-2 w-full" onClick={() => setIsShowAddDatabase(true)}>
+ Add database
+ </Button>
+ );
+
return (
<>
<div className="flex grow">
@@ -59,6 +65,8 @@ export const DatabasesComponent = ({ contentHeight }: Props) => {
className="mx-3 w-[250px] min-w-[250px] overflow-y-auto"
style={{ height: contentHeight }}
>
+ {databases.length >= 5 && addDatabaseButton}
+
{databases.map((database) => (
<DatabaseCardComponent
key={database.id}
@@ -68,11 +76,9 @@ export const DatabasesComponent = ({ contentHeight }: Props) => {
/>
))}
- <Button type="primary" className="w-full" onClick={() => setIsShowAddDatabase(true)}>
- Add database
- </Button>
+ {databases.length < 5 && addDatabaseButton}
- <div className="mx-3 mt-2 text-center text-xs text-gray-500">
+ <div className="mx-3 text-center text-xs text-gray-500">
Database - is a thing we are backing up
</div>
</div>
diff --git a/frontend/src/features/notifiers/ui/NotifiersComponent.tsx b/frontend/src/features/notifiers/ui/NotifiersComponent.tsx
index 256acba0..75e715a5 100644
--- a/frontend/src/features/notifiers/ui/NotifiersComponent.tsx
+++ b/frontend/src/features/notifiers/ui/NotifiersComponent.tsx
@@ -43,10 +43,21 @@ export const NotifiersComponent = ({ contentHeight }: Props) => {
);
}
+ const addNotifierButton = (
+ <Button type="primary" className="mb-2 w-full" onClick={() => setIsShowAddNotifier(true)}>
+ Add notifier
+ </Button>
+ );
+
return (
<>
<div className="flex grow">
- <div className="mx-3 w-[250px] overflow-y-auto" style={{ height: contentHeight }}>
+ <div
+ className="mx-3 w-[250px] min-w-[250px] overflow-y-auto"
+ style={{ height: contentHeight }}
+ >
+ {notifiers.length >= 5 && addNotifierButton}
+
{notifiers.map((notifier) => (
<NotifierCardComponent
key={notifier.id}
@@ -56,11 +67,9 @@ export const NotifiersComponent = ({ contentHeight }: Props) => {
/>
))}
- <Button type="primary" className="w-full" onClick={() => setIsShowAddNotifier(true)}>
- Add notifier
- </Button>
+ {notifiers.length < 5 && addNotifierButton}
- <div className="mx-3 mt-2 text-center text-xs text-gray-500">
+ <div className="mx-3 text-center text-xs text-gray-500">
Notifier - is a place where notifications will be sent (email, Slack, Telegram, etc.)
</div>
</div>
diff --git a/frontend/src/features/storages/OauthStorageComponent.tsx b/frontend/src/features/storages/OauthStorageComponent.tsx
new file mode 100644
index 00000000..6dac7695
--- /dev/null
+++ b/frontend/src/features/storages/OauthStorageComponent.tsx
@@ -0,0 +1,104 @@
+import { Modal, Spin } from 'antd';
+import { useEffect, useState } from 'react';
+
+import { GOOGLE_DRIVE_OAUTH_REDIRECT_URL } from '../../constants';
+import { type Storage, StorageType } from '../../entity/storages';
+import type { StorageOauthDto } from '../../entity/storages/models/StorageOauthDto';
+import { EditStorageComponent } from './ui/edit/EditStorageComponent';
+
+export function OauthStorageComponent() {
+ const [storage, setStorage] = useState<Storage | undefined>();
+
+ const exchangeGoogleOauthCode = async (oauthDto: StorageOauthDto) => {
+ if (!oauthDto.storage.googleDriveStorage) {
+ alert('Google Drive storage configuration not found');
+ return;
+ }
+
+ const { clientId, clientSecret } = oauthDto.storage.googleDriveStorage;
+ const { authCode } = oauthDto;
+
+ try {
+ // Exchange authorization code for access token
+ const response = await fetch('https://oauth2.googleapis.com/token', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ body: new URLSearchParams({
+ code: authCode,
+ client_id: clientId,
+ client_secret: clientSecret,
+ redirect_uri: GOOGLE_DRIVE_OAUTH_REDIRECT_URL,
+ grant_type: 'authorization_code',
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`OAuth exchange failed: ${response.statusText}`);
+ }
+
+ const tokenData = await response.json();
+
+ oauthDto.storage.googleDriveStorage.tokenJson = JSON.stringify(tokenData);
+ setStorage(oauthDto.storage);
+ } catch (error) {
+ alert(`Failed to exchange OAuth code: ${error}`);
+ }
+ };
+
+ useEffect(() => {
+ const oauthDtoParam = new URLSearchParams(window.location.search).get('oauthDto');
+ if (!oauthDtoParam) {
+ alert('OAuth param not found');
+ return;
+ }
+
+ const decodedParam = decodeURIComponent(oauthDtoParam);
+ const oauthDto: StorageOauthDto = JSON.parse(decodedParam);
+
+ if (oauthDto.storage.type === StorageType.GOOGLE_DRIVE) {
+ if (!oauthDto.storage.googleDriveStorage) {
+ alert('Google Drive storage not found');
+ return;
+ }
+
+ exchangeGoogleOauthCode(oauthDto);
+ }
+ }, []);
+
+ if (!storage) {
+ return (
+ <div className="mt-20 flex justify-center">
+ <Spin />
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ <Modal
+ title="Add storage"
+ footer={<div />}
+ open
+ onCancel={() => {
+ window.location.href = '/';
+ }}
+ >
+ <div className="my-3 max-w-[250px] text-gray-500">
+ Storage - is a place where backups will be stored (local disk, S3, etc.)
+ </div>
+
+ <EditStorageComponent
+ isShowClose={false}
+ onClose={() => {}}
+ isShowName={false}
+ editingStorage={storage}
+ onChanged={() => {
+ window.location.href = '/';
+ }}
+ />
+ </Modal>
+ </div>
+ );
+}
diff --git a/frontend/src/features/storages/StoragesComponent.tsx b/frontend/src/features/storages/StoragesComponent.tsx
index 79ab8088..1f0c142a 100644
--- a/frontend/src/features/storages/StoragesComponent.tsx
+++ b/frontend/src/features/storages/StoragesComponent.tsx
@@ -45,10 +45,21 @@ export const StoragesComponent = ({ contentHeight }: Props) => {
);
}
+ const addStorageButton = (
+ <Button type="primary" className="mb-2 w-full" onClick={() => setIsShowAddStorage(true)}>
+ Add storage
+ </Button>
+ );
+
return (
<>
<div className="flex grow">
- <div className="mx-3 w-[250px] overflow-y-auto" style={{ height: contentHeight }}>
+ <div
+ className="mx-3 w-[250px] min-w-[250px] overflow-y-auto"
+ style={{ height: contentHeight }}
+ >
+ {storages.length >= 5 && addStorageButton}
+
{storages.map((storage) => (
<StorageCardComponent
key={storage.id}
@@ -58,11 +69,9 @@ export const StoragesComponent = ({ contentHeight }: Props) => {
/>
))}
- <Button type="primary" className="w-full" onClick={() => setIsShowAddStorage(true)}>
- Add storage
- </Button>
+ {storages.length < 5 && addStorageButton}
- <div className="mx-3 mt-2 text-center text-xs text-gray-500">
+ <div className="mx-3 text-center text-xs text-gray-500">
Storage - is a place where backups will be stored (local disk, S3, etc.)
</div>
</div>
diff --git a/frontend/src/features/storages/ui/edit/EditStorageComponent.tsx b/frontend/src/features/storages/ui/edit/EditStorageComponent.tsx
index 0ae14940..15a8cb70 100644
--- a/frontend/src/features/storages/ui/edit/EditStorageComponent.tsx
+++ b/frontend/src/features/storages/ui/edit/EditStorageComponent.tsx
@@ -1,8 +1,14 @@
import { Button, Input, Select } from 'antd';
import { useEffect, useState } from 'react';
-import { type Storage, StorageType, storageApi } from '../../../../entity/storages';
+import {
+ type Storage,
+ StorageType,
+ getStorageLogoFromType,
+ storageApi,
+} from '../../../../entity/storages';
import { ToastHelper } from '../../../../shared/toast';
+import { EditGoogleDriveStorageComponent } from './storages/EditGoogleDriveStorageComponent';
import { EditS3StorageComponent } from './storages/EditS3StorageComponent';
interface Props {
@@ -69,6 +75,7 @@ export function EditStorageComponent({
storage.localStorage = undefined;
storage.s3Storage = undefined;
+ storage.googleDriveStorage = undefined;
if (type === StorageType.LOCAL) {
storage.localStorage = {};
@@ -84,6 +91,13 @@ export function EditStorageComponent({
};
}
+ if (type === StorageType.GOOGLE_DRIVE) {
+ storage.googleDriveStorage = {
+ clientId: '',
+ clientSecret: '',
+ };
+ }
+
setStorage(
JSON.parse(
JSON.stringify({
@@ -95,7 +109,8 @@ export function EditStorageComponent({
};
useEffect(() => {
- setIsUnsaved(false);
+ setIsUnsaved(true);
+
setStorage(
editingStorage
? JSON.parse(JSON.stringify(editingStorage))
@@ -125,6 +140,14 @@ export function EditStorageComponent({
);
}
+ if (storage.type === StorageType.GOOGLE_DRIVE) {
+ return (
+ storage.googleDriveStorage?.clientId &&
+ storage.googleDriveStorage?.clientSecret &&
+ storage.googleDriveStorage?.tokenJson
+ );
+ }
+
return false;
};
@@ -157,6 +180,7 @@ export function EditStorageComponent({
options={[
{ label: 'Local storage', value: StorageType.LOCAL },
{ label: 'S3', value: StorageType.S3 },
+ { label: 'Google Drive', value: StorageType.GOOGLE_DRIVE },
]}
onChange={(value) => {
setStorageType(value);
@@ -165,6 +189,8 @@ export function EditStorageComponent({
size="small"
className="w-full max-w-[250px]"
/>
+
+ <img src={getStorageLogoFromType(storage?.type)} className="ml-2 h-4 w-4" />
</div>
<div className="mt-5" />
@@ -177,6 +203,14 @@ export function EditStorageComponent({
setIsUnsaved={setIsUnsaved}
/>
)}
+
+ {storage?.type === StorageType.GOOGLE_DRIVE && (
+ <EditGoogleDriveStorageComponent
+ storage={storage}
+ setStorage={setStorage}
+ setIsUnsaved={setIsUnsaved}
+ />
+ )}
</div>
<div className="mt-3 flex">
diff --git a/frontend/src/features/storages/ui/edit/storages/EditGoogleDriveStorageComponent.tsx b/frontend/src/features/storages/ui/edit/storages/EditGoogleDriveStorageComponent.tsx
new file mode 100644
index 00000000..c0431f06
--- /dev/null
+++ b/frontend/src/features/storages/ui/edit/storages/EditGoogleDriveStorageComponent.tsx
@@ -0,0 +1,123 @@
+import { Button, Input } from 'antd';
+
+import { GOOGLE_DRIVE_OAUTH_REDIRECT_URL } from '../../../../../constants';
+import type { Storage } from '../../../../../entity/storages';
+import type { StorageOauthDto } from '../../../../../entity/storages/models/StorageOauthDto';
+
+interface Props {
+ storage: Storage;
+ setStorage: (storage: Storage) => void;
+ setIsUnsaved: (isUnsaved: boolean) => void;
+}
+
+export function EditGoogleDriveStorageComponent({ storage, setStorage, setIsUnsaved }: Props) {
+ const goToAuthUrl = () => {
+ if (!storage?.googleDriveStorage?.clientId || !storage?.googleDriveStorage?.clientSecret) {
+ return;
+ }
+
+ const redirectUri = GOOGLE_DRIVE_OAUTH_REDIRECT_URL;
+ const clientId = storage.googleDriveStorage.clientId;
+ const scope = 'https://www.googleapis.com/auth/drive.file';
+ const originUrl = `${window.location.origin}/storages/google-oauth`;
+
+ const oauthDto: StorageOauthDto = {
+ redirectUrl: originUrl,
+ storage: storage,
+ authCode: '',
+ };
+
+ const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${
+ clientId
+ }&redirect_uri=${redirectUri}&response_type=code&scope=${encodeURIComponent(scope)}&access_type=offline&prompt=consent&state=${encodeURIComponent(JSON.stringify(oauthDto))}`;
+
+ window.open(authUrl);
+ };
+
+ return (
+ <>
+ <div className="mb-2 flex items-center">
+ <div className="min-w-[110px]" />
+
+ <div className="text-xs text-blue-600">
+ <a href="https://postgresus.com/google-drive-storage" target="_blank" rel="noreferrer">
+ How to connect Google Drive?
+ </a>
+ </div>
+ </div>
+
+ <div className="mb-1 flex items-center">
+ <div className="min-w-[110px]">Client ID</div>
+ <Input
+ value={storage?.googleDriveStorage?.clientId || ''}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
+ if (!storage?.googleDriveStorage) return;
+
+ setStorage({
+ ...storage,
+ googleDriveStorage: {
+ ...storage.googleDriveStorage,
+ clientId: e.target.value.trim(),
+ },
+ });
+ setIsUnsaved(true);
+ }}
+ size="small"
+ className="w-full max-w-[250px]"
+ placeholder="my-client-id"
+ disabled={!!storage?.googleDriveStorage?.tokenJson}
+ />
+ </div>
+
+ <div className="mb-1 flex items-center">
+ <div className="min-w-[110px]">Client Secret</div>
+ <Input
+ value={storage?.googleDriveStorage?.clientSecret || ''}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
+ if (!storage?.googleDriveStorage) return;
+
+ setStorage({
+ ...storage,
+ googleDriveStorage: {
+ ...storage.googleDriveStorage,
+ clientSecret: e.target.value.trim(),
+ },
+ });
+ setIsUnsaved(true);
+ }}
+ size="small"
+ className="w-full max-w-[250px]"
+ placeholder="my-client-secret"
+ disabled={!!storage?.googleDriveStorage?.tokenJson}
+ />
+ </div>
+
+ {storage?.googleDriveStorage?.tokenJson && (
+ <>
+ <div className="mb-1 flex items-center">
+ <div className="min-w-[110px]">User Token</div>
+ <Input
+ value={storage?.googleDriveStorage?.tokenJson || ''}
+ disabled
+ size="small"
+ className="w-full max-w-[250px]"
+ placeholder="my-user-token"
+ />
+ </div>
+ </>
+ )}
+
+ {!storage?.googleDriveStorage?.tokenJson && (
+ <Button
+ type="primary"
+ disabled={
+ !storage?.googleDriveStorage?.clientId || !storage?.googleDriveStorage?.clientSecret
+ }
+ onClick={goToAuthUrl}
+ >
+ Authorize
+ </Button>
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/features/storages/ui/show/ShowStorageComponent.tsx b/frontend/src/features/storages/ui/show/ShowStorageComponent.tsx
index 12721370..2071b991 100644
--- a/frontend/src/features/storages/ui/show/ShowStorageComponent.tsx
+++ b/frontend/src/features/storages/ui/show/ShowStorageComponent.tsx
@@ -1,6 +1,7 @@
import { type Storage, StorageType } from '../../../../entity/storages';
import { getStorageLogoFromType } from '../../../../entity/storages/models/getStorageLogoFromType';
import { getStorageNameFromType } from '../../../../entity/storages/models/getStorageNameFromType';
+import { ShowGoogleDriveStorageComponent } from './storages/ShowGoogleDriveStorageComponent';
import { ShowS3StorageComponent } from './storages/ShowS3StorageComponent';
interface Props {
@@ -25,6 +26,12 @@ export function ShowStorageComponent({ storage }: Props) {
</div>
<div>{storage?.type === StorageType.S3 && <ShowS3StorageComponent storage={storage} />}</div>
+
+ <div>
+ {storage?.type === StorageType.GOOGLE_DRIVE && (
+ <ShowGoogleDriveStorageComponent storage={storage} />
+ )}
+ </div>
</div>
);
}
diff --git a/frontend/src/features/storages/ui/show/storages/ShowGoogleDriveStorageComponent.tsx b/frontend/src/features/storages/ui/show/storages/ShowGoogleDriveStorageComponent.tsx
new file mode 100644
index 00000000..f753df9a
--- /dev/null
+++ b/frontend/src/features/storages/ui/show/storages/ShowGoogleDriveStorageComponent.tsx
@@ -0,0 +1,32 @@
+import type { Storage } from '../../../../../entity/storages';
+
+interface Props {
+ storage: Storage;
+}
+
+export function ShowGoogleDriveStorageComponent({ storage }: Props) {
+ return (
+ <>
+ <div className="mb-1 flex items-center">
+ <div className="min-w-[110px]">Client ID</div>
+ {storage?.googleDriveStorage?.clientId
+ ? `${storage?.googleDriveStorage?.clientId.slice(0, 10)}***`
+ : '-'}
+ </div>
+
+ <div className="mb-1 flex items-center">
+ <div className="min-w-[110px]">Client Secret</div>
+ {storage?.googleDriveStorage?.clientSecret
+ ? `${storage?.googleDriveStorage?.clientSecret.slice(0, 10)}***`
+ : '-'}
+ </div>
+
+ <div className="mb-1 flex items-center">
+ <div className="min-w-[110px]">User Token</div>
+ {storage?.googleDriveStorage?.tokenJson
+ ? `${storage?.googleDriveStorage?.tokenJson.slice(0, 10)}***`
+ : '-'}
+ </div>
+ </>
+ );
+}