1
0

spa.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package controller
  2. import (
  3. "net/http"
  4. "github.com/mhsanaei/3x-ui/v3/internal/web/entity"
  5. "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
  6. "github.com/mhsanaei/3x-ui/v3/internal/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("/outbound", a.panelSPA)
  37. g.GET("/routing", 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. }
  44. // panelSPA serves the React SPA shell. Every GET under /panel/ that isn't an
  45. // API endpoint returns the same index.html — React Router reads the URL and
  46. // mounts the matching page on the client.
  47. func (a *XUIController) panelSPA(c *gin.Context) {
  48. serveDistPage(c, "index.html")
  49. }
  50. // csrfToken returns the session CSRF token to authenticated SPA clients.
  51. // The endpoint is GET (a safe method) so it bypasses CSRFMiddleware itself,
  52. // but checkLogin still gates the response — anonymous callers get 401/redirect.
  53. func (a *XUIController) csrfToken(c *gin.Context) {
  54. token, err := session.EnsureCSRFToken(c)
  55. if err != nil {
  56. c.JSON(http.StatusInternalServerError, entity.Msg{Success: false, Msg: err.Error()})
  57. return
  58. }
  59. c.JSON(http.StatusOK, entity.Msg{Success: true, Obj: token})
  60. }