delete.go 1.8 KB

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