xui.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package controller
  2. import (
  3. "net/http"
  4. "github.com/mhsanaei/3x-ui/v3/web/entity"
  5. "github.com/mhsanaei/3x-ui/v3/web/middleware"
  6. "github.com/mhsanaei/3x-ui/v3/web/session"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // XUIController is the main controller for the X-UI panel, managing sub-controllers.
  10. type XUIController struct {
  11. BaseController
  12. settingController *SettingController
  13. xraySettingController *XraySettingController
  14. }
  15. // NewXUIController creates a new XUIController and initializes its routes.
  16. func NewXUIController(g *gin.RouterGroup) *XUIController {
  17. a := &XUIController{}
  18. a.initRouter(g)
  19. return a
  20. }
  21. // initRouter sets up the main panel routes and initializes sub-controllers.
  22. //
  23. // The HTML routes all hand the same single-page-app shell (index.html) to the
  24. // browser; React Router takes over and renders the correct page from the URL.
  25. // The /panel/api, /panel/setting, /panel/xray sub-routers register POST/JSON
  26. // endpoints on different paths and stay untouched by the shell handler.
  27. func (a *XUIController) initRouter(g *gin.RouterGroup) {
  28. g = g.Group("/panel")
  29. g.Use(a.checkLogin)
  30. g.Use(middleware.CSRFMiddleware())
  31. g.GET("/", a.panelSPA)
  32. g.GET("/inbounds", a.panelSPA)
  33. g.GET("/clients", a.panelSPA)
  34. g.GET("/nodes", a.panelSPA)
  35. g.GET("/settings", a.panelSPA)
  36. g.GET("/xray", a.panelSPA)
  37. g.GET("/api-docs", a.panelSPA)
  38. // SPA pages built by Vite don't have a server-rendered <meta name="csrf-token">,
  39. // so they fetch the session token via this endpoint at startup and replay it
  40. // on subsequent unsafe requests through axios.
  41. g.GET("/csrf-token", a.csrfToken)
  42. a.settingController = NewSettingController(g)
  43. a.xraySettingController = NewXraySettingController(g)
  44. }
  45. // panelSPA serves the React SPA shell. Every GET under /panel/ that isn't an
  46. // API endpoint returns the same index.html — React Router reads the URL and
  47. // mounts the matching page on the client.
  48. func (a *XUIController) panelSPA(c *gin.Context) {
  49. serveDistPage(c, "index.html")
  50. }
  51. // csrfToken returns the session CSRF token to authenticated SPA clients.
  52. // The endpoint is GET (a safe method) so it bypasses CSRFMiddleware itself,
  53. // but checkLogin still gates the response — anonymous callers get 401/redirect.
  54. func (a *XUIController) csrfToken(c *gin.Context) {
  55. token, err := session.EnsureCSRFToken(c)
  56. if err != nil {
  57. c.JSON(http.StatusInternalServerError, entity.Msg{Success: false, Msg: err.Error()})
  58. return
  59. }
  60. c.JSON(http.StatusOK, entity.Msg{Success: true, Obj: token})
  61. }