api.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. Tgbot service.Tgbot
  19. }
  20. // NewAPIController creates a new APIController instance and initializes its routes.
  21. func NewAPIController(g *gin.RouterGroup, customGeo *service.CustomGeoService) *APIController {
  22. a := &APIController{}
  23. a.initRouter(g, customGeo)
  24. return a
  25. }
  26. func (a *APIController) checkAPIAuth(c *gin.Context) {
  27. auth := c.GetHeader("Authorization")
  28. if strings.HasPrefix(auth, "Bearer ") {
  29. tok := strings.TrimPrefix(auth, "Bearer ")
  30. if a.settingService.MatchApiToken(tok) {
  31. if u, err := a.userService.GetFirstUser(); err == nil {
  32. session.SetAPIAuthUser(c, u)
  33. }
  34. c.Set("api_authed", true)
  35. c.Next()
  36. return
  37. }
  38. }
  39. if !session.IsLogin(c) {
  40. if c.GetHeader("X-Requested-With") == "XMLHttpRequest" {
  41. c.AbortWithStatus(http.StatusUnauthorized)
  42. } else {
  43. c.AbortWithStatus(http.StatusNotFound)
  44. }
  45. return
  46. }
  47. c.Next()
  48. }
  49. // initRouter sets up the API routes for inbounds, server, and other endpoints.
  50. func (a *APIController) initRouter(g *gin.RouterGroup, customGeo *service.CustomGeoService) {
  51. // Main API group
  52. api := g.Group("/panel/api")
  53. api.Use(a.checkAPIAuth)
  54. api.Use(middleware.CSRFMiddleware())
  55. // Inbounds API
  56. inbounds := api.Group("/inbounds")
  57. a.inboundController = NewInboundController(inbounds)
  58. // Server API
  59. server := api.Group("/server")
  60. a.serverController = NewServerController(server)
  61. // Nodes API — multi-panel management
  62. nodes := api.Group("/nodes")
  63. a.nodeController = NewNodeController(nodes)
  64. NewCustomGeoController(api.Group("/custom-geo"), customGeo)
  65. // Extra routes
  66. api.POST("/backuptotgbot", a.BackuptoTgbot)
  67. }
  68. // BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
  69. func (a *APIController) BackuptoTgbot(c *gin.Context) {
  70. a.Tgbot.SendBackupToAdmins()
  71. }