api.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package controller
  2. import (
  3. "net/http"
  4. "github.com/mhsanaei/3x-ui/v2/web/middleware"
  5. "github.com/mhsanaei/3x-ui/v2/web/service"
  6. "github.com/mhsanaei/3x-ui/v2/web/session"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // APIController handles the main API routes for the 3x-ui panel, including inbounds and server management.
  10. type APIController struct {
  11. BaseController
  12. inboundController *InboundController
  13. serverController *ServerController
  14. Tgbot service.Tgbot
  15. }
  16. // NewAPIController creates a new APIController instance and initializes its routes.
  17. func NewAPIController(g *gin.RouterGroup, customGeo *service.CustomGeoService) *APIController {
  18. a := &APIController{}
  19. a.initRouter(g, customGeo)
  20. return a
  21. }
  22. // checkAPIAuth is a middleware that returns 404 for unauthenticated API requests
  23. // to hide the existence of API endpoints from unauthorized users
  24. func (a *APIController) checkAPIAuth(c *gin.Context) {
  25. if !session.IsLogin(c) {
  26. c.AbortWithStatus(http.StatusNotFound)
  27. return
  28. }
  29. c.Next()
  30. }
  31. // initRouter sets up the API routes for inbounds, server, and other endpoints.
  32. func (a *APIController) initRouter(g *gin.RouterGroup, customGeo *service.CustomGeoService) {
  33. // Main API group
  34. api := g.Group("/panel/api")
  35. api.Use(a.checkAPIAuth)
  36. api.Use(middleware.CSRFMiddleware())
  37. // Inbounds API
  38. inbounds := api.Group("/inbounds")
  39. a.inboundController = NewInboundController(inbounds)
  40. // Server API
  41. server := api.Group("/server")
  42. a.serverController = NewServerController(server)
  43. NewCustomGeoController(api.Group("/custom-geo"), customGeo)
  44. // Extra routes
  45. api.GET("/backuptotgbot", a.BackuptoTgbot)
  46. }
  47. // BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
  48. func (a *APIController) BackuptoTgbot(c *gin.Context) {
  49. a.Tgbot.SendBackupToAdmins()
  50. }