package main import ( configcore "bitrix_balancer_api/core/config" clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" _ "bitrix_balancer_api/rest_admin_service/docs" adminhandler "bitrix_balancer_api/rest_admin_service/handlers/admin" approvalstepshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_steps" approvaltaskshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_tasks" approvalextrashandler "bitrix_balancer_api/rest_admin_service/handlers/approvalextras" approvalshandler "bitrix_balancer_api/rest_admin_service/handlers/approvals" authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth" dashboardhandler "bitrix_balancer_api/rest_admin_service/handlers/dashboard" departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments" nodeshandler "bitrix_balancer_api/rest_admin_service/handlers/flow_nodes" notificationshandler "bitrix_balancer_api/rest_admin_service/handlers/notification" permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission" profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile" roleshandler "bitrix_balancer_api/rest_admin_service/handlers/roles" categorieshandler "bitrix_balancer_api/rest_admin_service/handlers/topic_categories" topicexecutorshandler "bitrix_balancer_api/rest_admin_service/handlers/topic_executors" topicshandler "bitrix_balancer_api/rest_admin_service/handlers/topics" hierarchieshandler "bitrix_balancer_api/rest_admin_service/handlers/user_hierarchy" userroleshandler "bitrix_balancer_api/rest_admin_service/handlers/user_roles" usershandler "bitrix_balancer_api/rest_admin_service/handlers/users" typesm "bitrix_balancer_api/rest_admin_service/types" "errors" "fmt" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/cors" "github.com/go-chi/httprate" "github.com/sirupsen/logrus" httpSwagger "github.com/swaggo/http-swagger" "log" "net/http" "time" ) const ( readTimeout = 15 * time.Minute // Таймаут чтения writeTimeout = 15 * time.Minute // Таймаут записи idleTimeout = 15 * time.Minute // Таймаут бездействия rateLimit = 15 // Лимит запросов rateWindow = 1 * time.Second // Окно времени для лимита запросов ) // @title RusPet Admin API // @version 0.1 // @description API админ-панели для системы согласований // @description // @description ## Возможности // @description - Управление отделами, ролями и пользователями // @description - Настройка тем и категорий согласований // @description - Управление иерархией согласований // @description - Назначение исполнителей и прав // @description - Просмотр заявок и шагов согласования // @description // @description ## Аутентификация // @description Все защищённые эндпоинты требуют: // @description - `Authorization: Bearer ` — JWT токен администратора // @description - `ApiKey: ` — HMAC подпись для верификации клиента // @description - `X-Timestamp: ` — Unix timestamp (не старше 3 минут) // @description - `x-device-id: ` — ID устройства // // @host localhost:8080 // @BasePath / // // @securityDefinitions.apikey BearerAuth // @in header // @name Authorization // // @securityDefinitions.apikey ApiKeyAuth // @in header // @name ApiKey // // @securityDefinitions.apikey DeviceID // @in header // @name x-device-id // // @securityDefinitions.apikey Timestamp // @in header // @name X-Timestamp // // @contact.name Roman // @contact.email romanzabolotskij0@gmail.com func main() { err := initService() if err != nil { logrus.Errorln("🔴 failed to init common: ", err) } select {} } func initService() error { clientsExternal, err := getClientsExternal() if err != nil { logrus.Errorln("🔴 failed to load config: ", err) return err } ipc, err := initInternalProvider(clientsExternal) if err != nil { logrus.Errorln("🔴 failed to init internal provider: ", err) return err } router, err := initBaseApiRouter(ipc) if err != nil { logrus.Errorln("🔴 failed to init base api router: ", err) return err } if err := startRestApiServer(ipc, router); err != nil { logrus.Errorln("🔴 failed to start server: ", err) return err } return nil } func getClientsExternal() (clientcontrollers.ClientsExternal, error) { options := &configcore.ConfigLoadOptions{ Redis: true, Database: true, Telegram: true, Secrets: configcore.SecretsOptions{ AuthJWT: configcore.AuthJWTOptions{ Admin: true, }, AdminAccessCode: true, }, Server: configcore.ExposedServiceOptions{ RESTAdminService: true, }, } return clientcontrollers.ReturnClientsExternal(options) } func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*typesm.InternalProviderControl, error) { return &typesm.InternalProviderControl{ Config: clientsExternal.Config, RedisClient: clientsExternal.Redis, Database: clientsExternal.DB, TGBotClient: clientsExternal.Telegram, }, nil } func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error { serverPort := fmt.Sprintf("%d", ipc.Config.Server.RESTAdminService.PortRest) serverAddr := ":" + serverPort httpServer := &http.Server{ Addr: serverAddr, Handler: router, ReadTimeout: readTimeout, WriteTimeout: writeTimeout, IdleTimeout: idleTimeout, } log.Printf("✅ Starting server on %s", serverAddr) return httpServer.ListenAndServe() } func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) { router := chi.NewRouter() corsOptions := cors.New(cors.Options{ AllowedOrigins: ipc.Config.Server.RESTAdminService.Cors.AllowedOrigins, // Список разрешенных origin AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch, http.MethodOptions}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"}, ExposedHeaders: []string{"Link", "Cache-Control"}, AllowCredentials: false, MaxAge: 300, // Максимальное время жизни предварительных запросов в секундах }) router.Use(corsOptions.Handler) router.Use(middleware.RealIP) router.Use(middleware.Recoverer) // Добавляем ограничение по IP router.Use(httprate.LimitByIP(rateLimit, rateWindow)) if ipc.Database == nil { return nil, errors.New("failed_to_connect_db") } err := registerRoutes(router, ipc) if err != nil { return nil, err } return router, nil } // регистрирует маршруты func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) error { router.Get("/swagger/*", httpSwagger.Handler( httpSwagger.URL("/swagger/doc.json"), // URL к сгенерированному JSON httpSwagger.DeepLinking(true), httpSwagger.DocExpansion("none"), httpSwagger.DomID("swagger-ui"), )) // Слайс обработчиков маршрутов routeHandlers := []struct { name string handler func(chi.Router, *typesm.InternalProviderControl) error }{ {"admin", adminhandler.RegisterAdminRoutes}, {"auth", authhandler.RegisterAuthRoutes}, {"profile", profilehandler.RegisterProfileRoutes}, {"users", usershandler.RegisterUserRoutes}, {"departments", departmentshandler.RegisterDepartmentRoutes}, {"roles", roleshandler.RegisterRoleRoutes}, {"categories", categorieshandler.RegisterCategoryRoutes}, {"topics", topicshandler.RegisterTopicRoutes}, {"user-roles", userroleshandler.RegisterUserRoleRoutes}, {"hierarchies", hierarchieshandler.RegisterHierarchyRoutes}, {"topic-executors", topicexecutorshandler.RegisterTopicExecutorRoutes}, {"approvals", approvalshandler.RegisterApprovalRoutes}, {"approval-steps", approvalstepshandler.RegisterApprovalStepRoutes}, {"permissions", permissionshandler.RegisterPermissionRoutes}, {"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes}, {"dashboard", dashboardhandler.RegisterDashboardRoutes}, {"notifications", notificationshandler.RegisterNotificationRoutes}, {"flownodes", nodeshandler.RegisterFlowNodesRoutes}, {"approvalextras", approvalextrashandler.RegisterApprovalExtrasRoutes}, } // Регистрация всех маршрутов for _, rh := range routeHandlers { if errObj := rh.handler(router, ipc); errObj != nil { return errors.New(fmt.Sprintf("🔴 failed to register %s routes", rh.name)) } } // Вывод зарегистрированных маршрутов if err := printRoutes(router, ipc); err != nil { return errors.New(fmt.Sprintf("🔴 failed to print routes: %v", err)) } return nil } func printRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { logrus.Info(fmt.Sprintf("🩵 [ %s ] %s\n", method, route)) return nil }) if err != nil { return err } return nil }