rename.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package config
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api"
  4. "github.com/0xJacky/Nginx-UI/internal/helper"
  5. "github.com/0xJacky/Nginx-UI/internal/nginx"
  6. "github.com/0xJacky/Nginx-UI/query"
  7. "github.com/gin-gonic/gin"
  8. "net/http"
  9. "os"
  10. )
  11. func Rename(c *gin.Context) {
  12. var json struct {
  13. BasePath string `json:"base_path"`
  14. OrigName string `json:"orig_name"`
  15. NewName string `json:"new_name"`
  16. }
  17. if !api.BindAndValid(c, &json) {
  18. return
  19. }
  20. if json.OrigName == json.OrigName {
  21. c.JSON(http.StatusOK, gin.H{
  22. "message": "ok",
  23. })
  24. return
  25. }
  26. origFullPath := nginx.GetConfPath(json.BasePath, json.OrigName)
  27. newFullPath := nginx.GetConfPath(json.BasePath, json.NewName)
  28. if !helper.IsUnderDirectory(origFullPath, nginx.GetConfPath()) ||
  29. !helper.IsUnderDirectory(newFullPath, nginx.GetConfPath()) {
  30. c.JSON(http.StatusForbidden, gin.H{
  31. "message": "you are not allowed to rename a file " +
  32. "outside of the nginx config path",
  33. })
  34. return
  35. }
  36. stat, err := os.Stat(origFullPath)
  37. if err != nil {
  38. api.ErrHandler(c, err)
  39. return
  40. }
  41. if helper.FileExists(newFullPath) {
  42. c.JSON(http.StatusNotAcceptable, gin.H{
  43. "message": "target file already exists",
  44. })
  45. return
  46. }
  47. err = os.Rename(origFullPath, newFullPath)
  48. if err != nil {
  49. api.ErrHandler(c, err)
  50. return
  51. }
  52. if !stat.IsDir() {
  53. // update ChatGPT records
  54. g := query.ChatGPTLog
  55. _, _ = g.Where(g.Name.Eq(newFullPath)).Delete()
  56. _, _ = g.Where(g.Name.Eq(origFullPath)).Update(g.Name, newFullPath)
  57. }
  58. c.JSON(http.StatusOK, gin.H{
  59. "message": "ok",
  60. })
  61. }