add.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package config
  2. import (
  3. "net/http"
  4. "os"
  5. "path/filepath"
  6. "time"
  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/0xJacky/Nginx-UI/model"
  11. "github.com/0xJacky/Nginx-UI/query"
  12. "github.com/gin-gonic/gin"
  13. "github.com/uozi-tech/cosy"
  14. )
  15. func AddConfig(c *gin.Context) {
  16. var json struct {
  17. config.SyncConfigPayload
  18. SyncNodeIds []uint64 `json:"sync_node_ids"`
  19. }
  20. if !cosy.BindAndValid(c, &json) {
  21. return
  22. }
  23. name := json.Name
  24. content := json.Content
  25. // Decode paths from URL encoding
  26. decodedBaseDir := helper.UnescapeURL(json.BaseDir)
  27. decodedName := helper.UnescapeURL(name)
  28. dir := nginx.GetConfPath(decodedBaseDir)
  29. path := filepath.Join(dir, decodedName)
  30. if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  31. c.JSON(http.StatusForbidden, gin.H{
  32. "message": "filepath is not under the nginx conf path",
  33. })
  34. return
  35. }
  36. if !json.Overwrite && helper.FileExists(path) {
  37. c.JSON(http.StatusNotAcceptable, gin.H{
  38. "message": "File exists",
  39. })
  40. return
  41. }
  42. // check if the dir exists, if not, use mkdirAll to create the dir
  43. if !helper.FileExists(dir) {
  44. err := os.MkdirAll(dir, 0755)
  45. if err != nil {
  46. cosy.ErrHandler(c, err)
  47. return
  48. }
  49. }
  50. err := os.WriteFile(path, []byte(content), 0644)
  51. if err != nil {
  52. cosy.ErrHandler(c, err)
  53. return
  54. }
  55. res := nginx.Control(nginx.Reload)
  56. if res.IsError() {
  57. res.RespError(c)
  58. return
  59. }
  60. q := query.Config
  61. _, err = q.Where(q.Filepath.Eq(path)).Delete()
  62. if err != nil {
  63. cosy.ErrHandler(c, err)
  64. return
  65. }
  66. cfg := &model.Config{
  67. Name: name,
  68. Filepath: path,
  69. SyncNodeIds: json.SyncNodeIds,
  70. SyncOverwrite: json.Overwrite,
  71. }
  72. err = q.Create(cfg)
  73. if err != nil {
  74. cosy.ErrHandler(c, err)
  75. return
  76. }
  77. err = config.SyncToRemoteServer(cfg)
  78. if err != nil {
  79. cosy.ErrHandler(c, err)
  80. return
  81. }
  82. c.JSON(http.StatusOK, config.Config{
  83. Name: name,
  84. Content: content,
  85. FilePath: path,
  86. ModifiedAt: time.Now(),
  87. })
  88. }