api.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 strings.HasPrefix(auth, "Bearer ") {
  30. tok := strings.TrimPrefix(auth, "Bearer ")
  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. // Server API
  60. server := api.Group("/server")
  61. a.serverController = NewServerController(server)
  62. // Nodes API — multi-panel management
  63. nodes := api.Group("/nodes")
  64. a.nodeController = NewNodeController(nodes)
  65. NewCustomGeoController(api.Group("/custom-geo"), customGeo)
  66. // Extra routes
  67. api.POST("/backuptotgbot", a.BackuptoTgbot)
  68. }
  69. // BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
  70. func (a *APIController) BackuptoTgbot(c *gin.Context) {
  71. a.Tgbot.SendBackupToAdmins()
  72. }