xui.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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("/groups", a.panelSPA)
  35. g.GET("/nodes", a.panelSPA)
  36. g.GET("/settings", a.panelSPA)
  37. g.GET("/xray", a.panelSPA)
  38. g.GET("/api-docs", a.panelSPA)
  39. // SPA pages built by Vite don't have a server-rendered <meta name="csrf-token">,
  40. // so they fetch the session token via this endpoint at startup and replay it
  41. // on subsequent unsafe requests through axios.
  42. g.GET("/csrf-token", a.csrfToken)
  43. a.settingController = NewSettingController(g)
  44. a.xraySettingController = NewXraySettingController(g)
  45. }
  46. // panelSPA serves the React SPA shell. Every GET under /panel/ that isn't an
  47. // API endpoint returns the same index.html — React Router reads the URL and
  48. // mounts the matching page on the client.
  49. func (a *XUIController) panelSPA(c *gin.Context) {
  50. serveDistPage(c, "index.html")
  51. }
  52. // csrfToken returns the session CSRF token to authenticated SPA clients.
  53. // The endpoint is GET (a safe method) so it bypasses CSRFMiddleware itself,
  54. // but checkLogin still gates the response — anonymous callers get 401/redirect.
  55. func (a *XUIController) csrfToken(c *gin.Context) {
  56. token, err := session.EnsureCSRFToken(c)
  57. if err != nil {
  58. c.JSON(http.StatusInternalServerError, entity.Msg{Success: false, Msg: err.Error()})
  59. return
  60. }
  61. c.JSON(http.StatusOK, entity.Msg{Success: true, Obj: token})
  62. }