From c951006738502c22d560efe97e70f9bc92fbc97b Mon Sep 17 00:00:00 2001 From: alexanderbkl Date: Wed, 28 Aug 2024 18:55:42 +0200 Subject: [PATCH 1/8] remove redundant logs and redundant migration checker, refactor database orm to prevent migration failure --- internal/api/auth.go | 2 - internal/api/file_upload.go | 6 +- internal/entity/entity_init.go | 1 - internal/entity/entity_tables.go | 74 ++++++++----------- internal/entity/file.go | 5 +- .../entity/file_share_state_user_shared.go | 4 +- 6 files changed, 38 insertions(+), 54 deletions(-) diff --git a/internal/api/auth.go b/internal/api/auth.go index ac893c4..552ddf2 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -91,8 +91,6 @@ func LoginUser(router *gin.RouterGroup, tokenMaker token.Maker) { return } - log.Infof("nonce: %s", nonce) - // validate signature result := web3.ValidateMessageSignature( f.WalletAddress, diff --git a/internal/api/file_upload.go b/internal/api/file_upload.go index 27b1521..c3c9607 100644 --- a/internal/api/file_upload.go +++ b/internal/api/file_upload.go @@ -66,9 +66,6 @@ func CheckFilesExistInPool(router *gin.RouterGroup) { headObject, err := s3.HeadObject(s3Config, config.Env().WasabiBucket, customFileMeta.CID) if err != nil { //this means that the object doesn't exist at S3, so we can return CID to frontend for later upload of binary and metadata - log.Info("CID not found:") - log.Info(customFileMeta.CID) - } else { //this means that the object exists at S3, so we can create a file entry on database for the file @@ -155,7 +152,8 @@ func CheckFilesExistInPool(router *gin.RouterGroup) { } if headObject == nil { - log.Print("headObject is nil") + //file doesn't exist on pool + //log.Print("headObject is nil") } } diff --git a/internal/entity/entity_init.go b/internal/entity/entity_init.go index a65f18f..1841c65 100644 --- a/internal/entity/entity_init.go +++ b/internal/entity/entity_init.go @@ -16,7 +16,6 @@ func InitDb(opt migrate.Options) { start := time.Now() Entities.Migrate(db.Db(), opt) - Entities.WaitForMigration(db.Db()) log.Debugf("migrate: completed in %s", time.Since(start)) } diff --git a/internal/entity/entity_tables.go b/internal/entity/entity_tables.go index 50c011e..5a91d85 100644 --- a/internal/entity/entity_tables.go +++ b/internal/entity/entity_tables.go @@ -4,6 +4,8 @@ import ( "fmt" "time" + "runtime/debug" + "github.com/Hello-Storage/hello-back/internal/migrate" "gorm.io/gorm" ) @@ -12,19 +14,24 @@ type Tables map[string]interface{} // Entities contains database entities and their table names. var Entities = Tables{ - Error{}.TableName(): &Error{}, - User{}.TableName(): &User{}, - UserDetail{}.TableName(): &UserDetail{}, - UserLogin{}.TableName(): &UserLogin{}, - ReferredUser{}.TableName(): &ReferredUser{}, - Plan{}.TableName(): &Plan{}, - Subscription{}.TableName(): &Subscription{}, - Email{}.TableName(): &Email{}, - Wallet{}.TableName(): &Wallet{}, - Github{}.TableName(): &Github{}, - File{}.TableName(): &File{}, - FileShareState{}.TableName(): &FileShareState{}, - PublicFile{}.TableName(): &PublicFile{}, + + Error{}.TableName(): &Error{}, + + User{}.TableName(): &User{}, + UserDetail{}.TableName(): &UserDetail{}, + UserLogin{}.TableName(): &UserLogin{}, + + ReferredUser{}.TableName(): &ReferredUser{}, + Plan{}.TableName(): &Plan{}, + Subscription{}.TableName(): &Subscription{}, + Email{}.TableName(): &Email{}, + Wallet{}.TableName(): &Wallet{}, + Github{}.TableName(): &Github{}, + + File{}.TableName(): &File{}, + FileShareState{}.TableName(): &FileShareState{}, + PublicFile{}.TableName(): &PublicFile{}, + Folder{}.TableName(): &Folder{}, FileUser{}.TableName(): &FileUser{}, FolderUser{}.TableName(): &FolderUser{}, @@ -40,31 +47,6 @@ var Entities = Tables{ InvestAccount{}.TableName(): &InvestAccount{}, } -// WaitForMigration waits for the database migration to be successful. -func (list Tables) WaitForMigration(db *gorm.DB) { - type RowCount struct { - Count int - } - - attempts := 100 - for name := range list { - for i := 0; i <= attempts; i++ { - count := RowCount{} - if err := db.Raw(fmt.Sprintf("SELECT COUNT(*) AS count FROM %s", name)).Scan(&count).Error; err == nil { - log.Tracef("migrate: %s migrated", name) - break - } else { - log.Tracef("migrate: waiting for %s migration (%s)", name, err.Error()) - time.Sleep(100 * time.Millisecond) - } - - if i == attempts { - panic("migration failed") - } - } - } -} - // Truncate removes all data from tables without dropping them. func (list Tables) Truncate(db *gorm.DB) { var name string @@ -93,6 +75,8 @@ func (list Tables) Migrate(db *gorm.DB, opt migrate.Options) { defer func() { if r := recover(); r != nil { log.Errorf("migrate: %s in %s (panic)", r, name) + log.Error("stack trace:\n", string(debug.Stack())) // Print the stack trace + } }() @@ -100,18 +84,21 @@ func (list Tables) Migrate(db *gorm.DB, opt migrate.Options) { // Run pre migrations, if any. if err := migrate.Run(db, opt.Pre()); err != nil { - log.Error(err) + log.Errorf("migrate: pre-migration error: %v", err) } // Run ORM auto migrations. if opt.AutoMigrate { for name, entity = range list { + if name == "users" || name == "wallets" || name == "githubs" { - // if db.Migrator().HasTable(name) { - continue - // } + if db.Migrator().HasTable(name) { + continue + } } if err := db.AutoMigrate(entity); err != nil { + log.Errorf("migrate: initial error migrating %s: %v", name, err) + log.Debugf("migrate: %s (waiting 1s)", err) time.Sleep(time.Second) @@ -126,7 +113,8 @@ func (list Tables) Migrate(db *gorm.DB, opt migrate.Options) { // Run main migrations, if any. if err := migrate.Run(db, opt); err != nil { - log.Error(err) + log.Errorf("migrate: main migration error: %v", err) + } } diff --git a/internal/entity/file.go b/internal/entity/file.go index c49b188..32b35f7 100644 --- a/internal/entity/file.go +++ b/internal/entity/file.go @@ -41,8 +41,9 @@ type File struct { IsInPool *bool `gorm:"type:boolean;default:false;" json:"is_in_pool"` IPFSHash string `gorm:"type:varchar(256);default:NULL" json:"ipfs_hash"` //sharestates are referenced by this file's UID at file share state - FileShareState FileShareState `gorm:"foreignKey:FileUID;references:UID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"file_share_state"` - EncryptionStatus EncryptionStatus `gorm:"type:encryption_status;default:'public'" json:"encryption_status"` + FileShareStatesUserShared FileShareStatesUserShared `gorm:"foreignKey:FileUID;references:UID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"file_share_states_user_shared"` + FileShareState FileShareState `gorm:"foreignKey:FileUID;references:UID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"file_share_state"` + EncryptionStatus EncryptionStatus `gorm:"type:encryption_status;default:'public'" json:"encryption_status"` } // TableName returns the entity table name. diff --git a/internal/entity/file_share_state_user_shared.go b/internal/entity/file_share_state_user_shared.go index cccf231..c5c0396 100644 --- a/internal/entity/file_share_state_user_shared.go +++ b/internal/entity/file_share_state_user_shared.go @@ -7,9 +7,9 @@ import ( type FileShareStatesUserShared struct { ID uint `gorm:"primarykey" json:"id"` - FileUID string `gorm:"type:varchar(42);index;references:UID;referencedTable:files" json:"file_uid"` + FileUID string `gorm:"type:varchar(42);uniqueIndex;references:UID;referencedTable:files" json:"file_uid"` UserID uint `gorm:"type:int" json:"user_id"` - PublicFileUserShared PublicFileUserShared `gorm:"foreignKey:FileUID;reference:FileUID"` + PublicFileUserShared PublicFileUserShared `gorm:"foreignKey:FileUID;references:FileUID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"public_files_user_shared"` } func (FileShareStatesUserShared) TableName() string { From b4e61c6cf3151601a91dc8b635a5eadb58f6372a Mon Sep 17 00:00:00 2001 From: alexanderbkl Date: Wed, 28 Aug 2024 18:57:06 +0200 Subject: [PATCH 2/8] remove obsolete github oauth env parameters --- internal/config/env.go | 8 ++++---- pkg/oauth/github.go | 6 ++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/internal/config/env.go b/internal/config/env.go index 0110b21..4fe3df6 100644 --- a/internal/config/env.go +++ b/internal/config/env.go @@ -24,8 +24,8 @@ type EnvVar struct { DBPassword string DBPort string // Github OAuth credential - GithubClientID string - GithubClientSecret string + //GithubClientID string + //GithubClientSecret string // Wasabi keys WasabiAccessKey string WasabiSecretKey string @@ -76,8 +76,8 @@ func LoadEnv() (err error) { DBPassword: os.Getenv("POSTGRES_PASSWORD"), DBPort: os.Getenv("POSTGRES_PORT"), // Github OAuth credentail - GithubClientID: os.Getenv("GITHUB_CLIENT_ID"), - GithubClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"), + //GithubClientID: os.Getenv("GITHUB_CLIENT_ID"), + //GithubClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"), //Wasabi keys WasabiAccessKey: os.Getenv("WASABI_ACCESS_KEY"), WasabiSecretKey: os.Getenv("WASABI_SECRET_KEY"), diff --git a/pkg/oauth/github.go b/pkg/oauth/github.go index dea1e58..190c39e 100644 --- a/pkg/oauth/github.go +++ b/pkg/oauth/github.go @@ -9,8 +9,6 @@ import ( "net/http" "net/url" "time" - - "github.com/Hello-Storage/hello-back/internal/config" ) type GithubUser struct { @@ -24,8 +22,8 @@ func GetGithubOAuthToken(code string) (string, error) { values := url.Values{} values.Add("code", code) - values.Add("client_id", config.Env().GithubClientID) - values.Add("client_secret", config.Env().GithubClientSecret) + //values.Add("client_id", config.Env().GithubClientID) + //values.Add("client_secret", config.Env().GithubClientSecret) query := values.Encode() From e01291761c6c2b5cefd317f1433eddf19ae18c33 Mon Sep 17 00:00:00 2001 From: alexanderbkl Date: Tue, 10 Sep 2024 03:57:49 +0200 Subject: [PATCH 3/8] updated from deprecated cosmtrek/air to air-verse maker dependency --- docker/Dockerfile.dev | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/Dockerfile.dev b/docker/Dockerfile.dev index c859698..cb694f1 100644 --- a/docker/Dockerfile.dev +++ b/docker/Dockerfile.dev @@ -7,7 +7,7 @@ ENV CGO_ENABLED 0 ENV GOPATH /go ENV GOCACHE /go-build -RUN go install github.com/cosmtrek/air@latest +RUN go install github.com/air-verse/air@latest COPY go.mod go.sum ./ From 590cf476fa2c4d5c5fb90ee78931e28314e15ea7 Mon Sep 17 00:00:00 2001 From: alexanderbkl Date: Tue, 10 Sep 2024 07:34:11 +0200 Subject: [PATCH 4/8] fix and improve sharedByMe obtention by checking if filesharestate exists, refactor for scalability && remove unnecessary logs --- internal/api/file.go | 8 ++-- internal/api/user_detail.go | 88 +++++++++++++++++++++++-------------- internal/query/file.go | 7 ++- 3 files changed, 61 insertions(+), 42 deletions(-) diff --git a/internal/api/file.go b/internal/api/file.go index 8d47c4a..1c4cd28 100644 --- a/internal/api/file.go +++ b/internal/api/file.go @@ -143,7 +143,7 @@ func GetShareState(router *gin.RouterGroup) { //get share state, if doesn't exist, create it share_state, _, err := query.FindShareStateByFileUID(file_uid) if err != nil { - log.Errorf("Error finding share state: %s", err) + //log.Errorf("Error finding share state: %s", err) share_state, err = query.CreateShareState(tx, f) if err != nil { log.Errorf("cannot create share state: %s", err) @@ -188,7 +188,7 @@ func GetShareState(router *gin.RouterGroup) { // get share state, if doesn't exist, create it shareState, _, err := query.FindShareStateByFileUID(fileUID) if err != nil { - log.Errorf("Error finding share state: %s", err) + //log.Errorf("Error finding share state: %s", err) shareState, err = query.CreateShareState(tx, f) if err != nil { log.Errorf("cannot create share state: %s", err) @@ -411,7 +411,7 @@ func PublishFile(router *gin.RouterGroup) { ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid share type"}) return } - + //cancel if user not found receiverNil := shareWithUser == nil || shareWithUser.ID == 0 if receiverNil { @@ -458,7 +458,7 @@ func PublishFile(router *gin.RouterGroup) { } // delete the file share state user shared in case it exists - query.DeleteFileShareStatesUserShared(db.Db(),f.UID, shareWithUser.ID) + query.DeleteFileShareStatesUserShared(db.Db(), f.UID, shareWithUser.ID) // create a new share state user shared shareState, err := query.CreateShareStateUserShared(tx, newFile, shareWithUser.ID) if err != nil { diff --git a/internal/api/user_detail.go b/internal/api/user_detail.go index 4bfb8ce..4db57b2 100644 --- a/internal/api/user_detail.go +++ b/internal/api/user_detail.go @@ -72,72 +72,92 @@ func GetUserDetail(router *gin.RouterGroup) { return } - // get user files from the table "file_user" (where permission != deleted) + // get filesUser from the table "file_user" (where permission != deleted) filesUser, err := query.GetFilesUserFromUser(user.ID) if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "error fetching user files"}) return } - // start variables for shared files var sharedWithUser entity.Files var sharedByUser entity.Files + sharedByUserMap := make(map[uint]struct{}) + sharedWithUserMap := make(map[string]struct{}) - // iterate over files + // Create a channel to fetch files concurrently + type fileResult struct { + file *entity.File + err error + } + fileChan := make(chan fileResult, len(filesUser)) + + // Fetch files concurrently using goroutines for _, fileUser := range filesUser { - // try to get file by its id - file, err := query.FindFileByID(fileUser.FileID) - if err != nil { - log.Errorf("error fetching file: %v", err) - if err != gorm.ErrRecordNotFound { - // if it's not a "not found" error it means it's probably an internal error, so stop here + go func(fileUser entity.FileUser) { + file, err := query.FindFileByID(fileUser.FileID) + fileChan <- fileResult{file: file, err: err} + }(fileUser) + } + + for _, fileUser := range filesUser { + fileResult := <-fileChan + if fileResult.err != nil { + log.Errorf("error fetching file: %v", fileResult.err) + if fileResult.err != gorm.ErrRecordNotFound { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "error fetching file"}) return } - // if it's a "not found" error, continue with the next file continue } - // get users with file CID + file := fileResult.file + + // Filter files shared by the user + if file.FileShareState.ID != 0 && fileUser.Permission == entity.OwnerPermission { + if _, exists := sharedByUserMap[file.ID]; exists { + continue + } + sharedByUser = append(sharedByUser, *file) + sharedByUserMap[file.ID] = struct{}{} + } + + // Check if the file CID has already been processed + if _, exists := sharedWithUserMap[file.CID]; exists { + continue // Skip processing the file if this CID has already been processed + } + + // Concurrently fetch users with the file CID usersWithFile, err := query.FindUsersByFileCID(file.CID) if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "error fetching users with file"}) return } - // filter out usersID that belong to others than the current user - usersWithFileFiltered := []uint{} + // Filter out usersID that belong to others than the current user + usersWithFileFiltered := make([]uint, 0, len(usersWithFile)) for _, usrID := range usersWithFile { if usrID != user.ID { usersWithFileFiltered = append(usersWithFileFiltered, usrID) } } - if file.ID != 0 { - if fileUser.Permission == entity.SharedPermission && len(usersWithFileFiltered) > 0 { - // if the file is shared to current user and its more than one user with the file - // then it's a shared (with the user) file - if file.Root == "/" /*|| !query.IsInSharedFolder(file.Root, authPayload.UserID) */{ - // if the file was shared by email or wallet, we need to get - // the public file and its share state - sharestatefound, err := query.GetFileShareStateByFileUIDAndUserID(file.UID, authPayload.UserID) - if err == nil { - file.FileShareState = query.ConvertToDomainEntities(sharestatefound) - } - sharedWithUser = append(sharedWithUser, *file) - } - } else if fileUser.Permission == entity.OwnerPermission && len(usersWithFileFiltered) > 0 { - // if the file owned by current user and its more than one user with the file - // then it's a shared (by the user) file - if file.Root == "/" /*|| !query.IsInSharedFolder(file.Root, authPayload.UserID) */{ - // TODO: check if the file/forder is in a shared folder or not - // (because if we only show the files in Root, the elements in a non-shared folder will not be shown) - sharedByUser = append(sharedByUser, *file) + if file.ID != 0 && fileUser.Permission == entity.SharedPermission && len(usersWithFileFiltered) > 0 { + if file.Root == "/" { + sharestatefound, err := query.GetFileShareStateByFileUIDAndUserID(file.UID, authPayload.UserID) + if err == nil { + file.FileShareState = query.ConvertToDomainEntities(sharestatefound) } + + sharedWithUser = append(sharedWithUser, *file) + // Mark this CID as processed to avoid duplicate entries + sharedWithUserMap[file.CID] = struct{}{} } } } + // Close the channel after processing + close(fileChan) + // at this point we have all the shared files, now we need to get the folders // get user folders from the table "folder_user" @@ -185,7 +205,7 @@ func GetUserDetail(router *gin.RouterGroup) { if folder.ID != 0 { if folderUser.Permission == entity.SharedPermission && len(usersWithFolderFiltered) > 0 { if folder.Root == "/" /*|| !query.IsInSharedFolder(folder.Root, authPayload.UserID)*/ { - // TODO: check if the file/forder is in a shared folder or not + // TODO: check if the file/forder is in a shared folder or not // (because if we only show the files in Root, the elements in a non-shared folder will not be shown) FoldersharedwithUser = append(FoldersharedwithUser, *folder) } diff --git a/internal/query/file.go b/internal/query/file.go index 41bc25e..2c5f1f5 100644 --- a/internal/query/file.go +++ b/internal/query/file.go @@ -90,7 +90,6 @@ func FindFilesByRootWithPermision(root string, userId uint) (files entity.Files, return files, nil } - // FindSharedFilesByRoot returns shared files in a given folder root. func FindPublicFilesByRoot(root string) (publicFiles []entity.PublicFile, err error) { files, err := FindFilesByRoot(root) @@ -626,7 +625,7 @@ func FindFilesNotInPool() (files entity.Files, err error) { } // get if file is in a shared folder or not -func IsInSharedFolder(fileRoot string, userID uint) (bool) { +func IsInSharedFolder(fileRoot string, userID uint) bool { // if file root is empty or user id is 0, return false if fileRoot == "" || userID == 0 || fileRoot == "/" { @@ -647,11 +646,11 @@ func IsInSharedFolder(fileRoot string, userID uint) (bool) { // get folder user by folder id and user id query = db.Db().Table("folder_users").Select("*"). - Where("user_id = ? AND folder_id = ?", userID, folderID) + Where("user_id = ? AND folder_id = ?", userID, folderID) var folderUser entity.FolderUser - if err := query.Scan(&folderUser) .Error; err != nil { + if err := query.Scan(&folderUser).Error; err != nil { return false } From ceb00634c1c983ff7dd300c3e4bc89c3bdc512db Mon Sep 17 00:00:00 2001 From: alexanderbkl Date: Tue, 10 Sep 2024 07:39:10 +0200 Subject: [PATCH 5/8] readded TODO comments --- internal/api/user_detail.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/internal/api/user_detail.go b/internal/api/user_detail.go index 4db57b2..0bd299d 100644 --- a/internal/api/user_detail.go +++ b/internal/api/user_detail.go @@ -117,6 +117,9 @@ func GetUserDetail(router *gin.RouterGroup) { if _, exists := sharedByUserMap[file.ID]; exists { continue } + /*|| !query.IsInSharedFolder(file.Root, authPayload.UserID) */ + // TODO: check if the file/forder is in a shared folder or not + // (because if we only show the files in Root, the elements in a non-shared folder will not be shown) sharedByUser = append(sharedByUser, *file) sharedByUserMap[file.ID] = struct{}{} } @@ -143,6 +146,8 @@ func GetUserDetail(router *gin.RouterGroup) { if file.ID != 0 && fileUser.Permission == entity.SharedPermission && len(usersWithFileFiltered) > 0 { if file.Root == "/" { + // TODO: check if the file/forder is in a shared folder or not + // (because if we only show the files in Root, the elements in a non-shared folder will not be shown) sharestatefound, err := query.GetFileShareStateByFileUIDAndUserID(file.UID, authPayload.UserID) if err == nil { file.FileShareState = query.ConvertToDomainEntities(sharestatefound) From 19335838dea29a8c3261faea3d0465c5bde46e71 Mon Sep 17 00:00:00 2001 From: alexanderbkl Date: Thu, 12 Sep 2024 08:28:45 +0200 Subject: [PATCH 6/8] remove redundant code --- internal/api/file.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/internal/api/file.go b/internal/api/file.go index 1c4cd28..478e849 100644 --- a/internal/api/file.go +++ b/internal/api/file.go @@ -484,7 +484,7 @@ func PublishFile(router *gin.RouterGroup) { // Send email with the file link to the user if the share type is email if shareType == "email" { // Send email with the file link to the user and pass also the sender user's email - sendEmailLinkToUser(authPayload.UserName, shareWithUser, accountIdentifier, newFile, publicFile) + sendEmailLinkToUser(authPayload.UserName, accountIdentifier, newFile, publicFile) } // Save the updated shareState.PublicFile @@ -518,7 +518,7 @@ func formatBytes(size int64) string { return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp]) } -func sendEmailLinkToUser(username string, user *entity.User, email string, file *entity.File, publicFile *entity.PublicFileUserShared) { +func sendEmailLinkToUser(username string, email string, file *entity.File, publicFile *entity.PublicFileUserShared) { mg := mg.Mailgun{ Domain: "hello.app", @@ -526,7 +526,8 @@ func sendEmailLinkToUser(username string, user *entity.User, email string, file } mg.Init() - id, err := mg.SendEmail( + //id, err := mg.SendEmail( + _, err := mg.SendEmail( "noreply@hello.app", email, "hello.app | Received file named "+file.Name+"", @@ -540,7 +541,7 @@ func sendEmailLinkToUser(username string, user *entity.User, email string, file }, ) - log.Infof("id: %s", id) + //log.Infof("id: %s", id) if err != nil { log.Errorf("failed to send email: %v", err) From c26f4a92f646d072492e16a496d4e4e31df8b323 Mon Sep 17 00:00:00 2001 From: alexanderbkl Date: Thu, 12 Sep 2024 08:52:23 +0200 Subject: [PATCH 7/8] remove deprecated circleci docker verioning --- .circleci/config.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 16fed6b..216ca2b 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -52,7 +52,6 @@ jobs: steps: - checkout - setup_remote_docker: - version: 20.10.14 docker_layer_caching: true - build-docker-image - run: @@ -67,7 +66,6 @@ jobs: steps: - checkout - setup_remote_docker: - version: 20.10.14 docker_layer_caching: true - attach_workspace: at: /tmp/workspace From e2fcc0f5aa33bba20446859c8acbfe9c4bca074d Mon Sep 17 00:00:00 2001 From: alexanderbkl Date: Thu, 12 Sep 2024 11:02:47 +0200 Subject: [PATCH 8/8] prevent getting shared files on main files page --- internal/query/file.go | 2 +- internal/query/file_share.go | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/query/file.go b/internal/query/file.go index 2c5f1f5..abe0002 100644 --- a/internal/query/file.go +++ b/internal/query/file.go @@ -83,7 +83,7 @@ func FindFilesByRoot(root string) (files entity.Files, err error) { return files, nil } func FindFilesByRootWithPermision(root string, userId uint) (files entity.Files, err error) { - if err := db.Db().Table("files").Joins("INNER JOIN files_users ON files_users.file_id = files.id").Where("files.root = ? AND files_users.user_id = ? AND files.deleted_at IS NULL", root, userId).Find(&files).Error; err != nil { + if err := db.Db().Table("files").Joins("INNER JOIN files_users ON files_users.file_id = files.id").Where("files.root = ? AND files.c_id_original_encrypted NOT LIKE '' AND files_users.user_id = ? AND files.deleted_at IS NULL", root, userId).Find(&files).Error; err != nil { return files, err } diff --git a/internal/query/file_share.go b/internal/query/file_share.go index bf2cd93..613c5f9 100644 --- a/internal/query/file_share.go +++ b/internal/query/file_share.go @@ -157,7 +157,7 @@ func DeleteFileShareStatesUserShared(db *gorm.DB, fileUID string, userID uint) e // Check if the error is due to the record not being found, which isn't considered an error in this context. if errors.Is(result.Error, gorm.ErrRecordNotFound) { // Possibly log this as info or debug, as it's an expected situation that doesn't require an action. - log.Infof("No file share state found for UID: %s, UserID: %d. Nothing to delete.", fileUID, userID) + //log.Infof("No file share state found for UID: %s, UserID: %d. Nothing to delete.", fileUID, userID) // Return nil to continue the transaction without considering this as an error. return nil } else { @@ -168,9 +168,9 @@ func DeleteFileShareStatesUserShared(db *gorm.DB, fileUID string, userID uint) e } db.Unscoped().Delete(&fileShareState.PublicFileUserShared) - db.Unscoped().Delete(&fileShareState); // Perform the second delete operation only if the previous operations were successful. + db.Unscoped().Delete(&fileShareState) // Perform the second delete operation only if the previous operations were successful. db.Unscoped().Where("file_uid = ?", fileUID).Delete(&filepublicf) - + // If everything was successful, return nil indicating no error occurred. return nil } @@ -183,7 +183,7 @@ func DeleteFileShareState(tx *gorm.DB, fileUID string) { if result.Error == nil { tx.Unscoped().Delete(&fileShareState.PublicFile) tx.Unscoped().Delete(&fileShareState) - // if error is record not found, ignore it + // if error is record not found, ignore it } else if !errors.Is(result.Error, gorm.ErrRecordNotFound) { log.Errorf("Error while finding file share state: %v", result.Error) }