xui.go 2.3 KB

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