1
0

api.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package controller
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/mhsanaei/3x-ui/v3/web/middleware"
  6. "github.com/mhsanaei/3x-ui/v3/web/service"
  7. "github.com/mhsanaei/3x-ui/v3/web/session"
  8. "github.com/gin-gonic/gin"
  9. )
  10. // APIController handles the main API routes for the 3x-ui panel, including inbounds and server management.
  11. type APIController struct {
  12. BaseController
  13. inboundController *InboundController
  14. serverController *ServerController
  15. nodeController *NodeController
  16. settingService service.SettingService
  17. userService service.UserService
  18. apiTokenService service.ApiTokenService
  19. Tgbot service.Tgbot
  20. }
  21. // NewAPIController creates a new APIController instance and initializes its routes.
  22. func NewAPIController(g *gin.RouterGroup, customGeo *service.CustomGeoService) *APIController {
  23. a := &APIController{}
  24. a.initRouter(g, customGeo)
  25. return a
  26. }
  27. func (a *APIController) checkAPIAuth(c *gin.Context) {
  28. auth := c.GetHeader("Authorization")
  29. if after, ok := strings.CutPrefix(auth, "Bearer "); ok {
  30. tok := after
  31. if a.apiTokenService.Match(tok) {
  32. if u, err := a.userService.GetFirstUser(); err == nil {
  33. session.SetAPIAuthUser(c, u)
  34. }
  35. c.Set("api_authed", true)
  36. c.Next()
  37. return
  38. }
  39. }
  40. if !session.IsLogin(c) {
  41. if c.GetHeader("X-Requested-With") == "XMLHttpRequest" {
  42. c.AbortWithStatus(http.StatusUnauthorized)
  43. } else {
  44. c.AbortWithStatus(http.StatusNotFound)
  45. }
  46. return
  47. }
  48. c.Next()
  49. }
  50. // initRouter sets up the API routes for inbounds, server, and other endpoints.
  51. func (a *APIController) initRouter(g *gin.RouterGroup, customGeo *service.CustomGeoService) {
  52. // Main API group
  53. api := g.Group("/panel/api")
  54. api.Use(a.checkAPIAuth)
  55. api.Use(middleware.CSRFMiddleware())
  56. // Inbounds API
  57. inbounds := api.Group("/inbounds")
  58. a.inboundController = NewInboundController(inbounds)
  59. clients := api.Group("/clients")
  60. NewClientController(clients)
  61. NewGroupController(clients)
  62. // Server API
  63. server := api.Group("/server")
  64. a.serverController = NewServerController(server)
  65. // Nodes API — multi-panel management
  66. nodes := api.Group("/nodes")
  67. a.nodeController = NewNodeController(nodes)
  68. NewCustomGeoController(api.Group("/custom-geo"), customGeo)
  69. // Extra routes
  70. api.POST("/backuptotgbot", a.BackuptoTgbot)
  71. }
  72. // BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
  73. func (a *APIController) BackuptoTgbot(c *gin.Context) {
  74. a.Tgbot.SendBackupToAdmins()
  75. }