|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/0xJacky/Nginx-UI/internal/config" |
| 8 | + "github.com/0xJacky/Nginx-UI/internal/helper" |
| 9 | + "github.com/0xJacky/Nginx-UI/internal/nginx" |
| 10 | + "github.com/gin-gonic/gin" |
| 11 | + "github.com/uozi-tech/cosy" |
| 12 | +) |
| 13 | + |
| 14 | +// DeleteConfig handles the deletion of configuration files or directories |
| 15 | +func DeleteConfig(c *gin.Context) { |
| 16 | + var json struct { |
| 17 | + BasePath string `json:"base_path"` |
| 18 | + Name string `json:"name" binding:"required"` |
| 19 | + SyncNodeIds []uint64 `json:"sync_node_ids" gorm:"serializer:json"` |
| 20 | + } |
| 21 | + if !cosy.BindAndValid(c, &json) { |
| 22 | + return |
| 23 | + } |
| 24 | + |
| 25 | + // Decode paths from URL encoding |
| 26 | + decodedBasePath := helper.UnescapeURL(json.BasePath) |
| 27 | + decodedName := helper.UnescapeURL(json.Name) |
| 28 | + |
| 29 | + fullPath := nginx.GetConfPath(decodedBasePath, decodedName) |
| 30 | + |
| 31 | + // Check if path is under nginx config directory |
| 32 | + if err := config.ValidateDeletePath(fullPath); err != nil { |
| 33 | + cosy.ErrHandler(c, err) |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + // Check if trying to delete protected paths |
| 38 | + if config.IsProtectedPath(fullPath, decodedName) { |
| 39 | + cosy.ErrHandler(c, config.ErrCannotDeleteProtectedPath) |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + // Check if file/directory exists |
| 44 | + stat, err := config.CheckFileExists(fullPath) |
| 45 | + if err != nil { |
| 46 | + cosy.ErrHandler(c, err) |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + // Delete the file or directory |
| 51 | + err = os.RemoveAll(fullPath) |
| 52 | + if err != nil { |
| 53 | + cosy.ErrHandler(c, err) |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + // Clean up database records |
| 58 | + if err := config.CleanupDatabaseRecords(fullPath, stat.IsDir()); err != nil { |
| 59 | + cosy.ErrHandler(c, err) |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + // Sync deletion to remote servers if configured |
| 64 | + if len(json.SyncNodeIds) > 0 { |
| 65 | + err = config.SyncDeleteOnRemoteServer(fullPath, json.SyncNodeIds) |
| 66 | + if err != nil { |
| 67 | + cosy.ErrHandler(c, err) |
| 68 | + return |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + c.JSON(http.StatusOK, gin.H{ |
| 73 | + "message": "deleted successfully", |
| 74 | + }) |
| 75 | +} |
0 commit comments